Search in sources :

Example 46 with MotanFrameworkException

use of com.weibo.api.motan.exception.MotanFrameworkException in project motan by weibocom.

the class ServiceMockFilter method filter.

@Override
public Response filter(Caller<?> caller, Request request) {
    // Do nothing when mock is empty.
    String mockServiceName = caller.getUrl().getParameter(URLParamType.mock.getName());
    if (StringUtils.isEmpty(mockServiceName) || "false".equals(mockServiceName)) {
        return caller.call(request);
    }
    MockInfo info = getServiceStat(caller.getUrl());
    DefaultResponse response = new DefaultResponse();
    if (mockServiceName.startsWith(RETURN_PREFIX)) {
        String value = mockServiceName.substring(RETURN_PREFIX.length());
        try {
            info.callNum.addAndGet(1);
            long sleepTime = caclSleepTime(info);
            Thread.sleep(sleepTime);
            response.setValue(parseMockValue(value));
        } catch (RuntimeException e) {
            if (e.getCause() != null) {
                response.setException(new MotanBizException("mock service call process error", e.getCause()));
            } else {
                response.setException(new MotanBizException("mock service call process error", e));
            }
        } catch (Exception e) {
            throw new IllegalStateException("Illegal mock json value in <motan:service ... mock=\"" + mockServiceName + "\" />");
        }
    } else {
        try {
            Class<?> mockClass = isDefault(mockServiceName) ? ReflectUtil.forName(caller.getInterface().getName() + "Mock") : ReflectUtil.forName(mockServiceName);
            if (!caller.getInterface().isAssignableFrom(mockClass)) {
                throw new MotanFrameworkException("The mock implemention class " + mockClass.getName() + " not implement interface " + caller.getInterface().getName());
            }
            try {
                mockClass.getConstructor();
            } catch (NoSuchMethodException e) {
                throw new IllegalStateException("No such empty constructor \"public " + mockClass.getSimpleName() + "()\" in mock implemention class " + mockClass.getName());
            }
            String methodDesc = ReflectUtil.getMethodDesc(request.getMethodName(), request.getParamtersDesc());
            Method[] methods = mockClass.getMethods();
            boolean invoke = false;
            for (Method method : methods) {
                if (methodDesc.equals(ReflectUtil.getMethodDesc(method))) {
                    Object value = invoke(mockClass.newInstance(), method, request.getArguments(), info);
                    response.setValue(value);
                    invoke = true;
                    break;
                }
            }
            if (!invoke) {
                throw new MotanFrameworkException("Mock method is not found." + methodDesc);
            }
        } catch (ClassNotFoundException e) {
            throw new MotanFrameworkException("Mock service is not found." + (isDefault(mockServiceName) ? caller.getInterface().getName() + "Mock" : mockServiceName));
        } catch (Exception e) {
            if (e.getCause() != null) {
                response.setException(new MotanBizException("mock service call process error", e.getCause()));
            } else {
                response.setException(new MotanBizException("mock service call process error", e));
            }
        }
    }
    return response;
}
Also used : MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException) Method(java.lang.reflect.Method) MotanBizException(com.weibo.api.motan.exception.MotanBizException) MotanBizException(com.weibo.api.motan.exception.MotanBizException) InvocationTargetException(java.lang.reflect.InvocationTargetException) MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException)

Example 47 with MotanFrameworkException

use of com.weibo.api.motan.exception.MotanFrameworkException in project motan by weibocom.

the class MotanV2Codec method encode.

@Override
public byte[] encode(Channel channel, Object message) throws IOException {
    try {
        if (DefaultRpcHeartbeatFactory.isHeartbeatRequest(message)) {
            return encodeHeartbeat(((Request) message).getRequestId(), true);
        }
        if (DefaultRpcHeartbeatFactory.isHeartbeatResponse(message)) {
            return encodeHeartbeat(((Response) message).getRequestId(), false);
        }
        MotanV2Header header = new MotanV2Header();
        byte[] body = null;
        Serialization serialization;
        GrowableByteBuffer buf = new GrowableByteBuffer(4096);
        // meta
        int index = HEADER_SIZE;
        buf.position(index);
        // metasize
        buf.putInt(0);
        if (message instanceof Request) {
            String serialName = channel.getUrl().getParameter(URLParamType.serialize.getName(), URLParamType.serialize.getValue());
            serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(serialName);
            if (serialization == null) {
                throw new MotanServiceException("can not found serialization " + serialName);
            }
            header.setSerialize(serialization.getSerializationNumber());
            Request request = (Request) message;
            putString(buf, M2_PATH);
            putString(buf, request.getInterfaceName());
            putString(buf, M2_METHOD);
            putString(buf, request.getMethodName());
            if (request.getParamtersDesc() != null) {
                putString(buf, M2_METHOD_DESC);
                putString(buf, request.getParamtersDesc());
            }
            if (request.getAttachments() != null && request.getAttachments().get(URLParamType.group.getName()) != null) {
                request.setAttachment(M2_GROUP, request.getAttachments().get(URLParamType.group.getName()));
            }
            putMap(buf, request.getAttachments());
            header.setRequestId(request.getRequestId());
            if (request.getArguments() != null) {
                body = serialization.serializeMulti(request.getArguments());
            }
        } else if (message instanceof Response) {
            Response response = (Response) message;
            serialization = getSerializationByNum(response.getSerializeNumber());
            header.setSerialize(serialization.getSerializationNumber());
            putString(buf, M2_PROCESS_TIME);
            putString(buf, String.valueOf(response.getProcessTime()));
            if (response.getException() != null) {
                putString(buf, M2_ERROR);
                putString(buf, ExceptionUtil.toMessage(response.getException()));
                header.setStatus(MotanV2Header.MessageStatus.EXCEPTION.getStatus());
            }
            putMap(buf, response.getAttachments());
            header.setRequestId(response.getRequestId());
            header.setRequest(false);
            if (response.getException() == null) {
                body = serialization.serialize(response.getValue());
            }
        }
        buf.position(buf.position() - 1);
        int metalength = buf.position() - index - 4;
        buf.putInt(index, metalength);
        // body
        if (body != null && body.length > 0) {
            if (channel.getUrl().getBooleanParameter(URLParamType.usegz.getName(), URLParamType.usegz.getBooleanValue()) && body.length > channel.getUrl().getIntParameter(URLParamType.mingzSize.getName(), URLParamType.mingzSize.getIntValue())) {
                try {
                    body = ByteUtil.gzip(body);
                    header.setGzip(true);
                } catch (IOException e) {
                    LoggerUtil.warn("MotanV2Codec encode gzip fail. so not gzip body.", e);
                }
            }
            buf.putInt(body.length);
            buf.put(body);
        } else {
            buf.putInt(0);
        }
        // header
        int position = buf.position();
        buf.position(0);
        buf.put(header.toBytes());
        buf.position(position);
        buf.flip();
        byte[] result = new byte[buf.remaining()];
        buf.get(result);
        return result;
    } catch (Exception e) {
        String errmsg = "";
        if (message != null) {
            if (message instanceof Request) {
                errmsg = "type:request, " + message.toString();
            } else {
                errmsg = "type:response, " + message.toString();
            }
        }
        LoggerUtil.warn("motan2 encode error." + errmsg, e);
        if (ExceptionUtil.isMotanException(e)) {
            throw (RuntimeException) e;
        } else {
            throw new MotanFrameworkException("encode error!" + errmsg + ", origin errmsg:" + e.getMessage(), e, MotanErrorMsgConstant.FRAMEWORK_ENCODE_ERROR);
        }
    }
}
Also used : Serialization(com.weibo.api.motan.codec.Serialization) DefaultResponse(com.weibo.api.motan.rpc.DefaultResponse) Response(com.weibo.api.motan.rpc.Response) MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException) DefaultRequest(com.weibo.api.motan.rpc.DefaultRequest) Request(com.weibo.api.motan.rpc.Request) IOException(java.io.IOException) MotanServiceException(com.weibo.api.motan.exception.MotanServiceException) MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException) MotanServiceException(com.weibo.api.motan.exception.MotanServiceException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 48 with MotanFrameworkException

use of com.weibo.api.motan.exception.MotanFrameworkException in project motan by weibocom.

the class AbstractRegistryFactory method getRegistry.

@Override
public Registry getRegistry(URL url) {
    String registryUri = getRegistryUri(url);
    try {
        lock.lock();
        Registry registry = registries.get(registryUri);
        if (registry != null) {
            return registry;
        }
        registry = createRegistry(url);
        if (registry == null) {
            throw new MotanFrameworkException("Create registry false for url:" + url, MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
        }
        registries.put(registryUri, registry);
        return registry;
    } catch (Exception e) {
        throw new MotanFrameworkException("Create registry false for url:" + url, e, MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
    } finally {
        lock.unlock();
    }
}
Also used : MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException) Registry(com.weibo.api.motan.registry.Registry) MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException)

Example 49 with MotanFrameworkException

use of com.weibo.api.motan.exception.MotanFrameworkException in project motan by weibocom.

the class SimpleConfigHandler method register.

private void register(List<URL> registryUrls, URL serviceUrl) {
    for (URL url : registryUrls) {
        // 根据check参数的设置,register失败可能会抛异常,上层应该知晓
        RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getExtension(url.getProtocol(), false);
        if (registryFactory == null) {
            throw new MotanFrameworkException(new MotanErrorMsg(500, MotanErrorMsgConstant.FRAMEWORK_REGISTER_ERROR_CODE, "register error! Could not find extension for registry protocol:" + url.getProtocol() + ", make sure registry module for " + url.getProtocol() + " is in classpath!"));
        }
        Registry registry = registryFactory.getRegistry(url);
        registry.register(serviceUrl);
    }
}
Also used : RegistryFactory(com.weibo.api.motan.registry.RegistryFactory) MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException) MotanErrorMsg(com.weibo.api.motan.exception.MotanErrorMsg) Registry(com.weibo.api.motan.registry.Registry)

Example 50 with MotanFrameworkException

use of com.weibo.api.motan.exception.MotanFrameworkException in project motan by weibocom.

the class ExtensionLoader method loadExtensionClasses.

private ConcurrentMap<String, Class<T>> loadExtensionClasses(String prefix) {
    String fullName = prefix + type.getName();
    List<String> classNames = new ArrayList<String>();
    try {
        Enumeration<URL> urls;
        if (classLoader == null) {
            urls = ClassLoader.getSystemResources(fullName);
        } else {
            urls = classLoader.getResources(fullName);
        }
        if (urls == null || !urls.hasMoreElements()) {
            return new ConcurrentHashMap<String, Class<T>>();
        }
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            parseUrl(type, url, classNames);
        }
    } catch (Exception e) {
        throw new MotanFrameworkException("ExtensionLoader loadExtensionClasses error, prefix: " + prefix + " type: " + type.getClass(), e);
    }
    return loadClass(classNames);
}
Also used : MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) URL(java.net.URL) IOException(java.io.IOException) MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException)

Aggregations

MotanFrameworkException (com.weibo.api.motan.exception.MotanFrameworkException)57 MotanServiceException (com.weibo.api.motan.exception.MotanServiceException)11 URL (com.weibo.api.motan.rpc.URL)10 IOException (java.io.IOException)9 Method (java.lang.reflect.Method)8 DefaultResponse (com.weibo.api.motan.rpc.DefaultResponse)6 Response (com.weibo.api.motan.rpc.Response)5 TransportException (com.weibo.api.motan.transport.TransportException)4 ArrayList (java.util.ArrayList)4 Serialization (com.weibo.api.motan.codec.Serialization)3 ConfigHandler (com.weibo.api.motan.config.handler.ConfigHandler)3 Registry (com.weibo.api.motan.registry.Registry)3 HeartbeatFactory (com.weibo.api.motan.transport.HeartbeatFactory)3 HashMap (java.util.HashMap)3 CommandListener (com.weibo.api.motan.registry.support.command.CommandListener)2 ServiceListener (com.weibo.api.motan.registry.support.command.ServiceListener)2 DefaultRequest (com.weibo.api.motan.rpc.DefaultRequest)2 Request (com.weibo.api.motan.rpc.Request)2 DeserializableObject (com.weibo.api.motan.serialize.DeserializableObject)2 ChannelFuture (io.netty.channel.ChannelFuture)2