You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@aries.apache.org by gn...@apache.org on 2016/04/11 14:05:36 UTC
[1/3] aries-rsa git commit: [ARIES-1526] Add a fast nio/protobuf
provider
Repository: aries-rsa
Updated Branches:
refs/heads/master 58bb694dc -> 62d835dec
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/util/ClassLoaderObjectInputStream.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/util/ClassLoaderObjectInputStream.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/util/ClassLoaderObjectInputStream.java
new file mode 100644
index 0000000..63138c0
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/util/ClassLoaderObjectInputStream.java
@@ -0,0 +1,86 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.util;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectStreamClass;
+import java.lang.reflect.Proxy;
+import java.util.HashMap;
+
+public class ClassLoaderObjectInputStream extends ObjectInputStream {
+
+ /** <p>Maps primitive type names to corresponding class objects.</p> */
+ private static final HashMap<String, Class> primClasses = new HashMap<String, Class>(8, 1.0F);
+
+ private ClassLoader classLoader;
+
+ public ClassLoaderObjectInputStream(InputStream in) throws IOException {
+ super(in);
+ }
+
+ public ClassLoader getClassLoader() {
+ return classLoader;
+ }
+
+ public void setClassLoader(ClassLoader classLoader) {
+ this.classLoader = classLoader;
+ }
+
+ protected Class resolveClass(ObjectStreamClass classDesc) throws IOException, ClassNotFoundException {
+ return load(classDesc.getName());
+ }
+
+ protected Class resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException {
+ Class[] cinterfaces = new Class[interfaces.length];
+ for (int i = 0; i < interfaces.length; i++) {
+ cinterfaces[i] = load(interfaces[i]);
+ }
+
+ try {
+ return Proxy.getProxyClass(classLoader, cinterfaces);
+ } catch (IllegalArgumentException e) {
+ throw new ClassNotFoundException(null, e);
+ }
+ }
+
+ private Class load(String className)
+ throws ClassNotFoundException {
+ try {
+ return Class.forName(className, false, classLoader);
+ } catch (ClassNotFoundException e) {
+ final Class clazz = primClasses.get(className);
+ if (clazz != null) {
+ return clazz;
+ } else {
+ throw e;
+ }
+ }
+ }
+
+ static {
+ primClasses.put("boolean", boolean.class);
+ primClasses.put("byte", byte.class);
+ primClasses.put("char", char.class);
+ primClasses.put("short", short.class);
+ primClasses.put("int", int.class);
+ primClasses.put("long", long.class);
+ primClasses.put("float", float.class);
+ primClasses.put("double", double.class);
+ primClasses.put("void", void.class);
+ }
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/util/IntrospectionSupport.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/util/IntrospectionSupport.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/util/IntrospectionSupport.java
new file mode 100755
index 0000000..1d31218
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/util/IntrospectionSupport.java
@@ -0,0 +1,362 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.util;
+
+import java.beans.PropertyEditor;
+import java.beans.PropertyEditorManager;
+import java.lang.reflect.Array;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+
+
+public final class IntrospectionSupport {
+
+ private IntrospectionSupport() {
+ }
+
+ public static boolean getProperties(Object target, Map props, String optionPrefix) {
+
+ boolean rc = false;
+ if (target == null) {
+ throw new IllegalArgumentException("target was null.");
+ }
+ if (props == null) {
+ throw new IllegalArgumentException("props was null.");
+ }
+
+ if (optionPrefix == null) {
+ optionPrefix = "";
+ }
+
+ Class<?> clazz = target.getClass();
+ Method[] methods = clazz.getMethods();
+ for (int i = 0; i < methods.length; i++) {
+ Method method = methods[i];
+ String name = method.getName();
+ Class<?> type = method.getReturnType();
+ Class<?> params[] = method.getParameterTypes();
+ if ((name.startsWith("is") || name.startsWith("get")) && params.length == 0 && type != null && isSettableType(type)) {
+
+ try {
+
+ Object value = method.invoke(target, new Object[] {});
+ if (value == null) {
+ continue;
+ }
+
+ String strValue = convertToString(value, type);
+ if (strValue == null) {
+ continue;
+ }
+ if (name.startsWith("get")) {
+ name = name.substring(3, 4).toLowerCase()
+ + name.substring(4);
+ } else {
+ name = name.substring(2, 3).toLowerCase()
+ + name.substring(3);
+ }
+ props.put(optionPrefix + name, strValue);
+ rc = true;
+
+ } catch (Throwable ignore) {
+ }
+
+ }
+ }
+
+ return rc;
+ }
+
+ public static boolean setProperties(Object target, Map<String, ?> props, String optionPrefix) {
+ boolean rc = false;
+ if (target == null) {
+ throw new IllegalArgumentException("target was null.");
+ }
+ if (props == null) {
+ throw new IllegalArgumentException("props was null.");
+ }
+
+ for (Iterator<String> iter = props.keySet().iterator(); iter.hasNext();) {
+ String name = iter.next();
+ if (name.startsWith(optionPrefix)) {
+ Object value = props.get(name);
+ name = name.substring(optionPrefix.length());
+ if (setProperty(target, name, value)) {
+ iter.remove();
+ rc = true;
+ }
+ }
+ }
+ return rc;
+ }
+
+ public static Map<String, Object> extractProperties(Map props, String optionPrefix) {
+ if (props == null) {
+ throw new IllegalArgumentException("props was null.");
+ }
+
+ HashMap<String, Object> rc = new HashMap<String, Object>(props.size());
+
+ for (Iterator<Entry> iter = props.entrySet().iterator(); iter.hasNext();) {
+ Entry entry = iter.next();
+ String name = (String)entry.getKey();
+ if (name.startsWith(optionPrefix)) {
+ name = name.substring(optionPrefix.length());
+ rc.put(name, entry.getValue());
+ iter.remove();
+ }
+ }
+
+ return rc;
+ }
+
+ public static boolean setProperties(Object target, Map props) {
+ boolean rc = false;
+
+ if (target == null) {
+ throw new IllegalArgumentException("target was null.");
+ }
+ if (props == null) {
+ throw new IllegalArgumentException("props was null.");
+ }
+
+ for (Iterator<Entry> iter = props.entrySet().iterator(); iter.hasNext();) {
+ Map.Entry entry = iter.next();
+ if (setProperty(target, (String)entry.getKey(), entry.getValue())) {
+ iter.remove();
+ rc = true;
+ }
+ }
+
+ return rc;
+ }
+
+ public static Class<?> getPropertyType(Object target, String name) {
+ Class<?> clazz = target.getClass();
+ Method setter = findSetterMethod(clazz, name);
+ if (setter == null) {
+ return null;
+ }
+ return setter.getParameterTypes()[0];
+ }
+
+ public static boolean setProperty(Object target, String name, Object value) {
+ try {
+ Class<?> clazz = target.getClass();
+ Method setter = findSetterMethod(clazz, name);
+ if (setter == null) {
+ return false;
+ }
+
+ // If the type is null or it matches the needed type, just use the
+ // value directly
+ if (value == null || value.getClass() == setter.getParameterTypes()[0]) {
+ setter.invoke(target, new Object[] {value});
+ } else {
+ // We need to convert it
+ setter.invoke(target, new Object[] {convert(value, setter.getParameterTypes()[0])});
+ }
+ return true;
+ } catch (Throwable ignore) {
+ return false;
+ }
+ }
+
+ private static Object convert(Object value, Class<?> type) {
+ if( type.isArray() ) {
+ if( value.getClass().isArray() ) {
+ int length = Array.getLength(value);
+ Class<?> componentType = type.getComponentType();
+ Object rc = Array.newInstance(componentType, length);
+ for (int i = 0; i < length; i++) {
+ Object o = Array.get(value, i);
+ Array.set(rc, i, convert(o, componentType));
+ }
+ return rc;
+ }
+ }
+ PropertyEditor editor = PropertyEditorManager.findEditor(type);
+ if (editor != null) {
+ editor.setAsText(value.toString());
+ return editor.getValue();
+ }
+ return null;
+ }
+
+ public static String convertToString(Object value, Class<?> type) {
+ PropertyEditor editor = PropertyEditorManager.findEditor(type);
+ if (editor != null) {
+ editor.setValue(value);
+ return editor.getAsText();
+ }
+ return null;
+ }
+
+ private static Method findSetterMethod(Class<?> clazz, String name) {
+ // Build the method name.
+ name = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
+ Method[] methods = clazz.getMethods();
+ for (int i = 0; i < methods.length; i++) {
+ Method method = methods[i];
+ Class<?> params[] = method.getParameterTypes();
+ if (method.getName().equals(name) && params.length == 1 ) {
+ return method;
+ }
+ }
+ return null;
+ }
+
+ private static boolean isSettableType(Class<?> clazz) {
+ if (PropertyEditorManager.findEditor(clazz) != null) {
+ return true;
+ }
+
+ return false;
+ }
+
+ public static String toString(Object target) {
+ return toString(target, Object.class, null, (String[])null);
+ }
+
+ public static String toString(Object target, String...fields) {
+ return toString(target, Object.class, null, fields);
+ }
+
+ public static String toString(Object target, Class<?> stopClass) {
+ return toString(target, stopClass, null, (String[])null);
+ }
+
+ public static String toString(Object target, Map<String, Object> overrideFields, String...fields) {
+ return toString(target, Object.class, overrideFields, fields);
+ }
+
+ public static String toString(Object target, Class<?> stopClass, Map<String, Object> overrideFields, String ... fields) {
+ try {
+ LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
+ addFields(target, target.getClass(), stopClass, map);
+ if (overrideFields != null) {
+ for(String key : overrideFields.keySet()) {
+ Object value = overrideFields.get(key);
+ map.put(key, value);
+ }
+ }
+
+ if( fields!=null ) {
+ map.keySet().retainAll(Arrays.asList(fields));
+ }
+
+ boolean useMultiLine=false;
+ LinkedHashMap<String, String> props = new LinkedHashMap<String, String>();
+ for (Entry<String, Object> entry : map.entrySet()) {
+ String key = entry.getKey();
+ String value = null;
+ if( entry.getValue() !=null ) {
+ value = entry.getValue().toString();
+ if( value!=null && ( value.indexOf('\n')>=0 || (key.length()+value.length())>70 ) ) {
+ useMultiLine=true;
+ }
+ }
+ props.put(key, value);
+ }
+
+ StringBuffer buffer = new StringBuffer();
+ if( useMultiLine) {
+ buffer.append("{\n");
+ boolean first = true;
+ for (Entry<String, String> entry : props.entrySet()) {
+ if (first) {
+ first = false;
+ } else {
+ buffer.append(",\n");
+ }
+ buffer.append(" ");
+ buffer.append(entry.getKey());
+ buffer.append(": ");
+ buffer.append(StringSupport.indent(entry.getValue(), 2));
+ }
+ buffer.append("\n}");
+ } else {
+ buffer.append("{");
+ boolean first = true;
+ for (Entry<String, String> entry : props.entrySet()) {
+ if (first) {
+ first = false;
+ } else {
+ buffer.append(", ");
+ }
+ buffer.append(entry.getKey());
+ buffer.append(": ");
+ String value = entry.getValue();
+ buffer.append(value);
+ }
+ buffer.append("}");
+ }
+ return buffer.toString();
+ } catch (Throwable e) {
+ e.printStackTrace();
+ return "Could not toString: "+e.toString();
+ }
+ }
+
+
+ public static String simpleName(Class<?> clazz) {
+ String name = clazz.getName();
+ int p = name.lastIndexOf(".");
+ if (p >= 0) {
+ name = name.substring(p + 1);
+ }
+ return name;
+ }
+
+ private static void addFields(Object target, Class<?> startClass, Class<?> stopClass, LinkedHashMap<String, Object> map) {
+
+ if (startClass != stopClass) {
+ addFields(target, startClass.getSuperclass(), stopClass, map);
+ }
+
+ Field[] fields = startClass.getDeclaredFields();
+ for (int i = 0; i < fields.length; i++) {
+ Field field = fields[i];
+ if (Modifier.isStatic(field.getModifiers())) {
+ continue;
+ }
+
+ try {
+ field.setAccessible(true);
+ Object o = field.get(target);
+ if (o != null && o.getClass().isArray()) {
+ try {
+ o = Arrays.asList((Object[])o);
+ } catch (Throwable e) {
+ }
+ }
+ map.put(field.getName(), o);
+ } catch (Throwable e) {
+ e.printStackTrace();
+ }
+ }
+
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/util/StringSupport.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/util/StringSupport.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/util/StringSupport.java
new file mode 100644
index 0000000..a8e0cd7
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/util/StringSupport.java
@@ -0,0 +1,40 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.util;
+
+import java.util.Arrays;
+
+/**
+ * Helper class to hold common text/string manipulation methods.
+ *
+ */
+public class StringSupport {
+
+ public static String indent(String value, int spaces) {
+ if( value == null ) {
+ return null;
+ }
+ String indent = fillString(spaces, ' ');
+ return value.replaceAll("(\\r?\\n)", "$1"+indent);
+ }
+
+ public static String fillString(int count, char character) {
+ char t[] = new char[count];
+ Arrays.fill(t, character);
+ return new String(t);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/util/URISupport.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/util/URISupport.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/util/URISupport.java
new file mode 100755
index 0000000..bed7923
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/util/URISupport.java
@@ -0,0 +1,332 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.util;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ */
+public class URISupport {
+
+ public static class CompositeData {
+ private String host;
+ private String scheme;
+ private String path;
+ private URI components[];
+ private Map<String, String> parameters;
+ private String fragment;
+
+ public URI[] getComponents() {
+ return components;
+ }
+
+ public String getFragment() {
+ return fragment;
+ }
+
+ public Map<String, String> getParameters() {
+ return parameters;
+ }
+
+ public String getScheme() {
+ return scheme;
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ public String getHost() {
+ return host;
+ }
+
+ public URI toURI() throws URISyntaxException {
+ StringBuffer sb = new StringBuffer();
+ if (scheme != null) {
+ sb.append(scheme);
+ sb.append(':');
+ }
+
+ if (host != null && host.length() != 0) {
+ sb.append(host);
+ } else {
+ sb.append('(');
+ for (int i = 0; i < components.length; i++) {
+ if (i != 0) {
+ sb.append(',');
+ }
+ sb.append(components[i].toString());
+ }
+ sb.append(')');
+ }
+
+ if (path != null) {
+ sb.append('/');
+ sb.append(path);
+ }
+ if (!parameters.isEmpty()) {
+ sb.append("?");
+ sb.append(createQueryString(parameters));
+ }
+ if (fragment != null) {
+ sb.append("#");
+ sb.append(fragment);
+ }
+ return new URI(sb.toString());
+ }
+ }
+
+ public static Map<String, String> parseQuery(String uri) throws URISyntaxException {
+ try {
+ Map<String, String> rc = new HashMap<String, String>();
+ if (uri != null) {
+ String[] parameters = uri.split("&");
+ for (int i = 0; i < parameters.length; i++) {
+ int p = parameters[i].indexOf("=");
+ if (p >= 0) {
+ String name = URLDecoder.decode(parameters[i].substring(0, p), "UTF-8");
+ String value = URLDecoder.decode(parameters[i].substring(p + 1), "UTF-8");
+ rc.put(name, value);
+ } else {
+ rc.put(parameters[i], null);
+ }
+ }
+ }
+ return rc;
+ } catch (UnsupportedEncodingException e) {
+ throw (URISyntaxException)new URISyntaxException(e.toString(), "Invalid encoding").initCause(e);
+ }
+ }
+
+ public static Map<String, String> parseParameters(URI uri) throws URISyntaxException {
+ return uri.getQuery() == null ? emptyMap() : parseQuery(stripPrefix(uri.getQuery(), "?"));
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Map<String, String> emptyMap() {
+ return Collections.EMPTY_MAP;
+ }
+
+ /**
+ * Removes any URI query from the given uri
+ */
+ public static URI removeQuery(URI uri) throws URISyntaxException {
+ return createURIWithQuery(uri, null);
+ }
+
+ /**
+ * Creates a URI with the given query
+ */
+ public static URI createURIWithQuery(URI uri, String query) throws URISyntaxException {
+ return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(),
+ query, uri.getFragment());
+ }
+
+ public static CompositeData parseComposite(URI uri) throws URISyntaxException {
+
+ CompositeData rc = new CompositeData();
+ rc.scheme = uri.getScheme();
+ String ssp = stripPrefix(uri.getSchemeSpecificPart().trim(), "//").trim();
+
+ parseComposite(uri, rc, ssp);
+
+ rc.fragment = uri.getFragment();
+ return rc;
+ }
+
+ /**
+ * @param uri
+ * @param rc
+ * @param ssp
+ * @throws URISyntaxException
+ */
+ private static void parseComposite(URI uri, CompositeData rc, String ssp) throws URISyntaxException {
+ String componentString;
+ String params;
+
+ if (!checkParenthesis(ssp)) {
+ throw new URISyntaxException(uri.toString(), "Not a matching number of '(' and ')' parenthesis");
+ }
+
+ int p;
+ int intialParen = ssp.indexOf("(");
+ if (intialParen == 0) {
+ rc.host = ssp.substring(0, intialParen);
+ p = rc.host.indexOf("/");
+ if (p >= 0) {
+ rc.path = rc.host.substring(p);
+ rc.host = rc.host.substring(0, p);
+ }
+ p = ssp.lastIndexOf(")");
+ componentString = ssp.substring(intialParen + 1, p);
+ params = ssp.substring(p + 1).trim();
+
+ } else {
+ componentString = ssp;
+ params = "";
+ }
+
+ String components[] = splitComponents(componentString);
+ rc.components = new URI[components.length];
+ for (int i = 0; i < components.length; i++) {
+ rc.components[i] = new URI(components[i].trim());
+ }
+
+ p = params.indexOf("?");
+ if (p >= 0) {
+ if (p > 0) {
+ rc.path = stripPrefix(params.substring(0, p), "/");
+ }
+ rc.parameters = parseQuery(params.substring(p + 1));
+ } else {
+ if (params.length() > 0) {
+ rc.path = stripPrefix(params, "/");
+ }
+ rc.parameters = emptyMap();
+ }
+ }
+
+ /**
+ * @param str
+ * @return
+ */
+ private static String[] splitComponents(String str) {
+ List<String> l = new ArrayList<String>();
+
+ int last = 0;
+ int depth = 0;
+ char chars[] = str.toCharArray();
+ for (int i = 0; i < chars.length; i++) {
+ switch (chars[i]) {
+ case '(':
+ depth++;
+ break;
+ case ')':
+ depth--;
+ break;
+ case ',':
+ if (depth == 0) {
+ String s = str.substring(last, i);
+ l.add(s);
+ last = i + 1;
+ }
+ break;
+ default:
+ }
+ }
+
+ String s = str.substring(last);
+ if (s.length() != 0) {
+ l.add(s);
+ }
+
+ String rc[] = new String[l.size()];
+ l.toArray(rc);
+ return rc;
+ }
+
+ public static String stripPrefix(String value, String prefix) {
+ if (value.startsWith(prefix)) {
+ return value.substring(prefix.length());
+ }
+ return value;
+ }
+
+ public static URI stripScheme(URI uri) throws URISyntaxException {
+ return new URI(stripPrefix(uri.getSchemeSpecificPart().trim(), "//"));
+ }
+
+ public static String createQueryString(Map<String,String> options) throws URISyntaxException {
+ try {
+ if (options.size() > 0) {
+ StringBuffer rc = new StringBuffer();
+ boolean first = true;
+ for (Map.Entry<String,String> entry : options.entrySet()) {
+ if (first) {
+ first = false;
+ } else {
+ rc.append("&");
+ }
+ String key = entry.getKey();
+ String value = entry.getValue();
+ rc.append(URLEncoder.encode(key, "UTF-8"));
+ rc.append("=");
+ rc.append(URLEncoder.encode(value, "UTF-8"));
+ }
+ return rc.toString();
+ } else {
+ return "";
+ }
+ } catch (UnsupportedEncodingException e) {
+ throw (URISyntaxException)new URISyntaxException(e.toString(), "Invalid encoding").initCause(e);
+ }
+ }
+
+ /**
+ * Creates a URI from the original URI and the remaining paramaters
+ *
+ * @throws URISyntaxException
+ */
+ public static URI createRemainingURI(URI originalURI, Map params) throws URISyntaxException {
+ String s = createQueryString(params);
+ if (s.length() == 0) {
+ s = null;
+ }
+ return createURIWithQuery(originalURI, s);
+ }
+
+ public static URI changeScheme(URI bindAddr, String scheme) throws URISyntaxException {
+ return new URI(scheme, bindAddr.getUserInfo(), bindAddr.getHost(), bindAddr.getPort(), bindAddr
+ .getPath(), bindAddr.getQuery(), bindAddr.getFragment());
+ }
+
+ public static boolean checkParenthesis(String str) {
+ boolean result = true;
+ if (str != null) {
+ int open = 0;
+ int closed = 0;
+
+ int i = 0;
+ while ((i = str.indexOf('(', i)) >= 0) {
+ i++;
+ open++;
+ }
+ i = 0;
+ while ((i = str.indexOf(')', i)) >= 0) {
+ i++;
+ closed++;
+ }
+ result = open == closed;
+ }
+ return result;
+ }
+
+ public int indexOfParenthesisMatch(String str) {
+ int result = -1;
+
+ return result;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/util/UuidGenerator.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/util/UuidGenerator.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/util/UuidGenerator.java
new file mode 100644
index 0000000..7f09e1a
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/util/UuidGenerator.java
@@ -0,0 +1,178 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.util;
+
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.UnknownHostException;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * A unique ID generator which is a fast implementation based on
+ * how <a href="http://activemq.apache.org/>Apache ActiveMQ</a> generates its UUID.
+ * <p/>
+ */
+public class UuidGenerator {
+
+ private static final Logger LOG = LoggerFactory.getLogger(UuidGenerator.class);
+ private static final String UNIQUE_STUB;
+ private static int instanceCount;
+ private static String hostName;
+ private String seed;
+ private AtomicLong sequence = new AtomicLong(1);
+ private int length;
+
+ private static UuidGenerator instance = null;
+ static {
+ String stub = "";
+ boolean canAccessSystemProps = true;
+ try {
+ SecurityManager sm = System.getSecurityManager();
+ if (sm != null) {
+ sm.checkPropertiesAccess();
+ }
+ } catch (SecurityException se) {
+ canAccessSystemProps = false;
+ }
+
+ if (canAccessSystemProps) {
+ try {
+ hostName = getLocalHostName();
+ ServerSocket ss = new ServerSocket(0);
+ stub = "-" + ss.getLocalPort() + "-" + System.currentTimeMillis() + "-";
+ Thread.sleep(100);
+ ss.close();
+ } catch (Exception ioe) {
+ LOG.warn("could not generate unique stub", ioe);
+ }
+ } else {
+ hostName = "localhost";
+ stub = "-1-" + System.currentTimeMillis() + "-";
+ }
+ UNIQUE_STUB = stub;
+ }
+
+ /**
+ * Construct an IdGenerator
+ */
+ private UuidGenerator(String prefix) {
+ synchronized (UNIQUE_STUB) {
+ int hashValue = prefix.hashCode();
+ if (hashValue < 0) {
+ hashValue = - hashValue;
+ }
+ this.seed = hashValue + UNIQUE_STUB + (instanceCount++) + ":";
+ this.seed = generateSanitizedId(this.seed);
+ this.length = this.seed.length() + ("" + Long.MAX_VALUE).length();
+ }
+ }
+
+ private UuidGenerator() {
+ this("ID:" + hostName);
+ }
+
+ /**
+ * As we have to find the hostname as a side-affect of generating a unique
+ * stub, we allow it's easy retrevial here
+ *
+ * @return the local host name
+ */
+
+ public static String getHostName() {
+ return hostName;
+ }
+
+
+ /**
+ * Generate a unqiue id
+ *
+ * @return a unique id
+ */
+
+ private String generateId() {
+ StringBuilder sb = new StringBuilder(length);
+ sb.append(seed);
+ sb.append(sequence.getAndIncrement());
+ return sb.toString();
+ }
+
+ /**
+ * Ensures that the id is friendly for a URL or file system
+ *
+ * @param id the unique id
+ * @return the id as file friendly id
+ */
+ public static String generateSanitizedId(String id) {
+ id = id.replace(':', '-');
+ id = id.replace('_', '-');
+ id = id.replace('.', '-');
+ id = id.replace('/', '-');
+ return id;
+ }
+
+
+ public static String getUUID() {
+ return getInstance().generateId();
+ }
+
+ public static UuidGenerator getInstance() {
+ if (instance == null) {
+ instance = new UuidGenerator();
+ }
+ return instance;
+ }
+
+ /**
+ * When using the {@link java.net.InetAddress#getHostName()} method in an
+ * environment where neither a proper DNS lookup nor an <tt>/etc/hosts</tt>
+ * entry exists for a given host, the following exception will be thrown:
+ * <code>
+ * java.net.UnknownHostException: <hostname>: <hostname>
+ * at java.net.InetAddress.getLocalHost(InetAddress.java:1425)
+ * ...
+ * </code>
+ * Instead of just throwing an UnknownHostException and giving up, this
+ * method grabs a suitable hostname from the exception and prevents the
+ * exception from being thrown. If a suitable hostname cannot be acquired
+ * from the exception, only then is the <tt>UnknownHostException</tt> thrown.
+ *
+ * @return The hostname
+ * @throws UnknownHostException
+ * @see {@link java.net.InetAddress#getLocalHost()}
+ * @see {@link java.net.InetAddress#getHostName()}
+ */
+ static String getLocalHostName() throws UnknownHostException {
+ try {
+ return (InetAddress.getLocalHost()).getHostName();
+ } catch (UnknownHostException uhe) {
+ String host = uhe.getMessage(); // host = "hostname: hostname"
+ if (host != null) {
+ int colon = host.indexOf(':');
+ if (colon > 0) {
+ return host.substring(0, colon);
+ }
+ }
+ throw uhe;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/test/java/org/apache/aries/rsa/provider/fastbin/InvocationTest.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/test/java/org/apache/aries/rsa/provider/fastbin/InvocationTest.java b/provider/fastbin/src/test/java/org/apache/aries/rsa/provider/fastbin/InvocationTest.java
new file mode 100644
index 0000000..960210b
--- /dev/null
+++ b/provider/fastbin/src/test/java/org/apache/aries/rsa/provider/fastbin/InvocationTest.java
@@ -0,0 +1,581 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Proxy;
+import java.lang.reflect.UndeclaredThrowableException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.aries.rsa.provider.fastbin.api.AsyncCallback;
+import org.apache.aries.rsa.provider.fastbin.api.AsyncCallbackFuture;
+import org.apache.aries.rsa.provider.fastbin.api.Dispatched;
+import org.apache.aries.rsa.provider.fastbin.api.ProtobufSerializationStrategy;
+import org.apache.aries.rsa.provider.fastbin.api.Serialization;
+import org.apache.aries.rsa.provider.fastbin.api.SerializationStrategy;
+import org.apache.aries.rsa.provider.fastbin.io.ServerInvoker;
+import org.apache.aries.rsa.provider.fastbin.tcp.ClientInvokerImpl;
+import org.apache.aries.rsa.provider.fastbin.tcp.ServerInvokerImpl;
+import org.apache.aries.rsa.provider.fastbin.test.StringValue;
+import org.fusesource.hawtdispatch.Dispatch;
+import org.fusesource.hawtdispatch.DispatchQueue;
+import org.junit.Test;
+
+import static org.fusesource.hawtdispatch.Dispatch.createQueue;
+import static org.junit.Assert.assertEquals;
+
+public class InvocationTest {
+ final static long MILLIS_IN_A_NANO = TimeUnit.MILLISECONDS.toNanos(1);
+ final static long SECONDS_IN_A_NANO = TimeUnit.SECONDS.toNanos(1);
+
+ final int BENCHMARK_CLIENTS = 100;
+ final int BENCHMARK_INVOCATIONS_PER_CLIENT = 1000;
+
+
+ @Test(timeout=30*1000)
+ public void testInvoke() throws Exception {
+
+ DispatchQueue queue = Dispatch.createQueue();
+ HashMap<String, SerializationStrategy> map = new HashMap<String, SerializationStrategy>();
+ map.put("protobuf", new ProtobufSerializationStrategy());
+
+ ServerInvokerImpl server = new ServerInvokerImpl("tcp://localhost:0", queue, map);
+ server.start();
+
+ ClientInvokerImpl client = new ClientInvokerImpl(queue, map);
+ client.start();
+
+ try {
+ server.registerService("service-id", new ServerInvoker.ServiceFactory() {
+ public Object get() {
+ return new HelloImpl();
+ }
+ public void unget() {
+ }
+ }, HelloImpl.class.getClassLoader());
+
+
+ InvocationHandler handler = client.getProxy(server.getConnectAddress(), "service-id", HelloImpl.class.getClassLoader());
+ Hello hello = (Hello) Proxy.newProxyInstance(HelloImpl.class.getClassLoader(), new Class[] { Hello.class }, handler);
+
+ assertEquals("Hello Fabric!", hello.hello("Fabric"));
+ assertEquals("Hello World!", hello.helloworld());
+
+ // Verification the we can pick the right overloaded method even if using a mixure
+ // of primitives / objects and array dimensions.
+ assertEquals('a', hello.mix(0));
+ assertEquals('b', hello.mix(new int[]{0}));
+ assertEquals('c', hello.mix(new Integer(0)));
+ assertEquals('d', hello.mix(new Integer[]{new Integer(0)}));
+ assertEquals('e', hello.mix(new int[0][0]));
+ assertEquals('f', hello.mix(new Integer[0][0]));
+
+ AsyncCallbackFuture<String> future1 = new AsyncCallbackFuture<String>();
+ hello.hello("Hiram", future1);
+ assertEquals("Hello Hiram!", future1.get(2, TimeUnit.SECONDS));
+
+ assertEquals("Hello Hiram!", hello.protobuf(stringValue("Hiram")).getValue());
+
+ AsyncCallbackFuture<StringValue.Getter> future2 = new AsyncCallbackFuture<StringValue.Getter>();
+ hello.protobuf(stringValue("Hiram Async"), future2);
+ assertEquals("Hello Hiram Async!", future2.get(2, TimeUnit.SECONDS).getValue());
+
+ }
+ finally {
+ server.stop();
+ client.stop();
+ }
+ }
+
+ @Test(timeout=30*1000)
+ public void testOverflowAsync() throws Exception {
+
+ DispatchQueue queue = Dispatch.createQueue();
+ HashMap<String, SerializationStrategy> map = new HashMap<String, SerializationStrategy>();
+ map.put("protobuf", new ProtobufSerializationStrategy());
+
+ ServerInvokerImpl server = new ServerInvokerImpl("tcp://localhost:0", queue, map);
+ server.start();
+
+ ClientInvokerImpl client = new ClientInvokerImpl(queue, map);
+ client.start();
+
+ try {
+ server.registerService("service-id", new ServerInvoker.ServiceFactory() {
+ public Object get() {
+ return new HelloImpl();
+ }
+ public void unget() {
+ }
+ }, HelloImpl.class.getClassLoader());
+
+
+ InvocationHandler handler = client.getProxy(server.getConnectAddress(), "service-id", HelloImpl.class.getClassLoader());
+ Hello hello = (Hello) Proxy.newProxyInstance(HelloImpl.class.getClassLoader(), new Class[] { Hello.class }, handler);
+
+ char[] chars = new char[65*1024];
+ String payload = new String(chars);
+
+ final List<AsyncCallbackFuture<String>> futures = new ArrayList<AsyncCallbackFuture<String>>();
+ for(int i = 0; i < 100; i++) {
+ AsyncCallbackFuture<String> future = new AsyncCallbackFuture<String>();
+ hello.hello(payload, future);
+ futures.add(future);
+ }
+
+ for(Future<String> f : futures) {
+ f.get(3, TimeUnit.SECONDS);
+ }
+// future2.get(2, TimeUnit.SECONDS);
+ //assertEquals("Hello Hiram!", future1.get(2, TimeUnit.SECONDS));
+
+ //assertEquals("Hello Hiram!", hello.protobuf(stringValue(payload)).getValue());
+ }
+ finally {
+ server.stop();
+ client.stop();
+ }
+ }
+
+ @Test(timeout=30*1000)
+ public void testOverflow() throws Exception {
+
+ DispatchQueue queue = Dispatch.createQueue();
+ HashMap<String, SerializationStrategy> map = new HashMap<String, SerializationStrategy>();
+ map.put("protobuf", new ProtobufSerializationStrategy());
+
+ ServerInvokerImpl server = new ServerInvokerImpl("tcp://localhost:0", queue, map);
+ server.start();
+
+ ClientInvokerImpl client = new ClientInvokerImpl(queue, map);
+ client.start();
+
+ try {
+ server.registerService("service-id", new ServerInvoker.ServiceFactory() {
+ public Object get() {
+ return new HelloImpl();
+ }
+ public void unget() {
+ }
+ }, HelloImpl.class.getClassLoader());
+
+
+ InvocationHandler handler = client.getProxy(server.getConnectAddress(), "service-id", HelloImpl.class.getClassLoader());
+ final Hello hello = (Hello) Proxy.newProxyInstance(HelloImpl.class.getClassLoader(), new Class[] { Hello.class }, handler);
+
+ final AtomicInteger requests = new AtomicInteger(0);
+ final AtomicInteger responses = new AtomicInteger(0);
+ final AtomicInteger failures = new AtomicInteger(0);
+
+ char[] chars = new char[65*1024];
+ final String payload = new String(chars);
+
+ Thread[] threads = new Thread[BENCHMARK_CLIENTS];
+ for (int t = 0; t < BENCHMARK_CLIENTS; t++) {
+ threads[t] = new Thread() {
+ public void run() {
+ try {
+ requests.incrementAndGet();
+
+ hello.hello(payload);
+
+ responses.incrementAndGet();
+ } catch (Throwable t) {
+ failures.incrementAndGet();
+ }
+ }
+ };
+ threads[t].start();
+ }
+
+ for (int t = 0; t < BENCHMARK_CLIENTS; t++) {
+ threads[t].join(10000);
+ System.err.format("REQUEST: %d of %d%n", requests.get(), BENCHMARK_CLIENTS);
+ System.err.format("RESPONSES: %d of %d%n", responses.get(), BENCHMARK_CLIENTS);
+ assertEquals(threads[t].isAlive(), false);
+ }
+
+ assertEquals(BENCHMARK_CLIENTS, requests.get());
+ assertEquals(BENCHMARK_CLIENTS, responses.get());
+ assertEquals(0, failures.get());
+
+ }
+ finally {
+ server.stop();
+ client.stop();
+ }
+ }
+
+ @Test(timeout=30*1000)
+ public void testNoOverflow() throws Exception {
+
+ DispatchQueue queue = Dispatch.createQueue();
+ HashMap<String, SerializationStrategy> map = new HashMap<String, SerializationStrategy>();
+ map.put("protobuf", new ProtobufSerializationStrategy());
+
+ ServerInvokerImpl server = new ServerInvokerImpl("tcp://localhost:0", queue, map);
+ server.start();
+
+ ClientInvokerImpl client = new ClientInvokerImpl(queue, map);
+ client.start();
+
+ try {
+ server.registerService("service-id", new ServerInvoker.ServiceFactory() {
+ public Object get() {
+ return new HelloImpl();
+ }
+ public void unget() {
+ }
+ }, HelloImpl.class.getClassLoader());
+
+
+ InvocationHandler handler = client.getProxy(server.getConnectAddress(), "service-id", HelloImpl.class.getClassLoader());
+ Hello hello = (Hello) Proxy.newProxyInstance(HelloImpl.class.getClassLoader(), new Class[] { Hello.class }, handler);
+
+ char[] chars = new char[65*1024];
+ String payload = new String(chars);
+
+ for(int i = 0; i < 100; i++) {
+ hello.hello(payload);
+ }
+ }
+ finally {
+ server.stop();
+ client.stop();
+ }
+ }
+
+ @Test(timeout=30*1000)
+ public void testUnderLoadSyncObject() throws Exception {
+ HashMap<String, SerializationStrategy> map = new HashMap<String, SerializationStrategy>();
+
+ DispatchQueue queue = Dispatch.createQueue();
+ ServerInvokerImpl server = new ServerInvokerImpl("tcp://localhost:0", queue, map);
+ server.start();
+ ClientInvokerImpl client = new ClientInvokerImpl(queue, map);
+ client.start();
+
+ try {
+ final HelloImpl helloImpl = new HelloImpl();
+ server.registerService("service-id", new ServerInvoker.ServiceFactory() {
+ public Object get() {
+ return helloImpl;
+ }
+ public void unget() {
+ }
+ }, HelloImpl.class.getClassLoader());
+
+
+ InvocationHandler handler = client.getProxy(server.getConnectAddress(), "service-id", HelloImpl.class.getClassLoader());
+
+ final Hello hello = (Hello) Proxy.newProxyInstance(HelloImpl.class.getClassLoader(), new Class[] { Hello.class }, handler);
+
+ assertEquals("Hello World!", hello.helloworld());
+
+ final AtomicInteger requests = new AtomicInteger(0);
+ final AtomicInteger failures = new AtomicInteger(0);
+ final long latencies[] = new long[BENCHMARK_CLIENTS * BENCHMARK_INVOCATIONS_PER_CLIENT];
+
+ final long start = System.nanoTime();
+ Thread[] threads = new Thread[BENCHMARK_CLIENTS];
+ for (int t = 0; t < BENCHMARK_CLIENTS; t++) {
+ final int thread_idx = t;
+ threads[t] = new Thread() {
+ public void run() {
+ for (int i = 0; i < BENCHMARK_INVOCATIONS_PER_CLIENT; i++) {
+ try {
+ requests.incrementAndGet();
+ String response;
+
+ final long start = System.nanoTime();
+ response = hello.hello("Fabric");
+ final long end = System.nanoTime();
+ latencies[(thread_idx* BENCHMARK_INVOCATIONS_PER_CLIENT)+i] = end-start;
+
+ assertEquals("Hello Fabric!", response);
+ } catch (Throwable t) {
+ latencies[(thread_idx* BENCHMARK_INVOCATIONS_PER_CLIENT)+i] = -1;
+ failures.incrementAndGet();
+ if (t instanceof UndeclaredThrowableException) {
+ t = ((UndeclaredThrowableException) t).getUndeclaredThrowable();
+ }
+ System.err.println("Error: " + t.getClass().getName() + (t.getMessage() != null ? " (" + t.getMessage() + ")" : ""));
+ }
+ }
+ }
+ };
+ threads[t].start();
+ }
+
+ for (int t = 0; t < BENCHMARK_CLIENTS; t++) {
+ threads[t].join();
+ }
+ final long end = System.nanoTime();
+
+ long latency_sum = 0;
+ for (int t = 0; t < latencies.length; t++) {
+ if( latencies[t] != -1 ) {
+ latency_sum += latencies[t];
+ }
+ }
+ double latency_avg = ((latency_sum * 1.0d)/requests.get()) / MILLIS_IN_A_NANO;
+ double request_rate = ((requests.get() * 1.0d)/(end-start)) * SECONDS_IN_A_NANO;
+
+ System.err.println(String.format("Requests/Second: %,.2f", request_rate));
+ System.err.println(String.format("Average request latency: %,.2f ms", latency_avg));
+ System.err.println("Error Ratio: " + failures.get() + " / " + requests.get());
+ }
+ finally {
+ server.stop();
+ client.stop();
+ }
+ }
+
+
+ class AsyncClient implements AsyncCallback<StringValue.Getter> {
+
+ final int thread_idx;
+ final int nbInvocationsPerThread;
+ final long latencies[];
+ final AtomicInteger requests;
+ final AtomicInteger failures;
+ final Hello hello;
+
+ final DispatchQueue queue = createQueue();
+ final StringValue.Buffer msg = stringValue("Fabric").freeze();
+ final CountDownLatch done = new CountDownLatch(1);
+
+ int i;
+ long start;
+
+
+ AsyncClient(int thread_idx, int nbInvocationsPerThread, Hello hello, AtomicInteger failures, AtomicInteger requests, long[] latencies) {
+ this.failures = failures;
+ this.requests = requests;
+ this.nbInvocationsPerThread = nbInvocationsPerThread;
+ this.latencies = latencies;
+ this.hello = hello;
+ this.thread_idx = thread_idx;
+ }
+
+ void start() {
+ queue.execute(new Runnable() {
+ public void run() {
+ sendNext();
+ }
+ });
+ }
+
+ void join() throws InterruptedException {
+ done.await(10, TimeUnit.SECONDS);
+ }
+
+ private void sendNext() {
+ if( i < nbInvocationsPerThread ) {
+ requests.incrementAndGet();
+ start = System.nanoTime();
+ hello.protobuf(msg, this);
+ } else {
+ done.countDown();
+ }
+ }
+
+ public void onSuccess(StringValue.Getter result) {
+ latencies[(thread_idx*nbInvocationsPerThread)+i] = System.nanoTime() -start;
+ i++;
+ sendNext();
+ }
+
+ public void onFailure(Throwable t) {
+ failures.incrementAndGet();
+ latencies[(thread_idx*nbInvocationsPerThread)+i] = -1;
+ i++;
+ if (t instanceof UndeclaredThrowableException) {
+ t = ((UndeclaredThrowableException) t).getUndeclaredThrowable();
+ }
+ System.err.println("Error: " + t.getClass().getName() + (t.getMessage() != null ? " (" + t.getMessage() + ")" : ""));
+ sendNext();
+ }
+ }
+
+ @Test(timeout=30*1000)
+ public void testUnderLoadAsyncProto() throws Exception {
+ HashMap<String, SerializationStrategy> map = new HashMap<String, SerializationStrategy>();
+ map.put("protobuf", new ProtobufSerializationStrategy());
+
+ DispatchQueue queue = Dispatch.createQueue();
+ ServerInvokerImpl server = new ServerInvokerImpl("tcp://localhost:0", queue, map);
+ server.start();
+ ClientInvokerImpl client = new ClientInvokerImpl(queue, map);
+ client.start();
+
+ try {
+
+ final HelloImpl helloImpl = new HelloImpl();
+ server.registerService("service-id", new ServerInvoker.ServiceFactory() {
+ public Object get() {
+ return helloImpl;
+ }
+ public void unget() {
+ }
+ }, HelloImpl.class.getClassLoader());
+
+
+ InvocationHandler handler = client.getProxy(server.getConnectAddress(), "service-id", HelloImpl.class.getClassLoader());
+
+ final Hello hello = (Hello) Proxy.newProxyInstance(HelloImpl.class.getClassLoader(), new Class[] { Hello.class }, handler);
+
+ final AtomicInteger requests = new AtomicInteger(0);
+ final AtomicInteger failures = new AtomicInteger(0);
+ final long latencies[] = new long[BENCHMARK_CLIENTS * BENCHMARK_INVOCATIONS_PER_CLIENT];
+
+ final long start = System.nanoTime();
+ AsyncClient[] threads = new AsyncClient[BENCHMARK_CLIENTS];
+ for (int t = 0; t < BENCHMARK_CLIENTS; t++) {
+ threads[t] = new AsyncClient(t, BENCHMARK_INVOCATIONS_PER_CLIENT, hello, failures, requests, latencies);
+ threads[t].start();
+ }
+
+ for (int t = 0; t < BENCHMARK_CLIENTS; t++) {
+ threads[t].join();
+ }
+ final long end = System.nanoTime();
+
+ long latency_sum = 0;
+ for (int t = 0; t < latencies.length; t++) {
+ if( latencies[t] != -1 ) {
+ latency_sum += latencies[t];
+ }
+ }
+ double latency_avg = ((latency_sum * 1.0d)/requests.get()) / MILLIS_IN_A_NANO;
+ double request_rate = ((requests.get() * 1.0d)/(end-start)) * SECONDS_IN_A_NANO;
+
+ System.err.println(String.format("Requests/Second: %,.2f", request_rate));
+ System.err.println(String.format("Average request latency: %,.2f ms", latency_avg));
+ System.err.println("Error Ratio: " + failures.get() + " / " + requests.get());
+ }
+ finally {
+ server.stop();
+ client.stop();
+ }
+ }
+
+ public static interface Hello {
+ String hello(String name);
+
+ // async version of the hello method.
+ void hello(String name, AsyncCallback<String> callback);
+
+ String helloworld();
+
+ char mix(int value);
+ char mix(int[] value);
+ char mix(Integer value);
+ char mix(Integer[] value);
+ char mix(int[][] value);
+ char mix(Integer[][] value);
+
+ @Serialization("protobuf")
+ StringValue.Getter protobuf(StringValue.Getter name);
+
+ @Serialization("protobuf")
+ void protobuf(StringValue.Getter name, AsyncCallback<StringValue.Getter> callback);
+
+ }
+
+ static private StringValue.Bean stringValue(String hello) {
+ StringValue.Bean rc = new StringValue.Bean();
+ rc.setValue(hello);
+ return rc;
+ }
+
+ public static class HelloImpl implements Hello, Dispatched {
+
+ DispatchQueue queue = Dispatch.createQueue();
+
+ public DispatchQueue queue() {
+ return queue;
+ }
+
+ private void queueCheck() {
+ if( !queue.isExecuting() ) {
+ throw new IllegalStateException("Not executing on our dispatch queue");
+ }
+ }
+
+ public String helloworld() {
+ return "Hello World!";
+ }
+
+ public String hello(String name) {
+ queueCheck();
+ return "Hello " + name + "!";
+ }
+
+ @Serialization("protobuf")
+ public StringValue.Getter protobuf(StringValue.Getter name) {
+ return stringValue(hello(name.getValue()));
+ }
+
+ @Serialization("protobuf")
+ public void protobuf(StringValue.Getter name, AsyncCallback<StringValue.Getter> callback) {
+ callback.onSuccess(protobuf(name));
+ }
+
+ public void hello(String name, AsyncCallback<String> callback) {
+ queueCheck();
+ callback.onSuccess(hello(name));
+ }
+
+ public char mix(int value) {
+ queueCheck();
+ return 'a';
+ }
+
+ public char mix(int[] value) {
+ queueCheck();
+ return 'b';
+ }
+
+ public char mix(Integer value) {
+ queueCheck();
+ return 'c';
+ }
+
+ public char mix(Integer[] value) {
+ queueCheck();
+ return 'd';
+ }
+
+ public char mix(int[][] value) {
+ queueCheck();
+ return 'e';
+ }
+ public char mix(Integer[][] value) {
+ queueCheck();
+ return 'f';
+ }
+
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/test/java/org/apache/aries/rsa/provider/fastbin/ManagerTest.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/test/java/org/apache/aries/rsa/provider/fastbin/ManagerTest.java b/provider/fastbin/src/test/java/org/apache/aries/rsa/provider/fastbin/ManagerTest.java
new file mode 100644
index 0000000..427628f
--- /dev/null
+++ b/provider/fastbin/src/test/java/org/apache/aries/rsa/provider/fastbin/ManagerTest.java
@@ -0,0 +1,106 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin;
+
+
+public class ManagerTest {
+
+ /*
+ @Test
+ public void testManager() throws Exception {
+
+ ZKServerFactoryBean zkServerFactoryBean = null;
+
+ try {
+
+ int zooKeeperPort = getFreePort();
+ int serverPort = getFreePort();
+
+ zkServerFactoryBean = new ZKServerFactoryBean();
+ zkServerFactoryBean.setPurge(true);
+ zkServerFactoryBean.setClientPortAddress(new InetSocketAddress("localhost", zooKeeperPort));
+ zkServerFactoryBean.afterPropertiesSet();
+
+ CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
+ .connectString("localhost:" + zooKeeperPort)
+ .retryPolicy(new RetryOneTime(1000))
+ .connectionTimeoutMs(60000);
+
+ CuratorFramework curator = builder.build();
+ curator.start();
+ curator.getZookeeperClient().blockUntilConnectedOrTimedOut();
+
+ BundleContext bundleContext = createMock(BundleContext.class);
+ ServiceRegistration registration = createMock(ServiceRegistration.class);
+ Manager manager = new Manager(bundleContext, curator, "tcp://localhost:" + serverPort, "localhost", TimeUnit.MINUTES.toMillis(5));
+
+ bundleContext.addServiceListener(manager, "(service.exported.interfaces=*)");
+ expect(bundleContext.getProperty("org.osgi.framework.uuid")).andReturn("the-framework-uuid");
+ expect(bundleContext.registerService(
+ EasyMock.<String[]>anyObject(),
+ same(manager),
+ EasyMock.<Dictionary>same(null))).andReturn(registration);
+ expect(bundleContext.getServiceReferences((String) null, "(service.exported.interfaces=*)")).andReturn(null);
+
+ replay(bundleContext, registration);
+
+ manager.init();
+
+ verify(bundleContext, registration);
+
+ reset(bundleContext, registration);
+
+ BundleContext expBundleContext = createMock(BundleContext.class);
+ Bundle expBundle = createMock(Bundle.class);
+ ServiceReference reference = createMock(ServiceReference.class);
+ final Properties props = new Properties();
+ props.put(Constants.OBJECTCLASS, new String[]{ConfigurationAdmin.class.getName()});
+ expect(reference.getProperty(EasyMock.<String>anyObject())).andAnswer(new IAnswer<Object>() {
+ public Object answer() throws Throwable {
+ return props.get(EasyMock.getCurrentArguments()[0]);
+ }
+ }).anyTimes();
+ expect(reference.getPropertyKeys()).andReturn(props.keySet().toArray(new String[0]));
+ expect(reference.getBundle()).andReturn(expBundle).anyTimes();
+ expect(expBundle.getBundleContext()).andReturn(expBundleContext).anyTimes();
+ expect(expBundle.getState()).andReturn(Bundle.ACTIVE).anyTimes();
+
+ replay(bundleContext, registration, reference, expBundleContext, expBundle);
+
+ manager.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, reference));
+ Thread.sleep(1000);
+
+ verify(bundleContext, registration, reference, expBundleContext, expBundle);
+
+ }
+ finally {
+ try {
+ zkServerFactoryBean.destroy();
+ } catch (Throwable t) { }
+ }
+ }
+
+ static int getFreePort() throws IOException {
+ ServerSocket sock = new ServerSocket();
+ try {
+ sock.bind(new InetSocketAddress(0));
+ return sock.getLocalPort();
+ } finally {
+ sock.close();
+ }
+ }
+ */
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/test/java/org/apache/aries/rsa/provider/fastbin/TransportFailureTest.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/test/java/org/apache/aries/rsa/provider/fastbin/TransportFailureTest.java b/provider/fastbin/src/test/java/org/apache/aries/rsa/provider/fastbin/TransportFailureTest.java
new file mode 100644
index 0000000..7d3cbf0
--- /dev/null
+++ b/provider/fastbin/src/test/java/org/apache/aries/rsa/provider/fastbin/TransportFailureTest.java
@@ -0,0 +1,128 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Proxy;
+import java.nio.channels.SocketChannel;
+import java.util.HashMap;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.aries.rsa.provider.fastbin.api.AsyncCallback;
+import org.apache.aries.rsa.provider.fastbin.api.AsyncCallbackFuture;
+import org.apache.aries.rsa.provider.fastbin.api.ProtobufSerializationStrategy;
+import org.apache.aries.rsa.provider.fastbin.api.SerializationStrategy;
+import org.apache.aries.rsa.provider.fastbin.io.ServerInvoker;
+import org.apache.aries.rsa.provider.fastbin.tcp.ClientInvokerImpl;
+import org.apache.aries.rsa.provider.fastbin.tcp.ServerInvokerImpl;
+import org.fusesource.hawtdispatch.Dispatch;
+import org.fusesource.hawtdispatch.DispatchQueue;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+public class TransportFailureTest {
+
+ private static long SLEEP_TIME = 100;
+ private static long MAX_DELAY = 1000;
+
+ @Test
+ public void testInvoke() throws Exception {
+
+ DispatchQueue queue = Dispatch.createQueue();
+ HashMap<String, SerializationStrategy> map = new HashMap<String, SerializationStrategy>();
+ map.put("protobuf", new ProtobufSerializationStrategy());
+
+ ServerInvokerImpl server = new ServerInvokerImpl("tcp://localhost:0", queue, map);
+ server.start();
+
+ ClientInvokerImpl client = new ClientInvokerImpl(queue, map);
+ client.start();
+
+ try {
+ server.registerService("service-id", new ServerInvoker.ServiceFactory() {
+ public Object get() {
+ return new HelloImpl();
+ }
+ public void unget() {
+ }
+ }, HelloImpl.class.getClassLoader());
+
+
+ InvocationHandler handler = client.getProxy(server.getConnectAddress(), "service-id", HelloImpl.class.getClassLoader());
+ Hello hello = (Hello) Proxy.newProxyInstance(HelloImpl.class.getClassLoader(), new Class[]{Hello.class}, handler);
+
+ AsyncCallbackFuture<String> future1 = new AsyncCallbackFuture<String>();
+ hello.hello("Guillaume", future1);
+
+ long t0 = System.currentTimeMillis();
+ try {
+ assertEquals("Hello Guillaume!", future1.get(MAX_DELAY, TimeUnit.MILLISECONDS));
+ fail("Should have thrown an exception");
+ } catch (Exception e) {
+ // Expected
+ long t1 = System.currentTimeMillis();
+ assertTrue(t1 - t0 > SLEEP_TIME / 2);
+ assertTrue(t1 - t0 < MAX_DELAY / 2);
+ }
+
+ }
+ finally {
+ server.stop();
+ client.stop();
+ }
+ }
+
+ public static interface Hello {
+ void hello(String name, AsyncCallback<String> callback) throws Exception;
+ }
+
+ public static class HelloImpl implements Hello {
+ public void hello(final String name, final AsyncCallback<String> callback) throws Exception {
+ new Thread(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ Thread.sleep(SLEEP_TIME);
+ // Big introspection call to access the transport channel and close it, simulating
+ // a disconnect on the client side.
+ ((SocketChannel) get(get(get(get(get(callback, "val$helper"), "onComplete"), "this$1"), "val$transport"), "channel")).close();
+ } catch (Throwable e) {
+ e.printStackTrace();
+ }
+ callback.onSuccess("Hello " + name + "!");
+ }
+ }).start();
+ }
+ }
+
+ private static Object get(Object obj, String field) throws Exception {
+ for (Class cl = obj.getClass(); cl != Object.class; cl = cl.getSuperclass()) {
+ try {
+ Field f = obj.getClass().getDeclaredField(field);
+ f.setAccessible(true);
+ return f.get(obj);
+ } catch (Throwable t) {
+ // Ignore
+ }
+ }
+ throw new NoSuchFieldException(field);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/test/java/org/apache/aries/rsa/provider/fastbin/tcp/LengthPrefixedCodecTest.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/test/java/org/apache/aries/rsa/provider/fastbin/tcp/LengthPrefixedCodecTest.java b/provider/fastbin/src/test/java/org/apache/aries/rsa/provider/fastbin/tcp/LengthPrefixedCodecTest.java
new file mode 100644
index 0000000..ca7e7f6
--- /dev/null
+++ b/provider/fastbin/src/test/java/org/apache/aries/rsa/provider/fastbin/tcp/LengthPrefixedCodecTest.java
@@ -0,0 +1,150 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.tcp;
+
+import java.nio.BufferUnderflowException;
+import java.nio.ByteBuffer;
+import java.nio.channels.ReadableByteChannel;
+import java.nio.channels.WritableByteChannel;
+
+import org.apache.aries.rsa.provider.fastbin.io.ProtocolCodec.BufferState;
+import org.easymock.IAnswer;
+import org.fusesource.hawtbuf.Buffer;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.easymock.EasyMock.anyObject;
+import static org.easymock.EasyMock.createMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.getCurrentArguments;
+import static org.easymock.EasyMock.replay;
+import static org.junit.Assert.assertEquals;
+
+public class LengthPrefixedCodecTest {
+ private ReadableByteChannel readableByteChannel = createMock(ReadableByteChannel.class);
+
+ private WritableByteChannel writableByteChannel = createMock(WritableByteChannel.class);
+ private LengthPrefixedCodec codec;
+
+ @Before
+ public void createLengthPrefixedCodec() throws Exception {
+ codec = new LengthPrefixedCodec();
+ codec.setReadableByteChannel(readableByteChannel);
+ codec.setWritableByteChannel(writableByteChannel);
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ }
+
+ @Test
+ public void testFull() throws Exception {
+ assertEquals(false, codec.full());
+ }
+
+ @Test
+ public void testEmpty() throws Exception {
+ assertEquals(true, codec.empty());
+ }
+
+ @Test
+ public void testGetWriteCounter() throws Exception {
+ assertEquals(0l, codec.getWriteCounter());
+ }
+
+ @Test
+ public void testGetReadCounter() throws Exception {
+ assertEquals(0l, codec.getReadCounter());
+ }
+
+ @Test
+ public void testWrite() throws Exception {
+ final Buffer value = Buffer.ascii("TESTDATA");
+
+ final BufferState state = codec.write(value);
+
+ assertEquals(BufferState.WAS_EMPTY, state);
+ assertEquals(false, codec.full());
+ assertEquals(false, codec.empty());
+ assertEquals(0l, codec.getWriteCounter());
+ }
+
+ @Test
+ public void testWrite$Twice() throws Exception {
+ final Buffer value1 = Buffer.ascii("TESTDATA");
+ final Buffer value2 = Buffer.ascii("TESTDATA");
+ codec.write(value1);
+
+ final BufferState state = codec.write(value2);
+
+ assertEquals(BufferState.NOT_EMPTY, state);
+ assertEquals(false, codec.full());
+ assertEquals(false, codec.empty());
+ assertEquals(0l, codec.getWriteCounter());
+ }
+
+ @Test
+ public void testFlush() throws Exception {
+ final Buffer value = Buffer.ascii("TESTDATA");
+ codec.write(value);
+ final int bytesThatWillBeWritten = value.length();
+ expect(writableByteChannel.write((ByteBuffer) anyObject())).andAnswer(createWriteAnswer(bytesThatWillBeWritten));
+ replay(writableByteChannel);
+
+ final BufferState state = codec.flush();
+
+ assertEquals(BufferState.EMPTY, state);
+ assertEquals(false, codec.full());
+ assertEquals(true, codec.empty());
+ assertEquals(bytesThatWillBeWritten, codec.getWriteCounter());
+
+ assertEquals(BufferState.WAS_EMPTY, codec.flush());
+ }
+
+ @Test
+ public void testFlush$Partially() throws Exception {
+ final Buffer value = Buffer.ascii("TESTDATA");
+ codec.write(value);
+ final int bytesThatWillBeWritten = value.length() / 2;
+ expect(writableByteChannel.write((ByteBuffer) anyObject())).andAnswer(createWriteAnswer(bytesThatWillBeWritten));
+ replay(writableByteChannel);
+
+ final BufferState state = codec.flush();
+
+ assertEquals(BufferState.NOT_EMPTY, state);
+ assertEquals(false, codec.full());
+ assertEquals(false, codec.empty());
+ assertEquals(bytesThatWillBeWritten, codec.getWriteCounter());
+ }
+
+ private IAnswer<Integer> createWriteAnswer(final int length) {
+ return new IAnswer<Integer>() {
+ @Override
+ public Integer answer() throws Throwable {
+ final ByteBuffer buffer = (ByteBuffer) getCurrentArguments()[0];
+ if(buffer.remaining() < length)
+ throw new BufferUnderflowException();
+ buffer.position(buffer.position() + length);
+ return length;
+ }
+ };
+ }
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/test/proto/example.proto
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/test/proto/example.proto b/provider/fastbin/src/test/proto/example.proto
new file mode 100644
index 0000000..91c737f
--- /dev/null
+++ b/provider/fastbin/src/test/proto/example.proto
@@ -0,0 +1,28 @@
+//
+// Copyright (C) FuseSource, Inc.
+// http://fusesource.com
+//
+// 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.apache.aries.rsa.provider.fastbin.test;
+
+option java_multiple_files = true;
+
+///////////////////////////////////////////////////////////////
+// Message related operations.
+///////////////////////////////////////////////////////////////
+
+message StringValue {
+ optional string value = 1;
+}
+
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/test/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/test/resources/log4j.properties b/provider/fastbin/src/test/resources/log4j.properties
new file mode 100644
index 0000000..0a36712
--- /dev/null
+++ b/provider/fastbin/src/test/resources/log4j.properties
@@ -0,0 +1,35 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+#
+# The logging properties used during tests..
+#
+log4j.rootLogger=WARN, console, file
+log4j.logger.org.apache.aries.rsa.provider.fastbin=TRACE
+
+# Console will only display warnnings
+log4j.appender.console=org.apache.log4j.ConsoleAppender
+log4j.appender.console.layout=org.apache.log4j.PatternLayout
+log4j.appender.console.layout.ConversionPattern=%-5p | %t | %m%n
+log4j.appender.console.threshold=TRACE
+
+# File appender will contain all info messages
+log4j.appender.file=org.apache.log4j.FileAppender
+log4j.appender.file.layout=org.apache.log4j.PatternLayout
+log4j.appender.file.layout.ConversionPattern=%d | %-5p | %m | %c | %t%n
+log4j.appender.file.file=target/test.log
+log4j.appender.file.append=true
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/pom.xml
----------------------------------------------------------------------
diff --git a/provider/pom.xml b/provider/pom.xml
index fb6a769..bbb1ee6 100644
--- a/provider/pom.xml
+++ b/provider/pom.xml
@@ -39,5 +39,6 @@
<modules>
<module>tcp</module>
+ <module>fastbin</module>
</modules>
</project>
[3/3] aries-rsa git commit: [ARIES-1526] Add a fast nio/protobuf
provider
Posted by gn...@apache.org.
[ARIES-1526] Add a fast nio/protobuf provider
Project: http://git-wip-us.apache.org/repos/asf/aries-rsa/repo
Commit: http://git-wip-us.apache.org/repos/asf/aries-rsa/commit/62d835de
Tree: http://git-wip-us.apache.org/repos/asf/aries-rsa/tree/62d835de
Diff: http://git-wip-us.apache.org/repos/asf/aries-rsa/diff/62d835de
Branch: refs/heads/master
Commit: 62d835dec07d9592b1ea3fe038cea39b1e9af9aa
Parents: 58bb694
Author: Guillaume Nodet <gn...@apache.org>
Authored: Mon Apr 11 12:08:14 2016 +0200
Committer: Guillaume Nodet <gn...@apache.org>
Committed: Mon Apr 11 14:04:42 2016 +0200
----------------------------------------------------------------------
features/src/main/resources/features.xml | 9 +-
parent/pom.xml | 19 +-
provider/fastbin/bnd.bnd | 1 +
provider/fastbin/pom.xml | 62 ++
.../aries/rsa/provider/fastbin/Activator.java | 66 ++
.../rsa/provider/fastbin/BaseActivator.java | 290 +++++++
.../rsa/provider/fastbin/FastBinProvider.java | 146 ++++
.../rsa/provider/fastbin/api/AsyncCallback.java | 26 +
.../fastbin/api/AsyncCallbackFuture.java | 43 +
.../rsa/provider/fastbin/api/Dispatched.java | 31 +
.../api/ObjectSerializationStrategy.java | 73 ++
.../api/ProtobufSerializationStrategy.java | 127 +++
.../rsa/provider/fastbin/api/Serialization.java | 29 +
.../fastbin/api/SerializationStrategy.java | 38 +
.../rsa/provider/fastbin/io/ClientInvoker.java | 24 +
.../rsa/provider/fastbin/io/ProtocolCodec.java | 97 +++
.../rsa/provider/fastbin/io/ServerInvoker.java | 34 +
.../aries/rsa/provider/fastbin/io/Service.java | 52 ++
.../rsa/provider/fastbin/io/Transport.java | 95 +++
.../fastbin/io/TransportAcceptListener.java | 31 +
.../provider/fastbin/io/TransportListener.java | 55 ++
.../provider/fastbin/io/TransportServer.java | 73 ++
.../fastbin/tcp/AsyncInvocationStrategy.java | 188 +++++
.../fastbin/tcp/BlockingInvocationStrategy.java | 126 +++
.../provider/fastbin/tcp/ClientInvokerImpl.java | 327 ++++++++
.../fastbin/tcp/InvocationStrategy.java | 34 +
.../fastbin/tcp/LengthPrefixedCodec.java | 175 ++++
.../provider/fastbin/tcp/ResponseFuture.java | 31 +
.../provider/fastbin/tcp/ServerInvokerImpl.java | 314 +++++++
.../rsa/provider/fastbin/tcp/TcpTransport.java | 828 +++++++++++++++++++
.../fastbin/tcp/TcpTransportFactory.java | 123 +++
.../fastbin/tcp/TcpTransportServer.java | 231 ++++++
.../rsa/provider/fastbin/tcp/TransportPool.java | 256 ++++++
.../util/ClassLoaderObjectInputStream.java | 86 ++
.../fastbin/util/IntrospectionSupport.java | 362 ++++++++
.../provider/fastbin/util/StringSupport.java | 40 +
.../rsa/provider/fastbin/util/URISupport.java | 332 ++++++++
.../provider/fastbin/util/UuidGenerator.java | 178 ++++
.../rsa/provider/fastbin/InvocationTest.java | 581 +++++++++++++
.../aries/rsa/provider/fastbin/ManagerTest.java | 106 +++
.../provider/fastbin/TransportFailureTest.java | 128 +++
.../fastbin/tcp/LengthPrefixedCodecTest.java | 150 ++++
provider/fastbin/src/test/proto/example.proto | 28 +
.../fastbin/src/test/resources/log4j.properties | 35 +
provider/pom.xml | 1 +
45 files changed, 6079 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/features/src/main/resources/features.xml
----------------------------------------------------------------------
diff --git a/features/src/main/resources/features.xml b/features/src/main/resources/features.xml
index 1f9aea0..ba9bc93 100644
--- a/features/src/main/resources/features.xml
+++ b/features/src/main/resources/features.xml
@@ -11,7 +11,14 @@
<feature>aries-rsa-core</feature>
<bundle>mvn:org.apache.aries.rsa.provider/org.apache.aries.rsa.provider.tcp/${project.version}</bundle>
</feature>
-
+
+ <feature name="aries-rsa-provider-fastbin" version="${project.version}">
+ <feature>aries-rsa-core</feature>
+ <bundle>mvn:org.fusesource.hawtdispatch/hawtdispatch/${hawtdispatch.version}</bundle>
+ <bundle>mvn:org.fusesource.hawtbuf/hawtbuf/${hawtbuf.version}</bundle>
+ <bundle>mvn:org.apache.aries.rsa.provider/org.apache.aries.rsa.provider.fastbin/${project.version}</bundle>
+ </feature>
+
<feature name="aries-rsa-discovery-local" version="${project.version}">
<feature>aries-rsa-core</feature>
<bundle>mvn:org.apache.aries.rsa.discovery/org.apache.aries.rsa.discovery.local/${project.version}</bundle>
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/parent/pom.xml
----------------------------------------------------------------------
diff --git a/parent/pom.xml b/parent/pom.xml
index bdef21b..3ffada2 100644
--- a/parent/pom.xml
+++ b/parent/pom.xml
@@ -33,6 +33,8 @@
<rsa.version>1.0.0</rsa.version>
<slf4j.version>1.7.14</slf4j.version>
<log4j.version>1.2.6</log4j.version>
+ <hawtdispatch.version>1.21</hawtdispatch.version>
+ <hawtbuf.version>1.11</hawtbuf.version>
<exam.version>4.8.0</exam.version>
<cxf.resources.base.path />
<cxf.checkstyle.extension />
@@ -104,7 +106,22 @@
<artifactId>org.apache.aries.rsa.spi</artifactId>
<version>${project.version}</version>
</dependency>
-
+ <dependency>
+ <groupId>org.fusesource.hawtdispatch</groupId>
+ <artifactId>hawtdispatch</artifactId>
+ <version>${hawtdispatch.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.fusesource.hawtbuf</groupId>
+ <artifactId>hawtbuf</artifactId>
+ <version>${hawtbuf.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.fusesource.hawtbuf</groupId>
+ <artifactId>hawtbuf-proto</artifactId>
+ <version>${hawtbuf.version}</version>
+ </dependency>
+
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/bnd.bnd
----------------------------------------------------------------------
diff --git a/provider/fastbin/bnd.bnd b/provider/fastbin/bnd.bnd
new file mode 100644
index 0000000..5249b00
--- /dev/null
+++ b/provider/fastbin/bnd.bnd
@@ -0,0 +1 @@
+Bundle-Activator: org.apache.aries.rsa.provider.fastbin.Activator
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/pom.xml
----------------------------------------------------------------------
diff --git a/provider/fastbin/pom.xml b/provider/fastbin/pom.xml
new file mode 100644
index 0000000..a748035
--- /dev/null
+++ b/provider/fastbin/pom.xml
@@ -0,0 +1,62 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.aries.rsa</groupId>
+ <artifactId>org.apache.aries.rsa.parent</artifactId>
+ <version>1.9-SNAPSHOT</version>
+ <relativePath>../../parent/pom.xml</relativePath>
+ </parent>
+
+ <groupId>org.apache.aries.rsa.provider</groupId>
+ <artifactId>org.apache.aries.rsa.provider.fastbin</artifactId>
+ <packaging>bundle</packaging>
+ <name>Aries Remote Service Admin provider FastBin</name>
+ <description>Provider for Java Serialization over FastBin</description>
+
+ <properties>
+ <topDirectoryLocation>../..</topDirectoryLocation>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.aries.rsa</groupId>
+ <artifactId>org.apache.aries.rsa.spi</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.fusesource.hawtdispatch</groupId>
+ <artifactId>hawtdispatch</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.fusesource.hawtbuf</groupId>
+ <artifactId>hawtbuf</artifactId>
+ </dependency>
+ <!-- this is only needed you you want to use the ProtobufSerializationStrategy -->
+ <dependency>
+ <groupId>org.fusesource.hawtbuf</groupId>
+ <artifactId>hawtbuf-proto</artifactId>
+ <optional>true</optional>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.fusesource.hawtbuf</groupId>
+ <artifactId>hawtbuf-protoc</artifactId>
+ <version>${hawtbuf.version}</version>
+ <configuration>
+ <type>alt</type>
+ </configuration>
+ <executions>
+ <execution>
+ <goals>
+ <goal>compile</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+
+</project>
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/Activator.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/Activator.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/Activator.java
new file mode 100644
index 0000000..b89de14
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/Activator.java
@@ -0,0 +1,66 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin;
+
+import java.util.Dictionary;
+import java.util.Hashtable;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.aries.rsa.provider.fastbin.util.UuidGenerator;
+import org.apache.aries.rsa.spi.DistributionProvider;
+import org.osgi.service.cm.ManagedService;
+import org.osgi.service.remoteserviceadmin.RemoteConstants;
+
+public class Activator extends BaseActivator implements ManagedService {
+
+ private FastBinProvider provider;
+
+ @Override
+ protected void doOpen() throws Exception {
+ manage("org.apache.aries.rsa.provider.fastbin");
+ }
+
+ @Override
+ protected void doStart() throws Exception {
+ String uri = getString("uri", "tcp://0.0.0.0:2543");
+ String exportedAddress = getString("exportedAddress", null);
+ if (exportedAddress == null) {
+ exportedAddress = UuidGenerator.getHostName();
+ }
+ long timeout = getLong("timeout", TimeUnit.MINUTES.toMillis(5));
+ provider = new FastBinProvider(uri, exportedAddress, timeout);
+ Dictionary<String, Object> props = new Hashtable<>();
+ props.put(RemoteConstants.REMOTE_INTENTS_SUPPORTED, new String[]{});
+ props.put(RemoteConstants.REMOTE_CONFIGS_SUPPORTED, provider.getSupportedTypes());
+ register(DistributionProvider.class, provider, props);
+ }
+
+ @Override
+ protected void doStop() {
+ super.doStop();
+ if (provider != null) {
+ try {
+ provider.close();
+ } finally {
+ provider = null;
+ }
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/BaseActivator.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/BaseActivator.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/BaseActivator.java
new file mode 100644
index 0000000..6b7b6fe
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/BaseActivator.java
@@ -0,0 +1,290 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin;
+
+import java.io.InputStream;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Dictionary;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Properties;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.Constants;
+import org.osgi.framework.ServiceRegistration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class BaseActivator implements BundleActivator, Runnable {
+
+ protected final Logger logger = LoggerFactory.getLogger(getClass());
+ protected BundleContext bundleContext;
+
+ protected ExecutorService executor = new ThreadPoolExecutor(0, 1, 0L, TimeUnit.MILLISECONDS,
+ new LinkedBlockingQueue<Runnable>());
+ private AtomicBoolean scheduled = new AtomicBoolean();
+
+ private long schedulerStopTimeout = TimeUnit.MILLISECONDS.convert(30, TimeUnit.SECONDS);
+
+ private List<ServiceRegistration> registrations;
+ private ServiceRegistration managedServiceRegistration;
+ private Dictionary<String, ?> configuration;
+
+ public long getSchedulerStopTimeout() {
+ return schedulerStopTimeout;
+ }
+
+ public void setSchedulerStopTimeout(long schedulerStopTimeout) {
+ this.schedulerStopTimeout = schedulerStopTimeout;
+ }
+
+ @Override
+ public void start(BundleContext context) throws Exception {
+ bundleContext = context;
+ scheduled.set(true);
+ doOpen();
+ scheduled.set(false);
+ if (managedServiceRegistration == null) {
+ try {
+ doStart();
+ } catch (Exception e) {
+ logger.warn("Error starting activator", e);
+ doStop();
+ }
+ } else {
+ reconfigure();
+ }
+ }
+
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ scheduled.set(true);
+ doClose();
+ executor.shutdown();
+ executor.awaitTermination(schedulerStopTimeout, TimeUnit.MILLISECONDS);
+ doStop();
+ }
+
+ protected void doOpen() throws Exception {
+ URL data = bundleContext.getBundle().getResource("OSGI-INF/karaf-tracker/" + getClass().getName());
+ if (data != null) {
+ Properties props = new Properties();
+ try (InputStream is = data.openStream()) {
+ props.load(is);
+ }
+ for (String key : props.stringPropertyNames()) {
+ if ("pid".equals(key)) {
+ manage(props.getProperty(key));
+ }
+ }
+ }
+ }
+
+ protected void doClose() {
+ if (managedServiceRegistration != null) {
+ managedServiceRegistration.unregister();
+ }
+ }
+
+ protected void doStart() throws Exception {
+ }
+
+ protected void doStop() {
+ if (registrations != null) {
+ for (ServiceRegistration reg : registrations) {
+ reg.unregister();
+ }
+ registrations = null;
+ }
+ }
+
+ /**
+ * Called in {@link #doOpen()}.
+ *
+ * @param pid The configuration PID to manage (ManagedService).
+ */
+ protected void manage(String pid) {
+ Hashtable<String, Object> props = new Hashtable<>();
+ props.put(Constants.SERVICE_PID, pid);
+ managedServiceRegistration = bundleContext.registerService(
+ "org.osgi.service.cm.ManagedService", this, props);
+ }
+
+ public void updated(Dictionary<String, ?> properties) {
+ this.configuration = properties;
+ reconfigure();
+ }
+
+ protected Dictionary<String, ?> getConfiguration() {
+ return configuration;
+ }
+
+ /**
+ * Called in {@link #doStart()}.
+ *
+ * @param key The configuration key
+ * @param def The default value.
+ * @return The value of the configuration key if found, the default value else.
+ */
+ protected int getInt(String key, int def) {
+ if (configuration != null) {
+ Object val = configuration.get(key);
+ if (val instanceof Number) {
+ return ((Number) val).intValue();
+ } else if (val != null) {
+ return Integer.parseInt(val.toString());
+ }
+ }
+ return def;
+ }
+
+ /**
+ * Called in {@link #doStart()}.
+ *
+ * @param key The configuration key.
+ * @param def The default value.
+ * @return The value of the configuration key if found, the default value else.
+ */
+ protected boolean getBoolean(String key, boolean def) {
+ if (configuration != null) {
+ Object val = configuration.get(key);
+ if (val instanceof Boolean) {
+ return (Boolean) val;
+ } else if (val != null) {
+ return Boolean.parseBoolean(val.toString());
+ }
+ }
+ return def;
+ }
+
+ /**
+ * Called in {@link #doStart()}.
+ *
+ * @param key The configuration key.
+ * @param def The default value.
+ * @return The value of the configuration key if found, the default value else.
+ */
+ protected long getLong(String key, long def) {
+ if (configuration != null) {
+ Object val = configuration.get(key);
+ if (val instanceof Number) {
+ return ((Number) val).longValue();
+ } else if (val != null) {
+ return Long.parseLong(val.toString());
+ }
+ }
+ return def;
+ }
+
+ /**
+ * Called in {@link #doStart()}.
+ *
+ * @param key The configuration key.
+ * @param def The default value.
+ * @return The value of the configuration key if found, the default value else.
+ */
+ protected String getString(String key, String def) {
+ if (configuration != null) {
+ Object val = configuration.get(key);
+ if (val != null) {
+ return val.toString();
+ }
+ }
+ return def;
+ }
+
+ protected void reconfigure() {
+ if (scheduled.compareAndSet(false, true)) {
+ executor.submit(this);
+ }
+ }
+
+ @Override
+ public void run() {
+ scheduled.set(false);
+ doStop();
+ try {
+ doStart();
+ } catch (Exception e) {
+ logger.warn("Error starting activator", e);
+ doStop();
+ }
+ }
+
+ /**
+ * Called in {@link #doStart()}.
+ *
+ * @param clazz The service interface to register.
+ * @param <T> The service type.
+ * @param service The actual service instance to register.
+ */
+ protected <T> void register(Class<T> clazz, T service) {
+ register(clazz, service, null);
+ }
+
+ /**
+ * Called in {@link #doStart()}.
+ *
+ * @param clazz The service interface to register.
+ * @param <T> The service type.
+ * @param service The actual service instance to register.
+ * @param props The service properties to register.
+ */
+ protected <T> void register(Class<T> clazz, T service, Dictionary<String, ?> props) {
+ trackRegistration(bundleContext.registerService(clazz, service, props));
+ }
+
+ /**
+ * Called in {@link #doStart()}.
+ *
+ * @param clazz The service interfaces to register.
+ * @param service The actual service instance to register.
+ */
+ protected void register(Class[] clazz, Object service) {
+ register(clazz, service, null);
+ }
+
+ /**
+ * Called in {@link #doStart()}.
+ *
+ * @param clazz The service interfaces to register.
+ * @param service The actual service instance to register.
+ * @param props The service properties to register.
+ */
+ protected void register(Class[] clazz, Object service, Dictionary<String, ?> props) {
+ String[] names = new String[clazz.length];
+ for (int i = 0; i < clazz.length; i++) {
+ names[i] = clazz[i].getName();
+ }
+ trackRegistration(bundleContext.registerService(names, service, props));
+ }
+
+ private void trackRegistration(ServiceRegistration registration) {
+ if (registrations == null) {
+ registrations = new ArrayList<>();
+ }
+ registrations.add(registration);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/FastBinProvider.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/FastBinProvider.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/FastBinProvider.java
new file mode 100644
index 0000000..476a699
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/FastBinProvider.java
@@ -0,0 +1,146 @@
+package org.apache.aries.rsa.provider.fastbin;
+
+import java.io.IOException;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Proxy;
+import java.net.URI;
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.aries.rsa.provider.fastbin.api.SerializationStrategy;
+import org.apache.aries.rsa.provider.fastbin.io.ClientInvoker;
+import org.apache.aries.rsa.provider.fastbin.io.ServerInvoker;
+import org.apache.aries.rsa.provider.fastbin.tcp.ClientInvokerImpl;
+import org.apache.aries.rsa.provider.fastbin.tcp.ServerInvokerImpl;
+import org.apache.aries.rsa.provider.fastbin.util.UuidGenerator;
+import org.apache.aries.rsa.spi.DistributionProvider;
+import org.apache.aries.rsa.spi.Endpoint;
+import org.apache.aries.rsa.spi.IntentUnsatisfiedException;
+import org.fusesource.hawtdispatch.Dispatch;
+import org.fusesource.hawtdispatch.DispatchQueue;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.remoteserviceadmin.EndpointDescription;
+import org.osgi.service.remoteserviceadmin.RemoteConstants;
+
+public class FastBinProvider implements DistributionProvider {
+
+ public static final String FASTBIN_CONFIG_TYPE = "aries.fastbin";
+
+ public static final String FASTBIN_ADDRESS = FASTBIN_CONFIG_TYPE + ".address";
+
+ private final String uri;
+ private final String exportedAddress;
+ private final long timeout;
+
+ private final DispatchQueue queue = Dispatch.createQueue();
+ private final Map<String, SerializationStrategy> serializationStrategies = new ConcurrentHashMap<>();
+
+ private ClientInvoker client;
+ private ServerInvoker server;
+
+ public FastBinProvider(java.lang.String uri, java.lang.String exportedAddress, long timeout) throws Exception {
+ this.uri = uri;
+ this.exportedAddress = exportedAddress;
+ this.timeout = timeout;
+ // Create client and server
+ this.client = new ClientInvokerImpl(queue, timeout, serializationStrategies);
+ this.server = new ServerInvokerImpl(uri, queue, serializationStrategies);
+ this.client.start();
+ this.server.start();
+ }
+
+ public void close() {
+ client.stop();
+ server.stop();
+ }
+
+ @Override
+ public String[] getSupportedTypes() {
+ return new String[] {FASTBIN_CONFIG_TYPE};
+ }
+
+ @Override
+ public Endpoint exportService(final Object serviceO,
+ BundleContext serviceContext,
+ Map<String, Object> effectiveProperties,
+ Class[] exportedInterfaces) {
+
+ // Compute properties
+ /*
+ Map<String, Object> properties = new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);
+ for (String k : reference.getPropertyKeys()) {
+ properties.put(k, reference.getProperty(k));
+ }
+ // Bail out if there is any intents specified, we don't support any
+ Set<String> intents = Utils.normalize(properties.get(SERVICE_EXPORTED_INTENTS));
+ Set<String> extraIntents = Utils.normalize(properties.get(SERVICE_EXPORTED_INTENTS_EXTRA));
+ if (!intents.isEmpty() || !extraIntents.isEmpty()) {
+ throw new UnsupportedOperationException();
+ }
+ // Bail out if there are any configurations specified, we don't support any
+ Set<String> configs = Utils.normalize(properties.get(SERVICE_EXPORTED_CONFIGS));
+ if (configs.isEmpty()) {
+ configs.add(CONFIG);
+ } else if (!configs.contains(CONFIG)) {
+ throw new UnsupportedOperationException();
+ }
+
+ URI connectUri = new URI(this.server.getConnectAddress());
+ String fabricAddress = connectUri.getScheme() + "://" + exportedAddress + ":" + connectUri.getPort();
+
+ properties.remove(SERVICE_EXPORTED_CONFIGS);
+ properties.put(SERVICE_IMPORTED_CONFIGS, new String[] { CONFIG });
+ properties.put(ENDPOINT_FRAMEWORK_UUID, this.uuid);
+ properties.put(FABRIC_ADDRESS, fabricAddress);
+
+ String uuid = UuidGenerator.getUUID();
+ properties.put(ENDPOINT_ID, uuid);
+ */
+
+ String endpointId = UuidGenerator.getUUID();
+ effectiveProperties.put(RemoteConstants.ENDPOINT_ID, endpointId);
+
+ URI connectUri = URI.create(this.server.getConnectAddress());
+ String fastbinAddress = connectUri.getScheme() + "://" + exportedAddress + ":" + connectUri.getPort();
+ effectiveProperties.put(FASTBIN_ADDRESS, fastbinAddress);
+ effectiveProperties.put(RemoteConstants.SERVICE_IMPORTED_CONFIGS, getSupportedTypes());
+
+ // Now, export the service
+ final EndpointDescription description = new EndpointDescription(effectiveProperties);
+
+ // Export it
+ server.registerService(description.getId(), new ServerInvoker.ServiceFactory() {
+ public Object get() {
+ return serviceO;
+ }
+ public void unget() {
+ }
+ }, serviceO.getClass().getClassLoader());
+
+ return new Endpoint() {
+ @Override
+ public EndpointDescription description() {
+ return description;
+ }
+
+ @Override
+ public void close() throws IOException {
+ server.unregisterService(description.getId());
+ }
+ };
+ }
+
+ @Override
+ public Object importEndpoint(ClassLoader cl,
+ BundleContext consumerContext,
+ Class[] interfaces,
+ EndpointDescription endpoint)
+ throws IntentUnsatisfiedException {
+
+ String address = (String) endpoint.getProperties().get(FASTBIN_ADDRESS);
+ InvocationHandler handler = client.getProxy(address, endpoint.getId(), cl);
+ return Proxy.newProxyInstance(cl, interfaces, handler);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/AsyncCallback.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/AsyncCallback.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/AsyncCallback.java
new file mode 100644
index 0000000..5ca7bbd
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/AsyncCallback.java
@@ -0,0 +1,26 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.api;
+
+/**
+ * <p>
+ * </p>
+ *
+ */
+public interface AsyncCallback<T> {
+ void onSuccess(T result);
+ void onFailure(Throwable failure);
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/AsyncCallbackFuture.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/AsyncCallbackFuture.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/AsyncCallbackFuture.java
new file mode 100644
index 0000000..71906bd
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/AsyncCallbackFuture.java
@@ -0,0 +1,43 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.api;
+
+import java.util.concurrent.Callable;
+import java.util.concurrent.FutureTask;
+
+/**
+ * <p>
+ * </p>
+ *
+ */
+public class AsyncCallbackFuture<T> extends FutureTask<T> implements AsyncCallback<T> {
+
+ public AsyncCallbackFuture() {
+ super(new Callable<T>() {
+ public T call() {
+ return null;
+ }
+ });
+ }
+
+ public void onSuccess(T result) {
+ super.set(result);
+ }
+
+ public void onFailure(Throwable failure) {
+ super.setException(failure);
+ }
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/Dispatched.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/Dispatched.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/Dispatched.java
new file mode 100644
index 0000000..77864d1
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/Dispatched.java
@@ -0,0 +1,31 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.api;
+
+import org.fusesource.hawtdispatch.DispatchQueue;
+
+/**
+ * <p>
+ * Implemented by object which expect to be call from the execution context
+ * of a dispatch queue.
+ * </p>
+ *
+ */
+public interface Dispatched {
+
+ DispatchQueue queue();
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/ObjectSerializationStrategy.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/ObjectSerializationStrategy.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/ObjectSerializationStrategy.java
new file mode 100644
index 0000000..c5762ca
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/ObjectSerializationStrategy.java
@@ -0,0 +1,73 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.api;
+
+import java.io.IOException;
+import java.io.ObjectOutputStream;
+
+import org.apache.aries.rsa.provider.fastbin.util.ClassLoaderObjectInputStream;
+import org.fusesource.hawtbuf.DataByteArrayInputStream;
+import org.fusesource.hawtbuf.DataByteArrayOutputStream;
+
+/**
+ * <p>
+ * </p>
+ *
+ */
+public class ObjectSerializationStrategy implements SerializationStrategy {
+ public static final ObjectSerializationStrategy INSTANCE = new ObjectSerializationStrategy();
+
+ public String name() {
+ return "object";
+ }
+
+ public void encodeRequest(ClassLoader loader, Class<?>[] types, Object[] args, DataByteArrayOutputStream target) throws IOException {
+ ObjectOutputStream oos = new ObjectOutputStream(target);
+ oos.writeObject(args);
+ oos.flush();
+ }
+
+ public void decodeResponse(ClassLoader loader, Class<?> type, DataByteArrayInputStream source, AsyncCallback result) throws IOException, ClassNotFoundException {
+ ClassLoaderObjectInputStream ois = new ClassLoaderObjectInputStream(source);
+ ois.setClassLoader(loader);
+ Throwable error = (Throwable) ois.readObject();
+ Object value = ois.readObject();
+ if (error != null) {
+ result.onFailure(error);
+ } else {
+ result.onSuccess(value);
+ }
+ }
+
+ public void decodeRequest(ClassLoader loader, Class<?>[] types, DataByteArrayInputStream source, Object[] target) throws IOException, ClassNotFoundException {
+ final ClassLoaderObjectInputStream ois = new ClassLoaderObjectInputStream(source);
+ ois.setClassLoader(loader);
+ final Object[] args = (Object[]) ois.readObject();
+ if( args!=null ) {
+ System.arraycopy(args, 0, target, 0, args.length);
+ }
+ }
+
+
+ public void encodeResponse(ClassLoader loader, Class<?> type, Object value, Throwable error, DataByteArrayOutputStream target) throws IOException, ClassNotFoundException {
+ ObjectOutputStream oos = new ObjectOutputStream(target);
+ oos.writeObject(error);
+ oos.writeObject(value);
+ oos.flush();
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/ProtobufSerializationStrategy.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/ProtobufSerializationStrategy.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/ProtobufSerializationStrategy.java
new file mode 100644
index 0000000..c53c65d
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/ProtobufSerializationStrategy.java
@@ -0,0 +1,127 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.api;
+
+import java.io.IOException;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+
+import org.fusesource.hawtbuf.DataByteArrayInputStream;
+import org.fusesource.hawtbuf.DataByteArrayOutputStream;
+import org.fusesource.hawtbuf.proto.PBMessage;
+import org.fusesource.hawtbuf.proto.PBMessageFactory;
+
+/**
+ * <p>
+ * </p>
+ *
+ */
+public class ProtobufSerializationStrategy implements SerializationStrategy {
+
+ public static final ProtobufSerializationStrategy INSTANCE = new ProtobufSerializationStrategy();
+
+ public String name() {
+ return "protobuf";
+ }
+
+ private void encodeProtobuf(Class<?> type, Object arg, DataByteArrayOutputStream target) throws IOException {
+ if( !PBMessage.class.isAssignableFrom(type) ) {
+ throw new IllegalArgumentException("Invalid "+name()+" serialization method: method argument not a "+PBMessage.class.getName());
+ }
+ PBMessage msg = (PBMessage) arg;
+ if( msg==null ) {
+ return;
+ }
+ msg.freeze().writeUnframed(target);
+ }
+
+ private Object decodeProtobuf(Class<?> type, DataByteArrayInputStream source) throws IllegalAccessException, NoSuchFieldException, IOException {
+ if( !PBMessage.class.isAssignableFrom(type) ) {
+ throw new IllegalArgumentException("Invalid "+name()+" serialization method: method argument not a "+PBMessage.class.getName());
+ }
+
+ // Get the factory instance...
+ PBMessageFactory factory = (PBMessageFactory) type.getEnclosingClass().getField("FACTORY").get(null);
+ PBMessage msg = factory.parseUnframed(source);
+ String name = type.getName();
+ Object rc;
+ if( name.endsWith("$Getter") || name.endsWith("$Buffer") ) {
+ // Interface is ok we us giving them a read only impl.
+ rc = msg;
+ } else {
+ // They want a read/write impl.
+ rc = msg.copy();
+ }
+ return rc;
+ }
+
+ public void encodeRequest(ClassLoader loader, Class<?>[] types, Object[] args, DataByteArrayOutputStream target) throws IOException {
+ if( types.length == 0 ) {
+ return;
+ } else if( types.length == 1 ) {
+ encodeProtobuf(types[0], args[0], target);
+ } else {
+ throw new IllegalArgumentException("Invalid "+name()+" serialization method: methods must have zero or one argument.");
+ }
+ }
+
+ public void decodeRequest(ClassLoader loader, Class<?>[] types, DataByteArrayInputStream source, Object[] target) throws IOException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
+ if( types.length == 0 ) {
+ return;
+ } else if( types.length == 1 ) {
+ target[0] = decodeProtobuf(types[0], source);
+ } else {
+ throw new IllegalArgumentException("Invalid "+name()+" serialization method: methods must have zero or one argument.");
+ }
+ }
+
+ public void encodeResponse(ClassLoader loader, Class<?> type, Object value, Throwable error, DataByteArrayOutputStream target) throws IOException, ClassNotFoundException {
+ if( error!=null ) {
+ target.writeBoolean(true);
+ target.writeUTF(error.getClass().getName());
+ target.writeUTF(error.getMessage());
+ } else {
+ target.writeBoolean(false);
+ encodeProtobuf(type, value, target);
+ }
+ }
+
+ public void decodeResponse(ClassLoader loader, Class<?> type, DataByteArrayInputStream source, AsyncCallback result) throws IOException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException {
+ if( source.readBoolean() ) {
+ String className = source.readUTF();
+ String message = source.readUTF();
+
+ Throwable error;
+ try {
+ // try to build the exception...
+ Constructor<?> ctr = loader.loadClass(className).getConstructor(new Class[]{String.class});
+ error = (Throwable) ctr.newInstance(message);
+ } catch (Throwable e) {
+ // fallback to something simple..
+ error = new RuntimeException(className+": "+message);
+ }
+ result.onFailure(error);
+
+ } else {
+ result.onSuccess(decodeProtobuf(type, source));
+ }
+
+ }
+
+
+
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/Serialization.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/Serialization.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/Serialization.java
new file mode 100644
index 0000000..3650085
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/Serialization.java
@@ -0,0 +1,29 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.api;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.TYPE, ElementType.METHOD})
+public @interface Serialization {
+ String value();
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/SerializationStrategy.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/SerializationStrategy.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/SerializationStrategy.java
new file mode 100644
index 0000000..d5ac175
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/api/SerializationStrategy.java
@@ -0,0 +1,38 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.api;
+
+import org.fusesource.hawtbuf.DataByteArrayInputStream;
+import org.fusesource.hawtbuf.DataByteArrayOutputStream;
+
+/**
+ * <p>
+ * </p>
+ *
+ */
+public interface SerializationStrategy {
+
+ String name();
+
+ void encodeRequest(ClassLoader loader, Class<?>[] types, Object[] args, DataByteArrayOutputStream target) throws Exception;
+
+ void decodeResponse(ClassLoader loader, Class<?> type, DataByteArrayInputStream source, AsyncCallback result) throws Exception;
+
+ void decodeRequest(ClassLoader loader, Class<?>[] types, DataByteArrayInputStream source, Object[] target) throws Exception;
+
+ void encodeResponse(ClassLoader loader, Class<?> type, Object value, Throwable error, DataByteArrayOutputStream target) throws Exception;
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/ClientInvoker.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/ClientInvoker.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/ClientInvoker.java
new file mode 100644
index 0000000..1d04e7c
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/ClientInvoker.java
@@ -0,0 +1,24 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.io;
+
+import java.lang.reflect.InvocationHandler;
+
+public interface ClientInvoker extends Service {
+
+ InvocationHandler getProxy(String address, String service, ClassLoader classLoader);
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/ProtocolCodec.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/ProtocolCodec.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/ProtocolCodec.java
new file mode 100644
index 0000000..e5ea148
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/ProtocolCodec.java
@@ -0,0 +1,97 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.io;
+
+import java.io.IOException;
+import java.nio.channels.ReadableByteChannel;
+import java.nio.channels.WritableByteChannel;
+
+
+
+/**
+ * Interface to encode and decode commands in and out of a a non blocking channel.
+ *
+ */
+public interface ProtocolCodec {
+
+ ///////////////////////////////////////////////////////////////////
+ //
+ // Methods related with reading from the channel
+ //
+ ///////////////////////////////////////////////////////////////////
+
+ /**
+ * @param channel
+ */
+ public void setReadableByteChannel(ReadableByteChannel channel);
+
+ /**
+ * Non-blocking channel based decoding.
+ *
+ * @return
+ * @throws IOException
+ */
+ Object read() throws IOException;
+
+ /**
+ * @return The number of bytes received.
+ */
+ public long getReadCounter();
+
+
+ ///////////////////////////////////////////////////////////////////
+ //
+ // Methods related with writing to the channel
+ //
+ ///////////////////////////////////////////////////////////////////
+
+
+ enum BufferState {
+ EMPTY,
+ WAS_EMPTY,
+ NOT_EMPTY,
+ FULL,
+ }
+
+ public void setWritableByteChannel(WritableByteChannel channel);
+
+ /**
+ * Non-blocking channel based encoding.
+ *
+ * @return true if the write completed.
+ * @throws IOException
+ */
+ BufferState write(Object value) throws IOException;
+
+ /**
+ * Attempts to complete the previous write which did not complete.
+ * @return
+ * @throws IOException
+ */
+ BufferState flush() throws IOException;
+
+ /**
+ * @return true if the codec will no accept any more writes.
+ */
+ boolean full();
+
+ /**
+ * @return The number of bytes written.
+ */
+ public long getWriteCounter();
+
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/ServerInvoker.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/ServerInvoker.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/ServerInvoker.java
new file mode 100644
index 0000000..bc1d68c
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/ServerInvoker.java
@@ -0,0 +1,34 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.io;
+
+public interface ServerInvoker extends Service {
+
+ String getConnectAddress();
+
+ void registerService(String id, ServiceFactory service, ClassLoader classLoader);
+
+ void unregisterService(String id);
+
+
+ public interface ServiceFactory {
+
+ Object get();
+
+ void unget();
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/Service.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/Service.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/Service.java
new file mode 100644
index 0000000..71bbd5d
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/Service.java
@@ -0,0 +1,52 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.io;
+
+
+/**
+ * The core lifecyle interface for ActiveMQ components.
+ *
+ * @version $Revision: 1.1 $
+ */
+public interface Service {
+
+ /**
+ * Starts the service. No guarantee is given that the service has fully started
+ * by the time this method returns.
+ */
+ void start() throws Exception;
+
+ /**
+ * Starts the service. Executes the onComplete runnable once the service has fully started up.
+ *
+ * @param onComplete my be set to null if not interested in a callback.
+ */
+ void start(Runnable onComplete) throws Exception;
+
+ /**
+ * Stops the service. No guarantee is given that the service has fully stopped
+ * by the time this method returns.
+ */
+ void stop();
+
+ /**
+ * Stops the service. Executes the onComplete runnable once the service has fully stopped.
+ *
+ * @param onComplete my be set to null if not interested in a callback.
+ */
+ void stop(Runnable onComplete);
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/Transport.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/Transport.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/Transport.java
new file mode 100644
index 0000000..f41b478
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/Transport.java
@@ -0,0 +1,95 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.io;
+
+import org.apache.aries.rsa.provider.fastbin.api.Dispatched;
+import org.fusesource.hawtdispatch.DispatchQueue;
+
+/**
+ * Represents an abstract connection. It can be a client side or server side connection.
+ *
+ */
+public interface Transport extends Service, Dispatched {
+
+
+ boolean full();
+
+ /**
+ * A one way asynchronous send of a command. Only sent if the the transport is not full.
+ *
+ * @param command
+ * @return true if the command was accepted.
+ */
+ boolean offer(Object command);
+
+ /**
+ * Returns the current transport listener
+ *
+ * @return
+ */
+ TransportListener getTransportListener();
+
+ /**
+ * Registers an inbound command listener
+ *
+ * @param commandListener
+ */
+ void setTransportListener(TransportListener commandListener);
+
+ /**
+ * Sets the dispatch queue used by the transport
+ *
+ * @param queue
+ */
+ void setDispatchQueue(DispatchQueue queue);
+
+ /**
+ * suspend delivery of commands.
+ */
+ void suspendRead();
+
+ /**
+ * resume delivery of commands.
+ */
+ void resumeRead();
+
+ /**
+ * @return the remote address for this connection
+ */
+ String getRemoteAddress();
+
+ /**
+ * @return true if the transport is disposed
+ */
+ boolean isDisposed();
+
+ /**
+ * @return true if the transport is connected
+ */
+ boolean isConnected();
+
+ /**
+ * @return The protocol codec for the transport.
+ */
+ ProtocolCodec getProtocolCodec();
+
+ /**
+ * Sets the protocol codec for the transport
+ * @param protocolCodec
+ */
+ void setProtocolCodec(ProtocolCodec protocolCodec);
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/TransportAcceptListener.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/TransportAcceptListener.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/TransportAcceptListener.java
new file mode 100644
index 0000000..247978c
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/TransportAcceptListener.java
@@ -0,0 +1,31 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.io;
+
+
+import org.apache.aries.rsa.provider.fastbin.tcp.TcpTransport;
+
+/**
+ * Implemented by object that need to get injected by
+ *
+ */
+public interface TransportAcceptListener {
+
+ void onAccept(TransportServer transportServer, TcpTransport transport);
+
+ void onAcceptError(TransportServer transportServer, Exception error);
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/TransportListener.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/TransportListener.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/TransportListener.java
new file mode 100644
index 0000000..4b16bde
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/TransportListener.java
@@ -0,0 +1,55 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.io;
+
+import java.io.IOException;
+
+
+/**
+ * An asynchronous listener of commands
+ *
+ */
+public interface TransportListener {
+
+ /**
+ * called to process a command
+ * @param command
+ */
+ void onTransportCommand(Transport transport, Object command);
+
+ /**
+ * transport can now accept more commands for transmission.
+ */
+ void onRefill(Transport transport);
+
+ /**
+ * An unrecoverable exception has occured on the transport
+ * @param error
+ */
+ void onTransportFailure(Transport transport, IOException error);
+
+ /**
+ * The transport has been connected.
+ */
+ public void onTransportConnected(Transport transport);
+
+ /**
+ * The transport has suffered a disconnection from
+ * which it hopes to recover
+ */
+ public void onTransportDisconnected(Transport transport);
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/TransportServer.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/TransportServer.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/TransportServer.java
new file mode 100644
index 0000000..e8f620e
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/io/TransportServer.java
@@ -0,0 +1,73 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.io;
+
+import java.net.InetSocketAddress;
+
+import org.fusesource.hawtdispatch.DispatchQueue;
+
+/**
+ * A TransportServer asynchronously accepts {@see Transport} objects and then
+ * delivers those objects to a {@see TransportAcceptListener}.
+ *
+ * @version $Revision: 1.4 $
+ */
+public interface TransportServer extends Service {
+
+ /**
+ * Registers an {@see TransportAcceptListener} which is notified of accepted
+ * channels.
+ *
+ * @param acceptListener
+ */
+ void setAcceptListener(TransportAcceptListener acceptListener);
+
+ String getBoundAddress();
+
+ String getConnectAddress();
+
+ /**
+ * @return The socket address that this transport is accepting connections
+ * on or null if this does not or is not currently accepting
+ * connections on a socket.
+ */
+ InetSocketAddress getSocketAddress();
+
+ /**
+ * Returns the dispatch queue used by the transport
+ *
+ * @return
+ */
+ DispatchQueue getDispatchQueue();
+
+ /**
+ * Sets the dispatch queue used by the transport
+ *
+ * @param queue
+ */
+ void setDispatchQueue(DispatchQueue queue);
+
+ /**
+ * suspend accepting new transports
+ */
+ void suspend();
+
+ /**
+ * resume accepting new transports
+ */
+ void resume();
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/AsyncInvocationStrategy.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/AsyncInvocationStrategy.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/AsyncInvocationStrategy.java
new file mode 100644
index 0000000..33b4b23
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/AsyncInvocationStrategy.java
@@ -0,0 +1,188 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.tcp;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.rmi.RemoteException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.aries.rsa.provider.fastbin.api.AsyncCallback;
+import org.apache.aries.rsa.provider.fastbin.api.SerializationStrategy;
+import org.fusesource.hawtbuf.DataByteArrayInputStream;
+import org.fusesource.hawtbuf.DataByteArrayOutputStream;
+import org.fusesource.hawtdispatch.Dispatch;
+import org.fusesource.hawtdispatch.DispatchQueue;
+
+/**
+ * <p>
+ * </p>
+ *
+ */
+public class AsyncInvocationStrategy implements InvocationStrategy {
+
+ public static final AsyncInvocationStrategy INSTANCE = new AsyncInvocationStrategy();
+
+ static public boolean isAsyncMethod(Method method) {
+ Class<?>[] types = method.getParameterTypes();
+ return types.length != 0 && types[types.length - 1] == AsyncCallback.class;
+ }
+
+
+ private class AsyncResponseFuture implements ResponseFuture {
+
+ private final ClassLoader loader;
+ private final Method method;
+ private final AsyncCallback callback;
+ private final SerializationStrategy serializationStrategy;
+ private final DispatchQueue queue;
+
+ public AsyncResponseFuture(ClassLoader loader, Method method, AsyncCallback callback, SerializationStrategy serializationStrategy, DispatchQueue queue) {
+ this.loader = loader;
+ this.method = method;
+ this.callback = callback;
+ this.serializationStrategy = serializationStrategy;
+ this.queue = queue;
+ }
+
+ public void set(final DataByteArrayInputStream source) {
+ if( queue!=null ) {
+ queue.execute(new Runnable() {
+ public void run() {
+ decodeIt(source);
+ }
+ });
+ } else {
+ decodeIt(source);
+ }
+ }
+
+ private void decodeIt(DataByteArrayInputStream source) {
+ try {
+ serializationStrategy.decodeResponse(loader, getResultType(method), source, callback);
+ } catch (Throwable e) {
+ e.printStackTrace();
+ }
+ }
+
+ public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
+ // TODO: we could store the timeout so we can time out the async request...
+ return null;
+ }
+
+ @Override
+ public void fail(Throwable throwable) {
+ callback.onFailure(throwable);
+ }
+ }
+
+ public ResponseFuture request(SerializationStrategy serializationStrategy, ClassLoader loader, Method method, Object[] args, DataByteArrayOutputStream target) throws Exception {
+ if(!isAsyncMethod(method)) {
+ throw new IllegalArgumentException("Invalid async method declaration: last argument is not a RequestCallback");
+ }
+
+ Class[] new_types = payloadTypes(method);
+ Object[] new_args = new Object[args.length-1];
+ System.arraycopy(args, 0, new_args, 0, new_args.length);
+
+ serializationStrategy.encodeRequest(loader, new_types, new_args, target);
+
+ return new AsyncResponseFuture(loader, method, (AsyncCallback) args[args.length-1], serializationStrategy, Dispatch.getCurrentQueue());
+ }
+
+ static private Class<?>[] payloadTypes(Method method) {
+ Class<?>[] types = method.getParameterTypes();
+ Class<?>[] new_types = new Class<?>[types.length-1];
+ System.arraycopy(types, 0, new_types, 0, new_types.length);
+ return new_types;
+ }
+
+ static private Class getResultType(Method method) {
+ Type[] types = method.getGenericParameterTypes();
+ ParameterizedType t = (ParameterizedType) types[types.length-1];
+ return (Class) t.getActualTypeArguments()[0];
+ }
+
+
+ class ServiceResponse {
+
+ private final ClassLoader loader;
+ private final Method method;
+ private final DataByteArrayOutputStream responseStream;
+ private final Runnable onComplete;
+ private final SerializationStrategy serializationStrategy;
+ private final int pos;
+ // Used to protect against sending multiple responses.
+ final AtomicBoolean responded = new AtomicBoolean(false);
+
+ public ServiceResponse(ClassLoader loader, Method method, DataByteArrayOutputStream responseStream, Runnable onComplete, SerializationStrategy serializationStrategy) {
+ this.loader = loader;
+ this.method = method;
+ this.responseStream = responseStream;
+ this.onComplete = onComplete;
+ this.serializationStrategy = serializationStrategy;
+ pos = responseStream.position();
+ }
+
+ public void send(Throwable error, Object value) {
+ if( responded.compareAndSet(false, true) ) {
+ Class resultType = getResultType(method);
+ try {
+ serializationStrategy.encodeResponse(loader, resultType, value, error, responseStream);
+ } catch (Exception e) {
+ // we failed to encode the response.. reposition and write that error.
+ try {
+ responseStream.position(pos);
+ serializationStrategy.encodeResponse(loader, resultType, value, new RemoteException(e.toString()), responseStream);
+ } catch (Exception unexpected) {
+ unexpected.printStackTrace();
+ }
+ } finally {
+ onComplete.run();
+ }
+ }
+ }
+
+
+ }
+ public void service(SerializationStrategy serializationStrategy, ClassLoader loader, Method method, Object target, DataByteArrayInputStream requestStream, final DataByteArrayOutputStream responseStream, final Runnable onComplete) {
+
+ final ServiceResponse helper = new ServiceResponse(loader, method, responseStream, onComplete, serializationStrategy);
+ try {
+
+ Object[] new_args = new Object[method.getParameterTypes().length];
+ serializationStrategy.decodeRequest(loader, payloadTypes(method), requestStream, new_args);
+ new_args[new_args.length-1] = new AsyncCallback<Object>() {
+ public void onSuccess(Object result) {
+ helper.send(null, result);
+ }
+ public void onFailure(Throwable failure) {
+ helper.send(failure, null);
+ }
+ };
+ method.invoke(target, new_args);
+
+ } catch (Throwable t) {
+ helper.send(t, null);
+ }
+
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/BlockingInvocationStrategy.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/BlockingInvocationStrategy.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/BlockingInvocationStrategy.java
new file mode 100644
index 0000000..d695e4f
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/BlockingInvocationStrategy.java
@@ -0,0 +1,126 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.tcp;
+
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.rmi.RemoteException;
+import java.util.concurrent.Callable;
+import java.util.concurrent.FutureTask;
+
+import org.apache.aries.rsa.provider.fastbin.api.AsyncCallback;
+import org.apache.aries.rsa.provider.fastbin.api.SerializationStrategy;
+import org.fusesource.hawtbuf.DataByteArrayInputStream;
+import org.fusesource.hawtbuf.DataByteArrayOutputStream;
+import org.fusesource.hawtdispatch.Dispatch;
+
+/**
+ * <p>
+ * </p>
+ *
+ */
+public class BlockingInvocationStrategy implements InvocationStrategy {
+
+ public static final BlockingInvocationStrategy INSTANCE = new BlockingInvocationStrategy();
+
+ private static final Callable<Object> EMPTY_CALLABLE = new Callable<Object>() {
+ public Object call() {
+ return null;
+ }
+ };
+
+ private class BlockingResponseFuture extends FutureTask<Object> implements ResponseFuture, AsyncCallback {
+
+ private final ClassLoader loader;
+ private final Method method;
+ private final SerializationStrategy serializationStrategy;
+
+ public BlockingResponseFuture(ClassLoader loader, Method method, SerializationStrategy serializationStrategy) {
+ super(EMPTY_CALLABLE);
+ this.loader = loader;
+ this.method = method;
+ this.serializationStrategy = serializationStrategy;
+ }
+
+ public void set(DataByteArrayInputStream source) throws IOException, ClassNotFoundException {
+ try {
+ serializationStrategy.decodeResponse(loader, method.getReturnType(), source, this);
+ } catch (Throwable e) {
+ super.setException(e);
+ }
+ }
+
+ public void fail(Throwable failure) {
+ super.setException(failure);
+ }
+
+ public void onSuccess(Object result) {
+ super.set(result);
+ }
+
+ public void onFailure(Throwable failure) {
+ super.setException(failure);
+ }
+ }
+
+ public ResponseFuture request(SerializationStrategy serializationStrategy, ClassLoader loader, Method method, Object[] args, DataByteArrayOutputStream target) throws Exception {
+
+ assert Dispatch.getCurrentQueue() == null : "You should not do blocking RPC class when executing on a dispatch queue";
+
+ serializationStrategy.encodeRequest(loader, method.getParameterTypes(), args, target);
+ return new BlockingResponseFuture(loader, method, serializationStrategy);
+ }
+
+ public void service(SerializationStrategy serializationStrategy, ClassLoader loader, Method method, Object target, DataByteArrayInputStream requestStream, DataByteArrayOutputStream responseStream, Runnable onComplete) {
+
+ int pos = responseStream.position();
+ try {
+
+ Object value = null;
+ Throwable error = null;
+
+ try {
+ Class<?>[] types = method.getParameterTypes();
+ final Object[] args = new Object[types.length];
+ serializationStrategy.decodeRequest(loader, types, requestStream, args);
+ value = method.invoke(target, args);
+ } catch (Throwable t) {
+ if (t instanceof InvocationTargetException) {
+ error = t.getCause();
+ } else {
+ error = t;
+ }
+ }
+
+ serializationStrategy.encodeResponse(loader, method.getReturnType(), value, error, responseStream);
+
+ } catch(Exception e) {
+
+ // we failed to encode the response.. reposition and write that error.
+ try {
+ responseStream.position(pos);
+ serializationStrategy.encodeResponse(loader, method.getReturnType(), null, new RemoteException(e.toString()), responseStream);
+ } catch (Exception unexpected) {
+ unexpected.printStackTrace();
+ }
+
+ } finally {
+ onComplete.run();
+ }
+ }
+
+}
[2/3] aries-rsa git commit: [ARIES-1526] Add a fast nio/protobuf
provider
Posted by gn...@apache.org.
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/ClientInvokerImpl.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/ClientInvokerImpl.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/ClientInvokerImpl.java
new file mode 100644
index 0000000..562fea7
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/ClientInvokerImpl.java
@@ -0,0 +1,327 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.tcp;
+
+import java.io.IOException;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.WeakHashMap;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.aries.rsa.provider.fastbin.api.Dispatched;
+import org.apache.aries.rsa.provider.fastbin.api.ObjectSerializationStrategy;
+import org.apache.aries.rsa.provider.fastbin.api.Serialization;
+import org.apache.aries.rsa.provider.fastbin.api.SerializationStrategy;
+import org.apache.aries.rsa.provider.fastbin.io.ClientInvoker;
+import org.apache.aries.rsa.provider.fastbin.io.ProtocolCodec;
+import org.apache.aries.rsa.provider.fastbin.io.Transport;
+import org.fusesource.hawtbuf.Buffer;
+import org.fusesource.hawtbuf.BufferEditor;
+import org.fusesource.hawtbuf.DataByteArrayInputStream;
+import org.fusesource.hawtbuf.DataByteArrayOutputStream;
+import org.fusesource.hawtbuf.UTF8Buffer;
+import org.fusesource.hawtdispatch.DispatchQueue;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ClientInvokerImpl implements ClientInvoker, Dispatched {
+
+ public static final long DEFAULT_TIMEOUT = TimeUnit.MINUTES.toMillis(5);
+
+ protected static final Logger LOGGER = LoggerFactory.getLogger(ClientInvokerImpl.class);
+
+ private final static HashMap<Class,String> CLASS_TO_PRIMITIVE = new HashMap<Class, String>(8, 1.0F);
+
+ static {
+ CLASS_TO_PRIMITIVE.put(boolean.class,"Z");
+ CLASS_TO_PRIMITIVE.put(byte.class,"B");
+ CLASS_TO_PRIMITIVE.put(char.class,"C");
+ CLASS_TO_PRIMITIVE.put(short.class,"S");
+ CLASS_TO_PRIMITIVE.put(int.class,"I");
+ CLASS_TO_PRIMITIVE.put(long.class,"J");
+ CLASS_TO_PRIMITIVE.put(float.class,"F");
+ CLASS_TO_PRIMITIVE.put(double.class,"D");
+ }
+
+ protected final AtomicLong correlationGenerator = new AtomicLong();
+ protected final DispatchQueue queue;
+ protected final Map<String, TransportPool> transports = new HashMap<String, TransportPool>();
+ protected final AtomicBoolean running = new AtomicBoolean(false);
+ protected final Map<Long, ResponseFuture> requests = new HashMap<Long, ResponseFuture>();
+ protected final long timeout;
+ protected final Map<String, SerializationStrategy> serializationStrategies;
+
+ public ClientInvokerImpl(DispatchQueue queue, Map<String, SerializationStrategy> serializationStrategies) {
+ this(queue, DEFAULT_TIMEOUT, serializationStrategies);
+ }
+
+ public ClientInvokerImpl(DispatchQueue queue, long timeout, Map<String, SerializationStrategy> serializationStrategies) {
+ this.queue = queue;
+ this.timeout = timeout;
+ this.serializationStrategies = serializationStrategies;
+ }
+
+ public DispatchQueue queue() {
+ return queue;
+ }
+
+ public void start() throws Exception {
+ start(null);
+ }
+
+ public void start(Runnable onComplete) throws Exception {
+ running.set(true);
+ if (onComplete != null) {
+ onComplete.run();
+ }
+ }
+
+ public void stop() {
+ stop(null);
+ }
+
+ public void stop(final Runnable onComplete) {
+ if (running.compareAndSet(true, false)) {
+ queue().execute(new Runnable() {
+ public void run() {
+ final AtomicInteger latch = new AtomicInteger(transports.size());
+ final Runnable countDown = new Runnable() {
+ public void run() {
+ if (latch.decrementAndGet() == 0) {
+ if (onComplete != null) {
+ onComplete.run();
+ }
+ }
+ }
+ };
+ for (TransportPool pool : transports.values()) {
+ pool.stop(countDown);
+ }
+ }
+ });
+ } else {
+ if (onComplete != null) {
+ onComplete.run();
+ }
+ }
+ }
+
+ public InvocationHandler getProxy(String address, String service, ClassLoader classLoader) {
+ return new ProxyInvocationHandler(address, service, classLoader);
+ }
+
+ protected void onCommand(TransportPool pool, Object data) {
+ try {
+ DataByteArrayInputStream bais = new DataByteArrayInputStream( (Buffer) data);
+ int size = bais.readInt();
+ long correlation = bais.readVarLong();
+ pool.onDone(correlation);
+ ResponseFuture response = requests.remove(correlation);
+ if( response!=null ) {
+ response.set(bais);
+ }
+ } catch (Exception e) {
+ LOGGER.info("Error while reading response", e);
+ }
+ }
+
+ protected void onFailure(Object id, Throwable throwable) {
+ ResponseFuture response = requests.remove(id);
+ if( response!=null ) {
+ response.fail(throwable);
+ }
+ }
+
+ static final WeakHashMap<Method, MethodData> method_cache = new WeakHashMap<Method, MethodData>();
+
+ static class MethodData {
+ private final SerializationStrategy serializationStrategy;
+ final Buffer signature;
+ final InvocationStrategy invocationStrategy;
+
+ MethodData(InvocationStrategy invocationStrategy, SerializationStrategy serializationStrategy, Buffer signature) {
+ this.invocationStrategy = invocationStrategy;
+ this.serializationStrategy = serializationStrategy;
+ this.signature = signature;
+ }
+ }
+
+ private MethodData getMethodData(Method method) throws IOException {
+ MethodData rc = null;
+ synchronized (method_cache) {
+ rc = method_cache.get(method);
+ }
+ if( rc==null ) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(method.getName());
+ sb.append(",");
+ Class<?>[] types = method.getParameterTypes();
+ for(int i=0; i < types.length; i++) {
+ if( i!=0 ) {
+ sb.append(",");
+ }
+ sb.append(encodeClassName(types[i]));
+ }
+ Buffer signature = new UTF8Buffer(sb.toString()).buffer();
+
+ Serialization annotation = method.getAnnotation(Serialization.class);
+ SerializationStrategy serializationStrategy;
+ if( annotation!=null ) {
+ serializationStrategy = serializationStrategies.get(annotation.value());
+ if( serializationStrategy==null ) {
+ throw new RuntimeException("Could not find the serialization strategy named: "+annotation.value());
+ }
+ } else {
+ serializationStrategy = ObjectSerializationStrategy.INSTANCE;
+ }
+
+ final InvocationStrategy strategy;
+ if( AsyncInvocationStrategy.isAsyncMethod(method) ) {
+ strategy = AsyncInvocationStrategy.INSTANCE;
+ } else {
+ strategy = BlockingInvocationStrategy.INSTANCE;
+ }
+
+ rc = new MethodData(strategy, serializationStrategy, signature);
+ synchronized (method_cache) {
+ method_cache.put(method, rc);
+ }
+ }
+ return rc;
+ }
+
+ String encodeClassName(Class<?> type) {
+ if( type.getComponentType()!=null ) {
+ return "["+ encodeClassName(type.getComponentType());
+ }
+ if( type.isPrimitive() ) {
+ return CLASS_TO_PRIMITIVE.get(type);
+ } else {
+ return "L"+type.getName();
+ }
+ }
+
+ protected Object request(ProxyInvocationHandler handler, final String address, final UTF8Buffer service, final ClassLoader classLoader, final Method method, final Object[] args) throws Exception {
+ if (!running.get()) {
+ throw new IllegalStateException("DOSGi Client stopped");
+ }
+
+ final long correlation = correlationGenerator.incrementAndGet();
+
+ // Encode the request before we try to pass it onto
+ // IO layers so that #1 we can report encoding error back to the caller
+ // and #2 reduce CPU load done in the execution queue since it's
+ // serially executed.
+
+ DataByteArrayOutputStream baos = new DataByteArrayOutputStream((int) (handler.lastRequestSize*1.10));
+ baos.writeInt(0); // we don't know the size yet...
+ baos.writeVarLong(correlation);
+ writeBuffer(baos, service);
+
+ MethodData methodData = getMethodData(method);
+ writeBuffer(baos, methodData.signature);
+
+ final ResponseFuture future = methodData.invocationStrategy.request(methodData.serializationStrategy, classLoader, method, args, baos);
+
+ // toBuffer() is better than toByteArray() since it avoids an
+ // array copy.
+ final Buffer command = baos.toBuffer();
+
+
+ // Update the field size.
+ BufferEditor editor = command.buffer().bigEndianEditor();
+ editor.writeInt(command.length);
+ handler.lastRequestSize = command.length;
+
+ queue().execute(new Runnable() {
+ public void run() {
+ try {
+ TransportPool pool = transports.get(address);
+ if (pool == null) {
+ pool = new InvokerTransportPool(address, queue());
+ transports.put(address, pool);
+ pool.start();
+ }
+ requests.put(correlation, future);
+ pool.offer(command, correlation);
+ } catch (Exception e) {
+ LOGGER.info("Error while sending request", e);
+ future.fail(e);
+ }
+ }
+ });
+
+ // TODO: make that configurable, that's only for tests
+ return future.get(timeout, TimeUnit.MILLISECONDS);
+ }
+
+ private void writeBuffer(DataByteArrayOutputStream baos, Buffer value) throws IOException {
+ baos.writeVarInt(value.length);
+ baos.write(value);
+ }
+
+ protected class ProxyInvocationHandler implements InvocationHandler {
+
+ final String address;
+ final UTF8Buffer service;
+ final ClassLoader classLoader;
+ int lastRequestSize = 250;
+
+ public ProxyInvocationHandler(String address, String service, ClassLoader classLoader) {
+ this.address = address;
+ this.service = new UTF8Buffer(service);
+ this.classLoader = classLoader;
+ }
+
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ return request(this, address, service, classLoader, method, args);
+ }
+
+ }
+
+ protected class InvokerTransportPool extends TransportPool {
+
+ public InvokerTransportPool(String uri, DispatchQueue queue) {
+ super(uri, queue, TransportPool.DEFAULT_POOL_SIZE, timeout << 1);
+ }
+
+ @Override
+ protected Transport createTransport(String uri) throws Exception {
+ return new TcpTransportFactory().connect(uri);
+ }
+
+ @Override
+ protected ProtocolCodec createCodec() {
+ return new LengthPrefixedCodec();
+ }
+
+ @Override
+ protected void onCommand(Object command) {
+ ClientInvokerImpl.this.onCommand(this, command);
+ }
+
+ @Override
+ protected void onFailure(Object id, Throwable throwable) {
+ ClientInvokerImpl.this.onFailure(id, throwable);
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/InvocationStrategy.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/InvocationStrategy.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/InvocationStrategy.java
new file mode 100644
index 0000000..8b3901b
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/InvocationStrategy.java
@@ -0,0 +1,34 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.tcp;
+
+import java.lang.reflect.Method;
+
+import org.apache.aries.rsa.provider.fastbin.api.SerializationStrategy;
+import org.fusesource.hawtbuf.DataByteArrayInputStream;
+import org.fusesource.hawtbuf.DataByteArrayOutputStream;
+
+/**
+ * <p>
+ * </p>
+ *
+ */
+public interface InvocationStrategy {
+
+ public ResponseFuture request(SerializationStrategy serializationStrategy, ClassLoader loader, Method method, Object[] args, DataByteArrayOutputStream requestStream) throws Exception;
+
+ void service(SerializationStrategy serializationStrategy, ClassLoader loader, Method method, Object target, DataByteArrayInputStream requestStream, DataByteArrayOutputStream responseStream, Runnable onComplete);
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/LengthPrefixedCodec.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/LengthPrefixedCodec.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/LengthPrefixedCodec.java
new file mode 100644
index 0000000..ca8c588
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/LengthPrefixedCodec.java
@@ -0,0 +1,175 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.tcp;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.net.ProtocolException;
+import java.net.SocketException;
+import java.nio.ByteBuffer;
+import java.nio.channels.ReadableByteChannel;
+import java.nio.channels.SocketChannel;
+import java.nio.channels.WritableByteChannel;
+import java.util.LinkedList;
+import java.util.Queue;
+
+import org.apache.aries.rsa.provider.fastbin.io.ProtocolCodec;
+import org.fusesource.hawtbuf.Buffer;
+
+public class LengthPrefixedCodec implements ProtocolCodec {
+
+
+ final int write_buffer_size = 1024 * 64;
+ long write_counter = 0L;
+ WritableByteChannel write_channel;
+
+ final Queue<ByteBuffer> next_write_buffers = new LinkedList<ByteBuffer>();
+ int next_write_size = 0;
+
+ public boolean full() {
+ return false;
+ }
+
+ protected boolean empty() {
+ if (next_write_size > 0) {
+ return false;
+ }
+ if (!next_write_buffers.isEmpty()) {
+ for (ByteBuffer b : next_write_buffers) {
+ if (b.remaining() > 0) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ public void setWritableByteChannel(WritableByteChannel channel) {
+ this.write_channel = channel;
+ if (channel instanceof SocketChannel) {
+ try {
+ ((SocketChannel) channel).socket().setSendBufferSize(write_buffer_size);
+ } catch (SocketException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ public BufferState write(Object value) throws IOException {
+ if (full()) {
+ return BufferState.FULL;
+ } else {
+ boolean wasEmpty = empty();
+ Buffer buffer = (Buffer) value;
+ next_write_size += buffer.length;
+ next_write_buffers.add(buffer.toByteBuffer());
+ return wasEmpty ? BufferState.WAS_EMPTY : BufferState.NOT_EMPTY;
+ }
+ }
+
+ public BufferState flush() throws IOException {
+ final long writeCounterBeforeFlush = write_counter;
+ while(!next_write_buffers.isEmpty()) {
+ final ByteBuffer nextBuffer = next_write_buffers.peek();
+ if (nextBuffer.remaining() < 1) {
+ next_write_buffers.remove();
+ continue;
+ }
+ int bytesWritten = write_channel.write(nextBuffer);
+ write_counter += bytesWritten;
+ next_write_size -= bytesWritten;
+ if (nextBuffer.remaining() > 0) {
+ break;
+ }
+ }
+ if (empty()) {
+ if (writeCounterBeforeFlush == write_counter) {
+ return BufferState.WAS_EMPTY;
+ } else {
+ return BufferState.EMPTY;
+ }
+ }
+ return BufferState.NOT_EMPTY;
+ }
+
+ public long getWriteCounter() {
+ return write_counter;
+ }
+
+ long read_counter = 0L;
+ int read_buffer_size = 1024 * 64;
+ ReadableByteChannel read_channel = null;
+ ByteBuffer read_buffer = ByteBuffer.allocate(4);
+
+
+ public void setReadableByteChannel(ReadableByteChannel channel) {
+ read_channel = channel;
+ if (channel instanceof SocketChannel) {
+ try {
+ ((SocketChannel) channel).socket().setReceiveBufferSize(read_buffer_size);
+ } catch (SocketException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ public Object read() throws IOException {
+ while(true) {
+ if( read_buffer.remaining()!=0 ) {
+ // keep reading from the channel until we fill the read buffer..
+ int count = read_channel.read(read_buffer);
+ if (count == -1) {
+ throw new EOFException("Peer disconnected");
+ } else if (count == 0) {
+ return null;
+ }
+ read_counter += count;
+ } else {
+ //read buffer is full.. interpret it..
+ read_buffer.flip();
+
+ if( read_buffer.capacity() == 4 ) {
+ // Finding out the
+ int size = read_buffer.getInt(0);
+ if( size < 4 ) {
+ throw new ProtocolException("Expecting a size greater than 3");
+ }
+ if( size == 4 ) {
+ // weird.. empty frame.. guess it could happen.
+ Buffer rc = new Buffer(read_buffer);
+ read_buffer = ByteBuffer.allocate(4);
+ return rc;
+ } else {
+ // Resize to the right size.. this resumes the reads..
+ ByteBuffer next = ByteBuffer.allocate(size);
+ next.putInt(size);
+ read_buffer = next;
+ }
+ } else {
+ // finish loading the rest of the buffer..
+ Buffer rc = new Buffer(read_buffer);
+ read_buffer = ByteBuffer.allocate(4);
+ return rc;
+ }
+ }
+ }
+ }
+
+ public long getReadCounter() {
+ return read_counter;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/ResponseFuture.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/ResponseFuture.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/ResponseFuture.java
new file mode 100644
index 0000000..2744f9a
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/ResponseFuture.java
@@ -0,0 +1,31 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.tcp;
+
+import java.util.concurrent.TimeUnit;
+
+import org.fusesource.hawtbuf.DataByteArrayInputStream;
+
+/**
+ * <p>
+ * </p>
+ *
+ */
+public interface ResponseFuture {
+ void set(DataByteArrayInputStream responseStream) throws Exception;
+ Object get(long timeout, TimeUnit unit) throws Exception;
+ void fail(Throwable throwable);
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/ServerInvokerImpl.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/ServerInvokerImpl.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/ServerInvokerImpl.java
new file mode 100644
index 0000000..9a12dbd
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/ServerInvokerImpl.java
@@ -0,0 +1,314 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.tcp;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.lang.reflect.Array;
+import java.lang.reflect.Method;
+import java.net.InetSocketAddress;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+import org.apache.aries.rsa.provider.fastbin.api.Dispatched;
+import org.apache.aries.rsa.provider.fastbin.api.ObjectSerializationStrategy;
+import org.apache.aries.rsa.provider.fastbin.api.Serialization;
+import org.apache.aries.rsa.provider.fastbin.api.SerializationStrategy;
+import org.apache.aries.rsa.provider.fastbin.io.ServerInvoker;
+import org.apache.aries.rsa.provider.fastbin.io.Transport;
+import org.apache.aries.rsa.provider.fastbin.io.TransportAcceptListener;
+import org.apache.aries.rsa.provider.fastbin.io.TransportListener;
+import org.apache.aries.rsa.provider.fastbin.io.TransportServer;
+import org.fusesource.hawtbuf.Buffer;
+import org.fusesource.hawtbuf.BufferEditor;
+import org.fusesource.hawtbuf.DataByteArrayInputStream;
+import org.fusesource.hawtbuf.DataByteArrayOutputStream;
+import org.fusesource.hawtbuf.UTF8Buffer;
+import org.fusesource.hawtdispatch.DispatchQueue;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ServerInvokerImpl implements ServerInvoker, Dispatched {
+
+ protected static final Logger LOGGER = LoggerFactory.getLogger(ServerInvokerImpl.class);
+ static private final HashMap<String, Class> PRIMITIVE_TO_CLASS = new HashMap<String, Class>(8, 1.0F);
+ static {
+ PRIMITIVE_TO_CLASS.put("Z", boolean.class);
+ PRIMITIVE_TO_CLASS.put("B", byte.class);
+ PRIMITIVE_TO_CLASS.put("C", char.class);
+ PRIMITIVE_TO_CLASS.put("S", short.class);
+ PRIMITIVE_TO_CLASS.put("I", int.class);
+ PRIMITIVE_TO_CLASS.put("J", long.class);
+ PRIMITIVE_TO_CLASS.put("F", float.class);
+ PRIMITIVE_TO_CLASS.put("D", double.class);
+ }
+
+ protected final ExecutorService blockingExecutor = Executors.newFixedThreadPool(8);
+ protected final DispatchQueue queue;
+ private final Map<String, SerializationStrategy> serializationStrategies;
+ protected final TransportServer server;
+ protected final Map<UTF8Buffer, ServiceFactoryHolder> holders = new HashMap<UTF8Buffer, ServiceFactoryHolder>();
+
+ static class MethodData {
+
+ private final SerializationStrategy serializationStrategy;
+ final InvocationStrategy invocationStrategy;
+ final Method method;
+
+ MethodData(InvocationStrategy invocationStrategy, SerializationStrategy serializationStrategy, Method method) {
+ this.invocationStrategy = invocationStrategy;
+ this.serializationStrategy = serializationStrategy;
+ this.method = method;
+ }
+ }
+
+ class ServiceFactoryHolder {
+
+ private final ServiceFactory factory;
+ private final ClassLoader loader;
+ private final Class clazz;
+ private HashMap<Buffer, MethodData> method_cache = new HashMap<Buffer, MethodData>();
+
+ public ServiceFactoryHolder(ServiceFactory factory, ClassLoader loader) {
+ this.factory = factory;
+ this.loader = loader;
+ Object o = factory.get();
+ clazz = o.getClass();
+ factory.unget();
+ }
+
+ private MethodData getMethodData(Buffer data) throws IOException, NoSuchMethodException, ClassNotFoundException {
+ MethodData rc = method_cache.get(data);
+ if( rc == null ) {
+ String[] parts = data.utf8().toString().split(",");
+ String name = parts[0];
+ Class params[] = new Class[parts.length-1];
+ for( int i=0; i < params.length; i++) {
+ params[i] = decodeClass(parts[i+1]);
+ }
+ Method method = clazz.getMethod(name, params);
+
+
+ Serialization annotation = method.getAnnotation(Serialization.class);
+ SerializationStrategy serializationStrategy;
+ if( annotation!=null ) {
+ serializationStrategy = serializationStrategies.get(annotation.value());
+ if( serializationStrategy==null ) {
+ throw new RuntimeException("Could not find the serialization strategy named: "+annotation.value());
+ }
+ } else {
+ serializationStrategy = ObjectSerializationStrategy.INSTANCE;
+ }
+
+
+ final InvocationStrategy invocationStrategy;
+ if( AsyncInvocationStrategy.isAsyncMethod(method) ) {
+ invocationStrategy = AsyncInvocationStrategy.INSTANCE;
+ } else {
+ invocationStrategy = BlockingInvocationStrategy.INSTANCE;
+ }
+
+ rc = new MethodData(invocationStrategy, serializationStrategy, method);
+ method_cache.put(data, rc);
+ }
+ return rc;
+ }
+
+ private Class<?> decodeClass(String s) throws ClassNotFoundException {
+ if( s.startsWith("[")) {
+ Class<?> nested = decodeClass(s.substring(1));
+ return Array.newInstance(nested,0).getClass();
+ }
+ String c = s.substring(0,1);
+ if( c.equals("L") ) {
+ return loader.loadClass(s.substring(1));
+ } else {
+ return PRIMITIVE_TO_CLASS.get(c);
+ }
+ }
+
+ }
+
+
+ public ServerInvokerImpl(String address, DispatchQueue queue, Map<String, SerializationStrategy> serializationStrategies) throws Exception {
+ this.queue = queue;
+ this.serializationStrategies = serializationStrategies;
+ this.server = new TcpTransportFactory().bind(address);
+ this.server.setDispatchQueue(queue);
+ this.server.setAcceptListener(new InvokerAcceptListener());
+ }
+
+ public InetSocketAddress getSocketAddress() {
+ return this.server.getSocketAddress();
+ }
+
+
+ public DispatchQueue queue() {
+ return queue;
+ }
+
+ public String getConnectAddress() {
+ return this.server.getConnectAddress();
+ }
+
+ public void registerService(final String id, final ServiceFactory service, final ClassLoader classLoader) {
+ queue().execute(new Runnable() {
+ public void run() {
+ holders.put(new UTF8Buffer(id), new ServiceFactoryHolder(service, classLoader));
+ }
+ });
+ }
+
+ public void unregisterService(final String id) {
+ queue().execute(new Runnable() {
+ public void run() {
+ holders.remove(new UTF8Buffer(id));
+ }
+ });
+ }
+
+ public void start() throws Exception {
+ start(null);
+ }
+
+ public void start(Runnable onComplete) throws Exception {
+ this.server.start(onComplete);
+ }
+
+ public void stop() {
+ stop(null);
+ }
+
+ public void stop(final Runnable onComplete) {
+ this.server.stop(new Runnable() {
+ public void run() {
+ blockingExecutor.shutdown();
+ if (onComplete != null) {
+ onComplete.run();
+ }
+ }
+ });
+ }
+
+
+ protected void onCommand(final Transport transport, Object data) {
+ try {
+ final DataByteArrayInputStream bais = new DataByteArrayInputStream((Buffer) data);
+ final int size = bais.readInt();
+ final long correlation = bais.readVarLong();
+
+ // Use UTF8Buffer instead of string to avoid encoding/decoding UTF-8 strings
+ // for every request.
+ final UTF8Buffer service = readBuffer(bais).utf8();
+ final Buffer encoded_method = readBuffer(bais);
+
+ final ServiceFactoryHolder holder = holders.get(service);
+ final MethodData methodData = holder.getMethodData(encoded_method);
+
+ final Object svc = holder.factory.get();
+
+ Runnable task = new Runnable() {
+ public void run() {
+
+ final DataByteArrayOutputStream baos = new DataByteArrayOutputStream();
+ try {
+ baos.writeInt(0); // make space for the size field.
+ baos.writeVarLong(correlation);
+ } catch (IOException e) { // should not happen
+ throw new RuntimeException(e);
+ }
+
+ // Lets decode the remaining args on the target's executor
+ // to take cpu load off the
+ methodData.invocationStrategy.service(methodData.serializationStrategy, holder.loader, methodData.method, svc, bais, baos, new Runnable() {
+ public void run() {
+ holder.factory.unget();
+ final Buffer command = baos.toBuffer();
+
+ // Update the size field.
+ BufferEditor editor = command.buffer().bigEndianEditor();
+ editor.writeInt(command.length);
+
+ queue().execute(new Runnable() {
+ public void run() {
+ transport.offer(command);
+ }
+ });
+ }
+ });
+ }
+ };
+
+ Executor executor;
+ if( svc instanceof Dispatched ) {
+ executor = ((Dispatched)svc).queue();
+ } else {
+ executor = blockingExecutor;
+ }
+ executor.execute(task);
+
+ } catch (Exception e) {
+ LOGGER.info("Error while reading request", e);
+ }
+ }
+
+ private Buffer readBuffer(DataByteArrayInputStream bais) throws IOException {
+ byte b[] = new byte[bais.readVarInt()];
+ bais.readFully(b);
+ return new Buffer(b);
+ }
+
+ class InvokerAcceptListener implements TransportAcceptListener {
+
+ public void onAccept(TransportServer transportServer, TcpTransport transport) {
+ transport.setProtocolCodec(new LengthPrefixedCodec());
+ transport.setDispatchQueue(queue());
+ transport.setTransportListener(new InvokerTransportListener());
+ transport.start();
+ }
+
+ public void onAcceptError(TransportServer transportServer, Exception error) {
+ LOGGER.info("Error accepting incoming connection", error);
+ }
+ }
+
+ class InvokerTransportListener implements TransportListener {
+
+ public void onTransportCommand(Transport transport, Object command) {
+ ServerInvokerImpl.this.onCommand(transport, command);
+ }
+
+ public void onRefill(Transport transport) {
+ }
+
+ public void onTransportFailure(Transport transport, IOException error) {
+ if (!transport.isDisposed() && !(error instanceof EOFException)) {
+ LOGGER.info("Transport failure", error);
+ }
+ }
+
+ public void onTransportConnected(Transport transport) {
+ transport.resumeRead();
+ }
+
+ public void onTransportDisconnected(Transport transport) {
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransport.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransport.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransport.java
new file mode 100644
index 0000000..ebedf0e
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransport.java
@@ -0,0 +1,828 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.tcp;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.URI;
+import java.net.UnknownHostException;
+import java.nio.ByteBuffer;
+import java.nio.channels.ReadableByteChannel;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.SocketChannel;
+import java.nio.channels.WritableByteChannel;
+import java.util.LinkedList;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.aries.rsa.provider.fastbin.io.ProtocolCodec;
+import org.apache.aries.rsa.provider.fastbin.io.Transport;
+import org.apache.aries.rsa.provider.fastbin.io.TransportListener;
+import org.fusesource.hawtdispatch.Dispatch;
+import org.fusesource.hawtdispatch.DispatchQueue;
+import org.fusesource.hawtdispatch.DispatchSource;
+import org.fusesource.hawtdispatch.Retained;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class TcpTransport implements Transport {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TcpTransport.class);
+
+ protected State _serviceState = CREATED;
+
+ protected Map<String, Object> socketOptions;
+
+ public static class State {
+ public String toString() {
+ return getClass().getSimpleName();
+ }
+ public boolean isStarted() {
+ return false;
+ }
+ }
+
+ static class CallbackSupport extends State {
+ LinkedList<Runnable> callbacks = new LinkedList<Runnable>();
+
+ void add(Runnable r) {
+ if (r != null) {
+ callbacks.add(r);
+ }
+ }
+
+ void done() {
+ for (Runnable callback : callbacks) {
+ callback.run();
+ }
+ }
+ }
+
+ abstract static class SocketState {
+ void onStop(Runnable onCompleted) {
+ }
+ void onCanceled() {
+ }
+ boolean is(Class<? extends SocketState> clazz) {
+ return getClass()==clazz;
+ }
+ }
+
+ public static final State CREATED = new State();
+
+ public static class STARTING extends CallbackSupport {
+ }
+
+ public static final State STARTED = new State() {
+ public boolean isStarted() {
+ return true;
+ }
+ };
+ public static class STOPPING extends CallbackSupport {
+ }
+
+ public static final State STOPPED = new State();
+
+
+ final public void start() {
+ start(null);
+ }
+
+ final public void stop() {
+ stop(null);
+ }
+
+ final public void start(final Runnable onCompleted) {
+ queue().execute(new Runnable() {
+ public void run() {
+ if (_serviceState == CREATED ||
+ _serviceState == STOPPED) {
+ final STARTING state = new STARTING();
+ state.add(onCompleted);
+ _serviceState = state;
+ _start(new Runnable() {
+ public void run() {
+ _serviceState = STARTED;
+ state.done();
+ }
+ });
+ } else if (_serviceState instanceof STARTING) {
+ ((STARTING) _serviceState).add(onCompleted);
+ } else if (_serviceState == STARTED) {
+ if (onCompleted != null) {
+ onCompleted.run();
+ }
+ } else {
+ if (onCompleted != null) {
+ onCompleted.run();
+ }
+ LOG.error("start should not be called from state: " + _serviceState);
+ }
+ }
+ });
+ }
+
+ final public void stop(final Runnable onCompleted) {
+ queue().execute(new Runnable() {
+ public void run() {
+ if (_serviceState == STARTED) {
+ final STOPPING state = new STOPPING();
+ state.add(onCompleted);
+ _serviceState = state;
+ _stop(new Runnable() {
+ public void run() {
+ _serviceState = STOPPED;
+ state.done();
+ }
+ });
+ } else if (_serviceState instanceof STOPPING) {
+ ((STOPPING) _serviceState).add(onCompleted);
+ } else if (_serviceState == STOPPED) {
+ if (onCompleted != null) {
+ onCompleted.run();
+ }
+ } else {
+ if (onCompleted != null) {
+ onCompleted.run();
+ }
+ LOG.error("stop should not be called from state: " + _serviceState);
+ }
+ }
+ });
+ }
+
+ protected State getServiceState() {
+ return _serviceState;
+ }
+
+ static class DISCONNECTED extends SocketState{}
+
+ class CONNECTING extends SocketState{
+ void onStop(Runnable onCompleted) {
+ trace("CONNECTING.onStop");
+ CANCELING state = new CANCELING();
+ socketState = state;
+ state.onStop(onCompleted);
+ }
+ void onCanceled() {
+ trace("CONNECTING.onCanceled");
+ CANCELING state = new CANCELING();
+ socketState = state;
+ state.onCanceled();
+ }
+ }
+
+ class CONNECTED extends SocketState {
+ void onStop(Runnable onCompleted) {
+ trace("CONNECTED.onStop");
+ CANCELING state = new CANCELING();
+ socketState = state;
+ state.add(createDisconnectTask());
+ state.onStop(onCompleted);
+ }
+ void onCanceled() {
+ trace("CONNECTED.onCanceled");
+ CANCELING state = new CANCELING();
+ socketState = state;
+ state.add(createDisconnectTask());
+ state.onCanceled();
+ }
+ Runnable createDisconnectTask() {
+ return new Runnable(){
+ public void run() {
+ listener.onTransportDisconnected(TcpTransport.this);
+ }
+ };
+ }
+ }
+
+ class CANCELING extends SocketState {
+ private LinkedList<Runnable> runnables = new LinkedList<Runnable>();
+ private int remaining;
+ private boolean dispose;
+
+ public CANCELING() {
+ if( readSource!=null ) {
+ remaining++;
+ readSource.cancel();
+ }
+ if( writeSource!=null ) {
+ remaining++;
+ writeSource.cancel();
+ }
+ }
+ void onStop(Runnable onCompleted) {
+ trace("CANCELING.onCompleted");
+ add(onCompleted);
+ dispose = true;
+ }
+ void add(Runnable onCompleted) {
+ if( onCompleted!=null ) {
+ runnables.add(onCompleted);
+ }
+ }
+ void onCanceled() {
+ trace("CANCELING.onCanceled");
+ remaining--;
+ if( remaining!=0 ) {
+ return;
+ }
+ try {
+ channel.close();
+ } catch (IOException ignore) {
+ }
+ socketState = new CANCELED(dispose);
+ for (Runnable runnable : runnables) {
+ runnable.run();
+ }
+ if (dispose) {
+ dispose();
+ }
+ }
+ }
+
+ class CANCELED extends SocketState {
+ private boolean disposed;
+
+ public CANCELED(boolean disposed) {
+ this.disposed=disposed;
+ }
+
+ void onStop(Runnable onCompleted) {
+ trace("CANCELED.onStop");
+ if( !disposed ) {
+ disposed = true;
+ dispose();
+ }
+ onCompleted.run();
+ }
+ }
+
+ protected URI remoteLocation;
+ protected URI localLocation;
+ protected TransportListener listener;
+ protected String remoteAddress;
+ protected ProtocolCodec codec;
+
+ protected SocketChannel channel;
+
+ protected SocketState socketState = new DISCONNECTED();
+
+ protected DispatchQueue dispatchQueue;
+ private DispatchSource readSource;
+ private DispatchSource writeSource;
+
+ protected boolean useLocalHost = true;
+
+ int max_read_rate;
+ int max_write_rate;
+ protected RateLimitingChannel rateLimitingChannel;
+
+ class RateLimitingChannel implements ReadableByteChannel, WritableByteChannel {
+
+ int read_allowance = max_read_rate;
+ boolean read_suspended = false;
+ int read_resume_counter = 0;
+ int write_allowance = max_write_rate;
+ boolean write_suspended = false;
+
+ public void resetAllowance() {
+ if( read_allowance != max_read_rate || write_allowance != max_write_rate) {
+ read_allowance = max_read_rate;
+ write_allowance = max_write_rate;
+ if( write_suspended ) {
+ write_suspended = false;
+ resumeWrite();
+ }
+ if( read_suspended ) {
+ read_suspended = false;
+ resumeRead();
+ for( int i=0; i < read_resume_counter ; i++ ) {
+ resumeRead();
+ }
+ }
+ }
+ }
+
+ public int read(ByteBuffer dst) throws IOException {
+ if( max_read_rate==0 ) {
+ return channel.read(dst);
+ } else {
+ int remaining = dst.remaining();
+ if( read_allowance ==0 || remaining ==0 ) {
+ return 0;
+ }
+
+ int reduction = 0;
+ if( remaining > read_allowance) {
+ reduction = remaining - read_allowance;
+ dst.limit(dst.limit() - reduction);
+ }
+ int rc=0;
+ try {
+ rc = channel.read(dst);
+ read_allowance -= rc;
+ } finally {
+ if( reduction!=0 ) {
+ if( dst.remaining() == 0 ) {
+ // we need to suspend the read now until we get
+ // a new allowance..
+ readSource.suspend();
+ read_suspended = true;
+ }
+ dst.limit(dst.limit() + reduction);
+ }
+ }
+ return rc;
+ }
+ }
+
+ public int write(ByteBuffer src) throws IOException {
+ if( max_write_rate==0 ) {
+ return channel.write(src);
+ } else {
+ int remaining = src.remaining();
+ if( write_allowance ==0 || remaining ==0 ) {
+ return 0;
+ }
+
+ int reduction = 0;
+ if( remaining > write_allowance) {
+ reduction = remaining - write_allowance;
+ src.limit(src.limit() - reduction);
+ }
+ int rc = 0;
+ try {
+ rc = channel.write(src);
+ write_allowance -= rc;
+ } finally {
+ if( reduction!=0 ) {
+ if( src.remaining() == 0 ) {
+ // we need to suspend the read now until we get
+ // a new allowance..
+ write_suspended = true;
+ suspendWrite();
+ }
+ src.limit(src.limit() + reduction);
+ }
+ }
+ return rc;
+ }
+ }
+
+ public boolean isOpen() {
+ return channel.isOpen();
+ }
+
+ public void close() throws IOException {
+ channel.close();
+ }
+
+ public void resumeRead() {
+ if( read_suspended ) {
+ read_resume_counter += 1;
+ } else {
+ _resumeRead();
+ }
+ }
+
+ }
+
+ private final Runnable CANCEL_HANDLER = new Runnable() {
+ public void run() {
+ socketState.onCanceled();
+ }
+ };
+
+ static final class OneWay {
+ final Object command;
+ final Retained retained;
+
+ public OneWay(Object command, Retained retained) {
+ this.command = command;
+ this.retained = retained;
+ }
+ }
+
+ public void connected(SocketChannel channel) throws IOException, Exception {
+ this.channel = channel;
+
+ if( codec !=null ) {
+ initializeCodec();
+ }
+
+ this.channel.configureBlocking(false);
+ this.remoteAddress = channel.socket().getRemoteSocketAddress().toString();
+ channel.socket().setSoLinger(true, 0);
+ channel.socket().setTcpNoDelay(true);
+
+ this.socketState = new CONNECTED();
+ }
+
+ protected void initializeCodec() {
+ codec.setReadableByteChannel(readChannel());
+ codec.setWritableByteChannel(writeChannel());
+ }
+
+ public void connecting(URI remoteLocation, URI localLocation) throws IOException, Exception {
+ this.channel = SocketChannel.open();
+ this.channel.configureBlocking(false);
+ this.remoteLocation = remoteLocation;
+ this.localLocation = localLocation;
+
+ if (localLocation != null) {
+ InetSocketAddress localAddress = new InetSocketAddress(InetAddress.getByName(localLocation.getHost()), localLocation.getPort());
+ channel.socket().bind(localAddress);
+ }
+
+ String host = resolveHostName(remoteLocation.getHost());
+ InetSocketAddress remoteAddress = new InetSocketAddress(host, remoteLocation.getPort());
+ channel.connect(remoteAddress);
+ this.socketState = new CONNECTING();
+ }
+
+
+ public DispatchQueue queue() {
+ return dispatchQueue;
+ }
+
+ public void setDispatchQueue(DispatchQueue queue) {
+ this.dispatchQueue = queue;
+ }
+
+ public void _start(Runnable onCompleted) {
+ try {
+ if (socketState.is(CONNECTING.class) ) {
+ trace("connecting...");
+ // this allows the connect to complete..
+ readSource = Dispatch.createSource(channel, SelectionKey.OP_CONNECT, dispatchQueue);
+ readSource.setEventHandler(new Runnable() {
+ public void run() {
+ if (getServiceState() != STARTED) {
+ return;
+ }
+ try {
+ trace("connected.");
+ channel.finishConnect();
+ readSource.setCancelHandler(null);
+ readSource.cancel();
+ readSource=null;
+ socketState = new CONNECTED();
+ onConnected();
+ } catch (IOException e) {
+ onTransportFailure(e);
+ }
+ }
+ });
+ readSource.setCancelHandler(CANCEL_HANDLER);
+ readSource.resume();
+
+ } else if (socketState.is(CONNECTED.class) ) {
+ dispatchQueue.execute(new Runnable() {
+ public void run() {
+ try {
+ trace("was connected.");
+ onConnected();
+ } catch (IOException e) {
+ onTransportFailure(e);
+ }
+ }
+ });
+ } else {
+ System.err.println("cannot be started. socket state is: "+socketState);
+ }
+ } finally {
+ if( onCompleted!=null ) {
+ onCompleted.run();
+ }
+ }
+ }
+
+ public void _stop(final Runnable onCompleted) {
+ trace("stopping.. at state: "+socketState);
+ socketState.onStop(onCompleted);
+ }
+
+ protected String resolveHostName(String host) throws UnknownHostException {
+ String localName = InetAddress.getLocalHost().getHostName();
+ if (localName != null && isUseLocalHost()) {
+ if (localName.equals(host)) {
+ return "localhost";
+ }
+ }
+ return host;
+ }
+
+ protected void onConnected() throws IOException {
+
+ readSource = Dispatch.createSource(channel, SelectionKey.OP_READ, dispatchQueue);
+ writeSource = Dispatch.createSource(channel, SelectionKey.OP_WRITE, dispatchQueue);
+
+ readSource.setCancelHandler(CANCEL_HANDLER);
+ writeSource.setCancelHandler(CANCEL_HANDLER);
+
+ readSource.setEventHandler(new Runnable() {
+ public void run() {
+ drainInbound();
+ }
+ });
+ writeSource.setEventHandler(new Runnable() {
+ public void run() {
+ drainOutbound();
+ }
+ });
+
+ if( max_read_rate!=0 || max_write_rate!=0 ) {
+ rateLimitingChannel = new RateLimitingChannel();
+ schedualRateAllowanceReset();
+ }
+
+ remoteAddress = channel.socket().getRemoteSocketAddress().toString();
+ listener.onTransportConnected(this);
+ }
+
+ private void schedualRateAllowanceReset() {
+ dispatchQueue.executeAfter(1, TimeUnit.SECONDS, new Runnable(){
+ public void run() {
+ if( !socketState.is(CONNECTED.class) ) {
+ return;
+ }
+ rateLimitingChannel.resetAllowance();
+ schedualRateAllowanceReset();
+ }
+ });
+ }
+
+ private void dispose() {
+ if( readSource!=null ) {
+ readSource.cancel();
+ readSource=null;
+ }
+
+ if( writeSource!=null ) {
+ writeSource.cancel();
+ writeSource=null;
+ }
+ this.codec = null;
+ }
+
+ public void onTransportFailure(IOException error) {
+ listener.onTransportFailure(this, error);
+ socketState.onCanceled();
+ }
+
+
+ public boolean full() {
+ return codec.full();
+ }
+
+ public boolean offer(Object command) {
+ assert Dispatch.getCurrentQueue() == dispatchQueue;
+ try {
+ if (!socketState.is(CONNECTED.class)) {
+ throw new IOException("Not connected.");
+ }
+ if (getServiceState() != STARTED) {
+ throw new IOException("Not running.");
+ }
+
+ ProtocolCodec.BufferState rc = codec.write(command);
+ switch (rc ) {
+ case FULL:
+ return false;
+ default:
+ if( drained ) {
+ drained = false;
+ resumeWrite();
+ }
+ return true;
+ }
+ } catch (IOException e) {
+ onTransportFailure(e);
+ return false;
+ }
+
+ }
+
+
+ boolean drained = true;
+ /**
+ *
+ */
+ protected void drainOutbound() {
+ assert Dispatch.getCurrentQueue() == dispatchQueue;
+ if (getServiceState() != STARTED || !socketState.is(CONNECTED.class)) {
+ return;
+ }
+ try {
+ if( codec.flush() == ProtocolCodec.BufferState.WAS_EMPTY && flush() ) {
+ if( !drained ) {
+ drained = true;
+ suspendWrite();
+ listener.onRefill(this);
+ }
+ }
+ } catch (IOException e) {
+ onTransportFailure(e);
+ }
+ }
+
+ protected boolean flush() throws IOException {
+ return true;
+ }
+
+ protected void drainInbound() {
+ if (!getServiceState().isStarted() || readSource.isSuspended()) {
+ return;
+ }
+ try {
+ long initial = codec.getReadCounter();
+ // Only process upto 64k worth of data at a time so we can give
+ // other connections a chance to process their requests.
+ while( codec.getReadCounter()-initial < 1024*64 ) {
+ Object command = codec.read();
+ if ( command!=null ) {
+ try {
+ listener.onTransportCommand(this, command);
+ } catch (Throwable e) {
+ onTransportFailure(new IOException("Transport listener failure."));
+ }
+
+ // the transport may be suspended after processing a command.
+ if (getServiceState() == STOPPED || readSource.isSuspended()) {
+ return;
+ }
+ } else {
+ return;
+ }
+ }
+ } catch (IOException e) {
+ onTransportFailure(e);
+ }
+ }
+
+
+ public String getRemoteAddress() {
+ return remoteAddress;
+ }
+
+ private boolean assertConnected() {
+ try {
+ if ( !isConnected() ) {
+ throw new IOException("Not connected.");
+ }
+ return true;
+ } catch (IOException e) {
+ onTransportFailure(e);
+ }
+ return false;
+ }
+
+ public void suspendRead() {
+ if( isConnected() && readSource!=null ) {
+ readSource.suspend();
+ }
+ }
+
+
+ public void resumeRead() {
+ if( isConnected() && readSource!=null ) {
+ if( rateLimitingChannel!=null ) {
+ rateLimitingChannel.resumeRead();
+ } else {
+ _resumeRead();
+ }
+ }
+ }
+ private void _resumeRead() {
+ readSource.resume();
+ dispatchQueue.execute(new Runnable(){
+ public void run() {
+ drainInbound();
+ }
+ });
+ }
+
+ protected void suspendWrite() {
+ if( isConnected() && writeSource!=null ) {
+ writeSource.suspend();
+ }
+ }
+ protected void resumeWrite() {
+ if( isConnected() && writeSource!=null ) {
+ writeSource.resume();
+ dispatchQueue.execute(new Runnable(){
+ public void run() {
+ drainOutbound();
+ }
+ });
+ }
+ }
+
+ public TransportListener getTransportListener() {
+ return listener;
+ }
+
+ public void setTransportListener(TransportListener listener) {
+ this.listener = listener;
+ }
+
+ public ProtocolCodec getProtocolCodec() {
+ return codec;
+ }
+
+ public void setProtocolCodec(ProtocolCodec protocolCodec) {
+ this.codec = protocolCodec;
+ if( channel!=null && codec!=null ) {
+ initializeCodec();
+ }
+ }
+
+ public boolean isConnected() {
+ return socketState.is(CONNECTED.class);
+ }
+
+ public boolean isDisposed() {
+ return getServiceState() == STOPPED;
+ }
+
+ public void setSocketOptions(Map<String, Object> socketOptions) {
+ this.socketOptions = socketOptions;
+ }
+
+ public boolean isUseLocalHost() {
+ return useLocalHost;
+ }
+
+ /**
+ * Sets whether 'localhost' or the actual local host name should be used to
+ * make local connections. On some operating systems such as Macs its not
+ * possible to connect as the local host name so localhost is better.
+ */
+ public void setUseLocalHost(boolean useLocalHost) {
+ this.useLocalHost = useLocalHost;
+ }
+
+
+ private void trace(String message) {
+ if( LOG.isTraceEnabled() ) {
+ final String label = dispatchQueue.getLabel();
+ if( label !=null ) {
+ LOG.trace(label +" | "+message);
+ } else {
+ LOG.trace(message);
+ }
+ }
+ }
+
+ public SocketChannel getSocketChannel() {
+ return channel;
+ }
+
+ public ReadableByteChannel readChannel() {
+ if(rateLimitingChannel!=null) {
+ return rateLimitingChannel;
+ } else {
+ return channel;
+ }
+ }
+
+ public WritableByteChannel writeChannel() {
+ if(rateLimitingChannel!=null) {
+ return rateLimitingChannel;
+ } else {
+ return channel;
+ }
+ }
+
+ public int getMax_read_rate() {
+ return max_read_rate;
+ }
+
+ public void setMax_read_rate(int max_read_rate) {
+ this.max_read_rate = max_read_rate;
+ }
+
+ public int getMax_write_rate() {
+ return max_write_rate;
+ }
+
+ public void setMax_write_rate(int max_write_rate) {
+ this.max_write_rate = max_write_rate;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransportFactory.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransportFactory.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransportFactory.java
new file mode 100644
index 0000000..2404190
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransportFactory.java
@@ -0,0 +1,123 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.tcp;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.security.NoSuchAlgorithmException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.aries.rsa.provider.fastbin.util.IntrospectionSupport;
+import org.apache.aries.rsa.provider.fastbin.util.URISupport;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ */
+public class TcpTransportFactory {
+ private static final Logger LOG = LoggerFactory.getLogger(TcpTransportFactory.class);
+
+ public TcpTransportServer bind(String location) throws Exception {
+
+ URI uri = new URI(location);
+ TcpTransportServer server = createTcpTransportServer(uri);
+ if (server == null) return null;
+
+ Map<String, String> options = new HashMap<String, String>(URISupport.parseParameters(uri));
+ IntrospectionSupport.setProperties(server, options);
+ Map<String, Object> transportOptions = IntrospectionSupport.extractProperties(options, "transport.");
+ server.setTransportOption(transportOptions);
+ return server;
+ }
+
+
+ public TcpTransport connect(String location) throws Exception {
+ URI uri = new URI(location);
+ TcpTransport transport = createTransport(uri);
+ if (transport == null) return null;
+
+ Map<String, String> options = new HashMap<String, String>(URISupport.parseParameters(uri));
+ URI localLocation = getLocalLocation(uri);
+
+ transport.connecting(uri, localLocation);
+
+ Map<String, Object> socketOptions = IntrospectionSupport.extractProperties(options, "socket.");
+ transport.setSocketOptions(socketOptions);
+
+ IntrospectionSupport.setProperties(transport, options);
+ if (!options.isEmpty()) {
+ // Release the transport resource as we are erroring out...
+ try {
+ transport.stop();
+ } catch (Throwable cleanup) {
+ }
+ throw new IllegalArgumentException("Invalid connect parameters: " + options);
+ }
+ return transport;
+ }
+
+ /**
+ * Allows subclasses of TcpTransportFactory to create custom instances of
+ * TcpTransportServer.
+ */
+ protected TcpTransportServer createTcpTransportServer(final URI location) throws IOException, URISyntaxException, Exception {
+ if( !location.getScheme().equals("tcp") ) {
+ return null;
+ }
+ return new TcpTransportServer(location);
+ }
+
+ /**
+ * Allows subclasses of TcpTransportFactory to create custom instances of
+ * TcpTransport.
+ */
+ protected TcpTransport createTransport(URI uri) throws NoSuchAlgorithmException, Exception {
+ if( !uri.getScheme().equals("tcp") ) {
+ return null;
+ }
+ TcpTransport transport = new TcpTransport();
+ return transport;
+ }
+
+ protected URI getLocalLocation(URI location) {
+ URI localLocation = null;
+ String path = location.getPath();
+ // see if the path is a local URI location
+ if (path != null && path.length() > 0) {
+ int localPortIndex = path.indexOf(':');
+ try {
+ Integer.parseInt(path.substring(localPortIndex + 1, path.length()));
+ String localString = location.getScheme() + ":/" + path;
+ localLocation = new URI(localString);
+ } catch (Exception e) {
+ LOG.warn("path isn't a valid local location for TcpTransport to use", e);
+ }
+ }
+ return localLocation;
+ }
+
+ protected String getOption(Map options, String key, String def) {
+ String rc = (String) options.remove(key);
+ if( rc == null ) {
+ rc = def;
+ }
+ return rc;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransportServer.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransportServer.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransportServer.java
new file mode 100644
index 0000000..3e828b5
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransportServer.java
@@ -0,0 +1,231 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.tcp;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.UnknownHostException;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.aries.rsa.provider.fastbin.io.TransportAcceptListener;
+import org.apache.aries.rsa.provider.fastbin.io.TransportServer;
+import org.apache.aries.rsa.provider.fastbin.util.IntrospectionSupport;
+import org.fusesource.hawtdispatch.Dispatch;
+import org.fusesource.hawtdispatch.DispatchQueue;
+import org.fusesource.hawtdispatch.DispatchSource;
+
+/**
+ * A TCP based transport server
+ *
+ */
+
+public class TcpTransportServer implements TransportServer {
+
+ private final String bindScheme;
+ private final InetSocketAddress bindAddress;
+
+ private int backlog = 100;
+ private Map<String, Object> transportOptions;
+
+ private ServerSocketChannel channel;
+ private TransportAcceptListener listener;
+ private DispatchQueue dispatchQueue;
+ private DispatchSource acceptSource;
+
+ public TcpTransportServer(URI location) throws UnknownHostException {
+ bindScheme = location.getScheme();
+ String host = location.getHost();
+ host = (host == null || host.length() == 0) ? "::" : host;
+ bindAddress = new InetSocketAddress(InetAddress.getByName(host), location.getPort());
+ }
+
+ public void setAcceptListener(TransportAcceptListener listener) {
+ this.listener = listener;
+ }
+
+ public InetSocketAddress getSocketAddress() {
+ return (InetSocketAddress) channel.socket().getLocalSocketAddress();
+ }
+
+ public DispatchQueue getDispatchQueue() {
+ return dispatchQueue;
+ }
+
+ public void setDispatchQueue(DispatchQueue dispatchQueue) {
+ this.dispatchQueue = dispatchQueue;
+ }
+
+ public void suspend() {
+ acceptSource.suspend();
+ }
+
+ public void resume() {
+ acceptSource.resume();
+ }
+
+ public void start() throws Exception {
+ start(null);
+ }
+ public void start(Runnable onCompleted) throws Exception {
+
+ try {
+ channel = ServerSocketChannel.open();
+ channel.configureBlocking(false);
+ channel.socket().bind(bindAddress, backlog);
+ } catch (IOException e) {
+ throw new IOException("Failed to bind to server socket: " + bindAddress + " due to: " + e, e);
+ }
+
+ acceptSource = Dispatch.createSource(channel, SelectionKey.OP_ACCEPT, dispatchQueue);
+ acceptSource.setEventHandler(new Runnable() {
+ public void run() {
+ try {
+ SocketChannel client = channel.accept();
+ while( client!=null ) {
+ handleSocket(client);
+ client = channel.accept();
+ }
+ } catch (Exception e) {
+ listener.onAcceptError(TcpTransportServer.this, e);
+ }
+ }
+ });
+ acceptSource.setCancelHandler(new Runnable() {
+ public void run() {
+ try {
+ channel.close();
+ } catch (IOException e) {
+ }
+ }
+ });
+ acceptSource.resume();
+ if( onCompleted!=null ) {
+ dispatchQueue.execute(onCompleted);
+ }
+ }
+
+ public String getBoundAddress() {
+ try {
+ return new URI(bindScheme, null, bindAddress.getAddress().getHostAddress(), channel.socket().getLocalPort(), null, null, null).toString();
+ } catch (URISyntaxException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public String getConnectAddress() {
+ try {
+ return new URI(bindScheme, null, resolveHostName(), channel.socket().getLocalPort(), null, null, null).toString();
+ } catch (URISyntaxException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+
+ protected String resolveHostName() {
+ String result;
+ if (bindAddress.getAddress().isAnyLocalAddress()) {
+ // make it more human readable and useful, an alternative to 0.0.0.0
+ try {
+ result = InetAddress.getLocalHost().getCanonicalHostName();
+ } catch (UnknownHostException e) {
+ result = "localhost";
+ }
+ } else {
+ result = bindAddress.getAddress().getCanonicalHostName();
+ }
+ return result;
+ }
+
+ public void stop() {
+ stop(null);
+ }
+ public void stop(final Runnable onCompleted) {
+ if( acceptSource.isCanceled() ) {
+ onCompleted.run();
+ } else {
+ acceptSource.setCancelHandler(new Runnable() {
+ public void run() {
+ try {
+ channel.close();
+ } catch (IOException e) {
+ }
+ if( onCompleted!=null ) {
+ onCompleted.run();
+ }
+ }
+ });
+ acceptSource.cancel();
+ }
+ }
+
+ public int getBacklog() {
+ return backlog;
+ }
+
+ public void setBacklog(int backlog) {
+ this.backlog = backlog;
+ }
+
+ protected final void handleSocket(SocketChannel socket) throws Exception {
+ HashMap<String, Object> options = new HashMap<String, Object>();
+// options.put("maxInactivityDuration", Long.valueOf(maxInactivityDuration));
+// options.put("maxInactivityDurationInitalDelay", Long.valueOf(maxInactivityDurationInitalDelay));
+// options.put("trace", Boolean.valueOf(trace));
+// options.put("soTimeout", Integer.valueOf(soTimeout));
+// options.put("socketBufferSize", Integer.valueOf(socketBufferSize));
+// options.put("connectionTimeout", Integer.valueOf(connectionTimeout));
+// options.put("dynamicManagement", Boolean.valueOf(dynamicManagement));
+// options.put("startLogging", Boolean.valueOf(startLogging));
+
+ TcpTransport transport = createTransport(socket, options);
+ listener.onAccept(this, transport);
+ }
+
+ protected TcpTransport createTransport(SocketChannel socketChannel, HashMap<String, Object> options) throws Exception {
+ TcpTransport transport = createTransport();
+ transport.connected(socketChannel);
+ if( options!=null ) {
+ IntrospectionSupport.setProperties(transport, options);
+ }
+ if (transportOptions != null) {
+ IntrospectionSupport.setProperties(transport, transportOptions);
+ }
+ return transport;
+ }
+
+ protected TcpTransport createTransport() {
+ return new TcpTransport();
+ }
+
+ public void setTransportOption(Map<String, Object> transportOptions) {
+ this.transportOptions = transportOptions;
+ }
+
+ /**
+ * @return pretty print of this
+ */
+ public String toString() {
+ return getBoundAddress();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/62d835de/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TransportPool.java
----------------------------------------------------------------------
diff --git a/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TransportPool.java b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TransportPool.java
new file mode 100644
index 0000000..493212f
--- /dev/null
+++ b/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TransportPool.java
@@ -0,0 +1,256 @@
+/**
+ * Copyright 2005-2015 Red Hat, Inc.
+ *
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.apache.aries.rsa.provider.fastbin.tcp;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.aries.rsa.provider.fastbin.io.ProtocolCodec;
+import org.apache.aries.rsa.provider.fastbin.io.Service;
+import org.apache.aries.rsa.provider.fastbin.io.Transport;
+import org.apache.aries.rsa.provider.fastbin.io.TransportListener;
+import org.fusesource.hawtdispatch.DispatchQueue;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public abstract class TransportPool implements Service {
+
+ protected static final Logger LOGGER = LoggerFactory.getLogger(TransportPool.class);
+
+ public static final int DEFAULT_POOL_SIZE = 2;
+
+ public static final long DEFAULT_EVICTION_DELAY = TimeUnit.MINUTES.toMillis(5);
+
+ protected final String uri;
+ protected final DispatchQueue queue;
+ protected final LinkedList<Pair> pending = new LinkedList<Pair>();
+ protected final Map<Transport, TransportState> transports = new HashMap<Transport, TransportState>();
+ protected AtomicBoolean running = new AtomicBoolean(false);
+
+ protected int poolSize;
+ protected long evictionDelay;
+
+ public TransportPool(String uri, DispatchQueue queue) {
+ this(uri, queue, DEFAULT_POOL_SIZE, DEFAULT_EVICTION_DELAY);
+ }
+
+ public TransportPool(String uri, DispatchQueue queue, int poolSize, long evictionDelay) {
+ this.uri = uri;
+ this.queue = queue;
+ this.poolSize = poolSize;
+ this.evictionDelay = evictionDelay;
+ }
+
+ protected abstract Transport createTransport(String uri) throws Exception;
+
+ protected abstract ProtocolCodec createCodec();
+
+ protected abstract void onCommand(Object command);
+
+ protected abstract void onFailure(Object id, Throwable throwable);
+
+ protected void onDone(Object id) {
+ for (TransportState state : transports.values()) {
+ if (state.inflight.remove(id)) {
+ break;
+ }
+ }
+ }
+
+ public void offer(final Object data, final Object id) {
+ if (!running.get()) {
+ throw new IllegalStateException("Transport pool stopped");
+ }
+ queue.execute(new Runnable() {
+ public void run() {
+ Transport transport = getIdleTransport();
+ if (transport != null) {
+ doOffer(transport, data, id);
+ if( transport.full() ) {
+ transports.get(transport).time = 0L;
+ }
+ } else {
+ pending.add(new Pair(data, id));
+ }
+ }
+ });
+ }
+
+ protected boolean doOffer(Transport transport, Object command, Object id) {
+ transports.get(transport).inflight.add(id);
+ return transport.offer(command);
+ }
+
+ protected Transport getIdleTransport() {
+ for (Map.Entry<Transport, TransportState> entry : transports.entrySet()) {
+ if (entry.getValue().time > 0) {
+ return entry.getKey();
+ }
+ }
+ if (transports.size() < poolSize) {
+ try {
+ startNewTransport();
+ } catch (Exception e) {
+ LOGGER.info("Unable to start new transport", e);
+ }
+ }
+ return null;
+ }
+
+ public void start() throws Exception {
+ start(null);
+ }
+
+ public void start(Runnable onComplete) throws Exception {
+ running.set(true);
+ }
+
+ public void stop() {
+ stop(null);
+ }
+
+ public void stop(final Runnable onComplete) {
+ if (running.compareAndSet(true, false)) {
+ queue.execute(new Runnable() {
+ public void run() {
+ final AtomicInteger latch = new AtomicInteger(transports.size());
+ final Runnable coutDown = new Runnable() {
+ public void run() {
+ if (latch.decrementAndGet() == 0) {
+ while (!pending.isEmpty()) {
+ Pair p = pending.removeFirst();
+ onFailure(p.id, new IOException("Transport stopped"));
+ }
+ onComplete.run();
+ }
+ }
+ };
+ while (!transports.isEmpty()) {
+ Transport transport = transports.keySet().iterator().next();
+ TransportState state = transports.remove(transport);
+ if (state != null) {
+ for (Object id : state.inflight) {
+ onFailure(id, new IOException("Transport stopped"));
+ }
+ }
+ transport.stop(coutDown);
+ }
+ }
+ });
+ } else {
+ onComplete.run();
+ }
+ }
+
+ protected void startNewTransport() throws Exception {
+ LOGGER.debug("Creating new transport for: {}", this.uri);
+ Transport transport = createTransport(this.uri);
+ transport.setDispatchQueue(queue);
+ transport.setProtocolCodec(createCodec());
+ transport.setTransportListener(new Listener());
+ transports.put(transport, new TransportState());
+ transport.start();
+ }
+
+ protected static class Pair {
+ Object command;
+ Object id;
+
+ public Pair(Object command, Object id) {
+ this.command = command;
+ this.id = id;
+ }
+ }
+
+ protected static class TransportState {
+ long time;
+ final Set<Object> inflight;
+
+ public TransportState() {
+ time = 0;
+ inflight = new HashSet<Object>();
+ }
+ }
+
+ protected class Listener implements TransportListener {
+
+ public void onTransportCommand(Transport transport, Object command) {
+ TransportPool.this.onCommand(command);
+ }
+
+ public void onRefill(final Transport transport) {
+ while (pending.size() > 0 && !transport.full()) {
+ Pair pair = pending.removeFirst();
+ boolean accepted = doOffer(transport, pair.command, pair.id);
+ assert accepted: "Should have been accepted since the transport was not full";
+ }
+
+ if( transport.full() ) {
+ transports.get(transport).time = 0L;
+ } else {
+ final long time = System.currentTimeMillis();
+ transports.get(transport).time = time;
+ if (evictionDelay > 0) {
+ queue.executeAfter(evictionDelay, TimeUnit.MILLISECONDS, new Runnable() {
+ public void run() {
+ TransportState state = transports.get(transport);
+ if (state != null && state.time == time) {
+ transports.remove(transport);
+ transport.stop();
+ }
+ }
+ });
+ }
+ }
+
+ }
+
+ public void onTransportFailure(Transport transport, IOException error) {
+ if (!transport.isDisposed()) {
+ LOGGER.info("Transport failure", error);
+ TransportState state = transports.remove(transport);
+ if (state != null) {
+ for (Object id : state.inflight) {
+ onFailure(id, error);
+ }
+ }
+ transport.stop();
+ if (transports.isEmpty()) {
+ while (!pending.isEmpty()) {
+ Pair p = pending.removeFirst();
+ onFailure(p.id, error);
+ }
+ }
+ }
+ }
+
+ public void onTransportConnected(Transport transport) {
+ transport.resumeRead();
+ onRefill(transport);
+ }
+
+ public void onTransportDisconnected(Transport transport) {
+ onTransportFailure(transport, new IOException("Transport disconnected"));
+ }
+ }
+}