com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException Java Examples

The following examples show how to use com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LocalRegistryTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() {
    FileUtils.cleanDirectory(new File(filePath));

    registryConfig = new RegistryConfig()
        .setProtocol("local")
        //.setParameter("registry.local.scan.period", "1000")
        .setSubscribe(true)
        .setRegister(true);
    //        registryConfig.setAddress()
    //                .setConnectTimeout(5000)
    //                .setHeartbeatPeriod(60000)
    //                .setReconnectPeriod(15000)
    //                .setBatch(true)
    //                .setBatchSize(10);

    registry = (LocalRegistry) RegistryFactory.getRegistry(registryConfig);
    try {
        registry.init();
    } catch (Exception e) {
        Assert.assertTrue(e instanceof SofaRpcRuntimeException);
    }
    registryConfig.setFile(file);
    registry.init();
    registry.start();
}
 
Example #2
Source File: GenericServiceImpl.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public void generic(Request request, StreamObserver<Response> responseObserver) {

    SofaRequest sofaRequest = TracingContextKey.getKeySofaRequest().get(Context.current());

    String methodName = sofaRequest.getMethodName();
    Class[] argTypes = getArgTypes(request);
    try {
        Serializer serializer = SerializerFactory.getSerializer(request.getSerializeType());

        Method declaredMethod = proxyClass.getDeclaredMethod(methodName, argTypes);
        Object result = declaredMethod.invoke(ref, getInvokeArgs(request, argTypes, serializer));

        Response.Builder builder = Response.newBuilder();
        builder.setSerializeType(request.getSerializeType());
        builder.setType(declaredMethod.getReturnType().getName());
        builder.setData(ByteString.copyFrom(serializer.encode(result, null).array()));
        Response build = builder.build();
        responseObserver.onNext(build);
        responseObserver.onCompleted();
    } catch (Exception e) {
        LOGGER.error("Invoke " + methodName + " error:", e);
        throw new SofaRpcRuntimeException(e);
    }
}
 
Example #3
Source File: AloneBoltClientConnectionManager.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 通过配置获取长连接
 *
 * @param rpcClient       bolt客户端
 * @param transportConfig 传输层配置
 * @param url             传输层地址
 * @return 长连接
 */
public Connection getConnection(RpcClient rpcClient, ClientTransportConfig transportConfig, Url url) {
    if (rpcClient == null || transportConfig == null || url == null) {
        return null;
    }
    Connection connection;
    try {
        connection = rpcClient.getConnection(url, url.getConnectTimeout());
    } catch (InterruptedException | RemotingException e) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_GET_CONNECTION),e);
    }
    if (connection == null) {
        return null;
    }

    return connection;
}
 
Example #4
Source File: AbstractHttpServer.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public void registerProcessor(ProviderConfig providerConfig, Invoker instance) {
    // 缓存Invoker对象
    String serviceName = getUniqueName(providerConfig);
    serverHandler.getInvokerMap().put(serviceName, instance);
    // 解析方法,不支持方法重载
    Class itfClass = providerConfig.getProxyClass();
    HashMap<String, Method> methodsLimit = new HashMap<String, Method>(16);
    for (Method method : itfClass.getMethods()) {
        String methodName = method.getName();
        if (methodsLimit.containsKey(methodName)) {
            // 重名的方法
            throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_OVERLOADING_METHOD,
                itfClass.getName(), methodName));
        }
        methodsLimit.put(methodName, method);
    }

    for (Map.Entry<String, Method> entry : methodsLimit.entrySet()) {
        // 缓存接口的方法
        ReflectCache.putMethodCache(serviceName, entry.getValue());
        ReflectCache.putMethodSigsCache(serviceName, entry.getKey(),
            ClassTypeUtils.getTypeStrs(entry.getValue().getParameterTypes(), true));
    }
}
 
Example #5
Source File: Curator4ZookeeperRegistry.java    From spring-cloud-sofastack-samples with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized boolean start() {
    if (zkClient == null) {
        LOGGER.warn("Start zookeeper registry must be do init first!");
        return false;
    }
    if (zkClient.getState() == CuratorFrameworkState.STARTED) {
        return true;
    }
    try {
        zkClient.start();
    } catch (Throwable t) {
        throw new SofaRpcRuntimeException("Failed to start zookeeper zkClient", t);
    }
    return zkClient.getState() == CuratorFrameworkState.STARTED;
}
 
Example #6
Source File: ZookeeperAdminRegistry.java    From sofa-dashboard with Apache License 2.0 6 votes vote down vote up
@Override
public void subscribe(String group, RegistryDataChangeListener listener) {
    // 注册Consumer节点
    try {
        PathChildrenCache pathChildrenCache = new PathChildrenCache(zkClient,
            SofaDashboardConstants.SEPARATOR + group, true);

        pathChildrenCache.start(PathChildrenCache.StartMode.NORMAL);

        pathChildrenCache.getListenable().addListener(rootNodeChangeListener);
    } catch (Exception e) {
        throw new SofaRpcRuntimeException("Failed to register consumer to zookeeperRegistry!",
            e);
    }

}
 
Example #7
Source File: NacosRegistry.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public void unSubscribe(ConsumerConfig config) {
    if (config.isSubscribe()) {
        String serviceName = NacosRegistryHelper.buildServiceName(config, config.getProtocol());
        try {
            EventListener eventListener = consumerListeners.remove(config);
            if (null != eventListener) {
                namingService.unsubscribe(serviceName, defaultCluster, eventListener);
            }
        } catch (Exception e) {
            if (!RpcRunningState.isShuttingDown()) {

                if (e instanceof SofaRpcRuntimeException) {
                    throw (SofaRpcRuntimeException) e;
                } else {
                    throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_UNSUB_LISTENER, EXT_NAME), e);
                }
            }
        }

        providerObserver.removeProviderListener(config);
    }
}
 
Example #8
Source File: ZookeeperRegistry.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized boolean start() {
    if (zkClient == null) {
        LOGGER.warn("Start zookeeper registry must be do init first!");
        return false;
    }
    if (zkClient.getState() == CuratorFrameworkState.STARTED) {
        return true;
    }
    try {
        zkClient.start();
    } catch (Exception e) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_ZOOKEEPER_CLIENT_START), e);
    }
    return zkClient.getState() == CuratorFrameworkState.STARTED;
}
 
Example #9
Source File: BytebuddyProxy.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T getProxy(Class<T> interfaceClass, Invoker proxyInvoker) {

    Class<? extends T> cls = PROXY_CLASS_MAP.get(interfaceClass);
    if (cls == null) {
        cls = new ByteBuddy()
            .subclass(interfaceClass)
            .method(
                ElementMatchers.isDeclaredBy(interfaceClass).or(ElementMatchers.isEquals())
                    .or(ElementMatchers.isToString().or(ElementMatchers.isHashCode())))
            .intercept(MethodDelegation.to(new BytebuddyInvocationHandler(proxyInvoker), "handler"))
            .make()
            .load(interfaceClass.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
            .getLoaded();

        PROXY_CLASS_MAP.put(interfaceClass, cls);
    }
    try {
        return cls.newInstance();
    } catch (Throwable t) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_PROXY_CONSTRUCT, "bytebuddy"), t);
    }

}
 
Example #10
Source File: LoggerFactory.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
public static Logger getLogger(String name) {
    try {
        Object logInstance = ClassUtils.forName(implClass, Logger.class.getClassLoader())
            .getConstructor(String.class)
            .newInstance(name);
        if (logInstance instanceof Logger) {
            return (Logger) logInstance;
        } else {
            throw new SofaRpcRuntimeException(implClass + " is not type of  " + Logger.class);
        }
    } catch (SofaRpcRuntimeException ex) {
        throw ex;
    } catch (Exception e) {
        throw new SofaRpcRuntimeException("Error when getLogger of " + name
            + ", implement is " + implClass + "", e);
    }
}
 
Example #11
Source File: LoggerFactory.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
public static Logger getLogger(Class clazz) {
    try {
        Object logInstance = ClassUtils.forName(implClass, Logger.class.getClassLoader())
            .getConstructor(Class.class).newInstance(clazz);
        if (logInstance instanceof Logger) {
            return (Logger) logInstance;
        } else {
            throw new SofaRpcRuntimeException(implClass + " is not type of  " + Logger.class);
        }
    } catch (SofaRpcRuntimeException ex) {
        throw ex;
    } catch (Exception e) {
        throw new SofaRpcRuntimeException("Error when getLogger of " + clazz.getName()
            + ", implement is " + implClass + "", e);
    }
}
 
Example #12
Source File: RpcConfigs.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private static void init() {
    try {
        // loadDefault
        String json = FileUtils.file2String(RpcConfigs.class, "rpc-config-default.json", "UTF-8");
        Map map = JSON.parseObject(json, Map.class);
        CFG.putAll(map);

        // loadCustom
        loadCustom("sofa-rpc/rpc-config.json");
        loadCustom("META-INF/sofa-rpc/rpc-config.json");

        // load system properties
        CFG.putAll(new HashMap(System.getProperties())); // 注意部分属性可能被覆盖为字符串
    } catch (Exception e) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_LOAD_RPC_CONFIGS), e);
    }
}
 
Example #13
Source File: ExtensionLoader.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 得到实例
 *
 * @param alias 别名
 * @return 扩展实例(已判断是否单例)
 */
public T getExtension(String alias) {
    ExtensionClass<T> extensionClass = getExtensionClass(alias);
    if (extensionClass == null) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_EXTENSION_NOT_FOUND, interfaceName, alias));
    } else {
        if (extensible.singleton() && factory != null) {
            T t = factory.get(alias);
            if (t == null) {
                synchronized (this) {
                    t = factory.get(alias);
                    if (t == null) {
                        t = extensionClass.getExtInstance();
                        factory.put(alias, t);
                    }
                }
            }
            return t;
        } else {
            return extensionClass.getExtInstance();
        }
    }
}
 
Example #14
Source File: ExtensionLoader.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 得到实例
 *
 * @param alias    别名
 * @param argTypes 扩展初始化需要的参数类型
 * @param args     扩展初始化需要的参数
 * @return 扩展实例(已判断是否单例)
 */
public T getExtension(String alias, Class[] argTypes, Object[] args) {
    ExtensionClass<T> extensionClass = getExtensionClass(alias);
    if (extensionClass == null) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_EXTENSION_NOT_FOUND, interfaceName, alias));
    } else {
        if (extensible.singleton() && factory != null) {
            T t = factory.get(alias);
            if (t == null) {
                synchronized (this) {
                    t = factory.get(alias);
                    if (t == null) {
                        t = extensionClass.getExtInstance(argTypes, args);
                        factory.put(alias, t);
                    }
                }
            }
            return t;
        } else {
            return extensionClass.getExtInstance(argTypes, args);
        }
    }
}
 
Example #15
Source File: ReflectUtils.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 得到get/is方法
 *
 * @param clazz    类
 * @param property 属性
 * @return Method 方法对象
 */
public static Method getPropertyGetterMethod(Class clazz, String property) {
    String methodName = "get" + property.substring(0, 1).toUpperCase() + property.substring(1);
    Method method;
    try {
        method = clazz.getMethod(methodName);
    } catch (NoSuchMethodException e) {
        try {
            methodName = "is" + property.substring(0, 1).toUpperCase() + property.substring(1);
            method = clazz.getMethod(methodName);
        } catch (NoSuchMethodException e1) {
            throw new SofaRpcRuntimeException("No getter method for " + clazz.getName() + "#" + property, e);
        }
    }
    return method;
}
 
Example #16
Source File: DefaultProviderBootstrap.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * for check fields and parameters of consumer config
 */
protected void checkParameters() {
    // 检查注入的ref是否接口实现类
    Class proxyClass = providerConfig.getProxyClass();
    String key = providerConfig.buildKey();
    T ref = providerConfig.getRef();
    if (!proxyClass.isInstance(ref)) {
        String name = ref == null ? "null" : ref.getClass().getName();
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_REFERENCE_AND_INTERFACE, name,
            providerConfig.getInterfaceId(), key));
    }
    // server 不能为空
    if (CommonUtils.isEmpty(providerConfig.getServer())) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_SERVER_EMPTY, key));
    }
    checkMethods(proxyClass);
}
 
Example #17
Source File: DynamicConfigManagerFactory.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 得到动态配置管理
 *
 * @param alias 别名
 * @return DynamicManager 实现
 */
public static synchronized DynamicConfigManager getDynamicManager(String appName, String alias) {
    if (ALL_DYNAMICS.size() > 3) { // 超过3次 是不是配错了?
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("Size of dynamic manager is greater than 3, Please check it!");
        }
    }
    try {
        // 注意:RegistryConfig重写了equals方法,如果多个RegistryConfig属性一样,则认为是一个对象
        DynamicConfigManager registry = ALL_DYNAMICS.get(alias);
        if (registry == null) {
            ExtensionClass<DynamicConfigManager> ext = ExtensionLoaderFactory.getExtensionLoader(
                DynamicConfigManager.class)
                .getExtensionClass(alias);
            if (ext == null) {
                throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_LOAD_EXT, "DynamicConfigManager",
                    alias));
            }
            registry = ext.getExtInstance(new Class[] { String.class }, new Object[] { appName });
            ALL_DYNAMICS.put(alias, registry);
        }
        return registry;
    } catch (Throwable e) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_LOAD_EXT, "DynamicConfigManager", alias),
            e);
    }
}
 
Example #18
Source File: CompressorFactoryTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Test
public void getCompressorNotExist() throws Exception {
    try {
        CompressorFactory.getCompressor((byte) 999);
        Assert.fail();
    } catch (SofaRpcRuntimeException e) {
    }
}
 
Example #19
Source File: FileUtils.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 得到USER_HOME目录
 *
 * @param base 用户目录下文件夹
 * @return 得到用户目录
 */
public static String getUserHomeDir(String base) {
    String userhome = System.getProperty("user.home");
    File file = new File(userhome, base);
    if (file.exists()) {
        if (!file.isDirectory()) {
            // LOGGER.error("{} exists, but not directory", file.getAbsolutePath());
            throw new SofaRpcRuntimeException(file.getAbsolutePath() + " exists, but not directory");
        }
    } else {
        file.mkdirs(); // 可能创建不成功
    }
    return file.getAbsolutePath();
}
 
Example #20
Source File: SerializerFactoryTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Test
public void getSerializerNotExist() {
    try {
        SerializerFactory.getSerializer((byte) 999);
        Assert.fail();
    } catch (SofaRpcRuntimeException e) {
    }
}
 
Example #21
Source File: RpcConfigs.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * Gets int value.
 *
 * @param primaryKey   the primary key
 * @param secondaryKey the secondary key
 * @return the int value
 */
public static int getIntValue(String primaryKey, String secondaryKey) {
    Object val = CFG.get(primaryKey);
    if (val == null) {
        val = CFG.get(secondaryKey);
        if (val == null) {
            throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_NOT_FOUND_KEY, primaryKey + "/" +
                secondaryKey));
        }
    }
    return Integer.parseInt(val.toString());
}
 
Example #22
Source File: RpcConfigs.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * Gets int value.
 *
 * @param primaryKey the primary key
 * @return the int value
 */
public static int getIntValue(String primaryKey) {
    Object val = CFG.get(primaryKey);
    if (val == null) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_NOT_FOUND_KEY, primaryKey));
    } else {
        return Integer.parseInt(val.toString());
    }
}
 
Example #23
Source File: RpcConfigs.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * Gets boolean value.
 *
 * @param primaryKey   the primary key
 * @param secondaryKey the secondary key
 * @return the boolean value
 */
public static boolean getBooleanValue(String primaryKey, String secondaryKey) {
    Object val = CFG.get(primaryKey);
    if (val == null) {
        val = CFG.get(secondaryKey);
        if (val == null) {
            throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_NOT_FOUND_KEY, primaryKey + "/" +
                secondaryKey));
        }
    }
    return Boolean.valueOf(val.toString());
}
 
Example #24
Source File: RpcConfigs.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * Gets boolean value.
 *
 * @param primaryKey the primary key
 * @return the boolean value
 */
public static boolean getBooleanValue(String primaryKey) {
    Object val = CFG.get(primaryKey);
    if (val == null) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_NOT_FOUND_KEY, primaryKey));
    } else {
        return Boolean.valueOf(val.toString());
    }
}
 
Example #25
Source File: Curator4ZookeeperRegistry.java    From spring-cloud-sofastack-samples with Apache License 2.0 5 votes vote down vote up
/**
 * 订阅接口级配置
 *
 * @param config   provider/consumer config
 * @param listener config listener
 */
protected void subscribeConfig(final AbstractInterfaceConfig config, ConfigListener listener) {
    try {
        if (configObserver == null) {
            configObserver = new ZookeeperConfigObserver();
        }
        configObserver.addConfigListener(config, listener);
        final String configPath = buildConfigPath(rootPath, config);
        // 监听配置节点下 子节点增加、子节点删除、子节点Data修改事件
        PathChildrenCache pathChildrenCache = new PathChildrenCache(zkClient, configPath, true);
        pathChildrenCache.getListenable().addListener((client1, event) -> {
            if (LOGGER.isDebugEnabled(config.getAppName())) {
                LOGGER.debug("Receive zookeeper event: " + "type=[" + event.getType() + "]");
            }
            switch (event.getType()) {
                case CHILD_ADDED:
                    configObserver.addConfig(config, configPath, event.getData());
                    break;
                case CHILD_REMOVED:
                    configObserver.removeConfig(config, configPath, event.getData());
                    break;
                case CHILD_UPDATED:
                    configObserver.updateConfig(config, configPath, event.getData());
                    break;
                default:
                    break;
            }
        });
        pathChildrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
        INTERFACE_CONFIG_CACHE.put(configPath, pathChildrenCache);
        configObserver.updateConfigAll(config, configPath, pathChildrenCache.getCurrentData());
    } catch (Throwable t) {
        throw new SofaRpcRuntimeException(
            "Failed to subscribe provider config from zookeeperRegistry!", t);
    }
}
 
Example #26
Source File: ReflectUtils.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 得到set方法
 *
 * @param clazz         类
 * @param property      属性
 * @param propertyClazz 属性
 * @return Method 方法对象
 */
public static Method getPropertySetterMethod(Class clazz, String property, Class propertyClazz) {
    String methodName = "set" + property.substring(0, 1).toUpperCase() + property.substring(1);
    try {
        return clazz.getMethod(methodName, propertyClazz);
    } catch (NoSuchMethodException e) {
        throw new SofaRpcRuntimeException("No setter method for " + clazz.getName() + "#" + property, e);
    }
}
 
Example #27
Source File: ClassUtils.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 根据类名加载Class
 *
 * @param className  类名
 * @param initialize 是否初始化
 * @return Class
 */
public static Class forName(String className, boolean initialize) {
    try {
        return Class.forName(className, initialize, getCurrentClassLoader());
    } catch (Exception e) {
        throw new SofaRpcRuntimeException(e);
    }
}
 
Example #28
Source File: ClassUtils.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 根据类名加载Class
 *
 * @param className 类名
 * @param cl        Classloader
 * @return Class
 */
public static Class forName(String className, ClassLoader cl) {
    try {
        return Class.forName(className, true, cl);
    } catch (Exception e) {
        throw new SofaRpcRuntimeException(e);
    }
}
 
Example #29
Source File: CompressorFactory.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 按压缩编码返回协议对象
 *
 * @param code Compressor编码
 * @return Compressor
 */
public static Compressor getCompressor(byte code) {
    Compressor compressor = TYPE_COMPRESSOR_MAP.get(code);
    if (compressor == null) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_COMPRESSOR_NOT_FOUND, code));
    }
    return compressor;
}
 
Example #30
Source File: RpcConfigs.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * Gets string value.
 *
 * @param primaryKey the primary key
 * @return the string value
 */
public static String getStringValue(String primaryKey) {
    String val = (String) CFG.get(primaryKey);
    if (val == null) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_NOT_FOUND_KEY, primaryKey));
    } else {
        return val;
    }
}