Example usage for java.lang.reflect Method getExceptionTypes

List of usage examples for java.lang.reflect Method getExceptionTypes

Introduction

In this page you can find the example usage for java.lang.reflect Method getExceptionTypes.

Prototype

@Override
public Class<?>[] getExceptionTypes() 

Source Link

Usage

From source file:com.meidusa.venus.client.RemotingInvocationHandler.java

protected Object invokeRemoteService(Service service, Endpoint endpoint, Method method,
        EndpointParameter[] params, Object[] args) throws Exception {
    String apiName = VenusAnnotationUtils.getApiname(method, service, endpoint);

    AthenaTransactionId athenaTransactionId = null;
    if (service.athenaFlag()) {
        athenaTransactionId = AthenaTransactionDelegate.getDelegate().startClientTransaction(apiName);
    }//from   ww  w  . j a v a  2 s. c o  m
    boolean async = false;

    if (endpoint.async()) {
        async = true;
    }

    byte[] traceID = VenusTracerUtil.getTracerID();

    if (traceID == null) {
        traceID = VenusTracerUtil.randomTracerID();
    }

    Serializer serializer = SerializerFactory.getSerializer(serializeType);

    SerializeServiceRequestPacket serviceRequestPacket = new SerializeServiceRequestPacket(serializer, null);

    serviceRequestPacket.clientId = PacketConstant.VENUS_CLIENT_ID;
    serviceRequestPacket.clientRequestId = sequenceId.getAndIncrement();
    serviceRequestPacket.traceId = traceID;
    serviceRequestPacket.apiName = apiName;
    serviceRequestPacket.serviceVersion = service.version();
    serviceRequestPacket.parameterMap = new HashMap<String, Object>();

    if (params != null) {
        for (int i = 0; i < params.length; i++) {
            if (args[i] instanceof InvocationListener) {
                async = true;
                ReferenceInvocationListener listener = new ReferenceInvocationListener();
                ServicePacketBuffer buffer = new ServicePacketBuffer(16);
                buffer.writeLengthCodedString(args[i].getClass().getName(), "utf-8");
                buffer.writeInt(System.identityHashCode(args[i]));
                listener.setIdentityData(buffer.toByteBuffer().array());
                Type type = method.getGenericParameterTypes()[i];
                if (type instanceof ParameterizedType) {
                    ParameterizedType genericType = ((ParameterizedType) type);
                    container.putInvocationListener((InvocationListener) args[i],
                            genericType.getActualTypeArguments()[0]);
                } else {
                    throw new InvalidParameterException("invocationListener is not generic");
                }

                serviceRequestPacket.parameterMap.put(params[i].getParamName(), listener);
            } else {
                serviceRequestPacket.parameterMap.put(params[i].getParamName(), args[i]);
            }

        }
    }
    setTransactionId(serviceRequestPacket, athenaTransactionId);

    PerformanceLevel pLevel = AnnotationUtil.getAnnotation(method.getAnnotations(), PerformanceLevel.class);
    long start = TimeUtil.currentTimeMillis();
    long borrowed = start;

    if (async) {
        if (!this.isEnableAsync()) {
            throw new VenusConfigException("service async call disabled");
        }

        BackendConnection conn = null;
        try {

            if (nioConnPool instanceof RequestLoadbalanceObjectPool) {
                conn = (BackendConnection) ((RequestLoadbalanceObjectPool) nioConnPool)
                        .borrowObject(serviceRequestPacket.parameterMap, endpoint);
            } else {
                conn = nioConnPool.borrowObject();
            }
            borrowed = TimeUtil.currentTimeMillis();

            conn.write(serviceRequestPacket.toByteBuffer());
            VenusTracerUtil.logRequest(traceID, serviceRequestPacket.apiName,
                    JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE));
            return null;
        } finally {
            if (service.athenaFlag()) {
                AthenaTransactionDelegate.getDelegate().completeClientTransaction();
            }
            if (performanceLogger.isDebugEnabled()) {
                long end = TimeUtil.currentTimeMillis();
                long time = end - borrowed;
                StringBuffer buffer = new StringBuffer();
                buffer.append("[").append(borrowed - start).append(",").append(time)
                        .append("]ms (*client,async*) traceID=").append(UUID.toString(traceID)).append(", api=")
                        .append(serviceRequestPacket.apiName);

                performanceLogger.debug(buffer.toString());
            }

            if (conn != null) {
                nioConnPool.returnObject(conn);
            }
        }
    } else {
        AbstractBIOConnection conn = null;
        int soTimeout = 0;
        int oldTimeout = 0;
        boolean success = true;
        int errorCode = 0;
        AbstractServicePacket packet = null;
        String remoteAddress = null;
        boolean invalided = false;
        try {
            if (bioConnPool instanceof RequestLoadbalanceObjectPool) {
                conn = (AbstractBIOConnection) ((RequestLoadbalanceObjectPool) bioConnPool)
                        .borrowObject(serviceRequestPacket.parameterMap, endpoint);
            } else {
                conn = (AbstractBIOConnection) bioConnPool.borrowObject();
            }
            remoteAddress = conn.getRemoteAddress();
            borrowed = TimeUtil.currentTimeMillis();
            ServiceConfig config = this.serviceFactory.getServiceConfig(method.getDeclaringClass());

            oldTimeout = conn.getSoTimeout();
            if (config != null) {
                EndpointConfig endpointConfig = config.getEndpointConfig(endpoint.name());
                if (endpointConfig != null) {
                    int eTimeOut = endpointConfig.getTimeWait();
                    if (eTimeOut > 0) {
                        soTimeout = eTimeOut;
                    }
                } else {
                    if (config.getTimeWait() > 0) {
                        soTimeout = config.getTimeWait();
                    } else {
                        if (endpoint.timeWait() > 0) {
                            soTimeout = endpoint.timeWait();
                        }
                    }
                }

            } else {

                if (endpoint.timeWait() > 0) {
                    soTimeout = endpoint.timeWait();
                }
            }

            byte[] bts;

            try {

                if (soTimeout > 0) {
                    conn.setSoTimeout(soTimeout);
                }
                conn.write(serviceRequestPacket.toByteArray());
                VenusTracerUtil.logRequest(traceID, serviceRequestPacket.apiName,
                        JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE));
                bts = conn.read();
            } catch (IOException e) {
                try {
                    conn.close();
                } catch (Exception e1) {
                    // ignore
                }

                bioConnPool.invalidateObject(conn);
                invalided = true;
                Class<?>[] eClass = method.getExceptionTypes();

                if (eClass != null && eClass.length > 0) {
                    for (Class<?> clazz : eClass) {
                        if (e.getClass().isAssignableFrom(clazz)) {
                            throw e;
                        }
                    }
                }

                throw new RemoteSocketIOException("api=" + serviceRequestPacket.apiName + ", remoteIp="
                        + conn.getRemoteAddress() + ",(" + e.getMessage() + ")", e);
            }

            int type = AbstractServicePacket.getType(bts);
            switch (type) {
            case PacketConstant.PACKET_TYPE_ERROR:
                ErrorPacket error = new ErrorPacket();
                error.init(bts);
                packet = error;
                Exception e = venusExceptionFactory.getException(error.errorCode, error.message);
                if (e == null) {
                    throw new DefaultVenusException(error.errorCode, error.message);
                } else {
                    if (error.additionalData != null) {
                        Map<String, Type> tmap = Utils.getBeanFieldType(e.getClass(), Exception.class);
                        if (tmap != null && tmap.size() > 0) {
                            Object obj = serializer.decode(error.additionalData, tmap);
                            BeanUtils.copyProperties(e, obj);
                        }
                    }
                    throw e;
                }
            case PacketConstant.PACKET_TYPE_OK:
                OKPacket ok = new OKPacket();
                ok.init(bts);
                packet = ok;
                return null;
            case PacketConstant.PACKET_TYPE_SERVICE_RESPONSE:
                ServiceResponsePacket response = new SerializeServiceResponsePacket(serializer,
                        method.getGenericReturnType());
                response.init(bts);
                packet = response;
                return response.result;
            default: {
                logger.warn("unknow response type=" + type);
                success = false;
                return null;
            }
            }
        } catch (Exception e) {
            success = false;

            if (e instanceof CodedException
                    || (errorCode = venusExceptionFactory.getErrorCode(e.getClass())) != 0
                    || e instanceof RuntimeException) {
                if (e instanceof CodedException) {
                    errorCode = ((CodedException) e).getErrorCode();
                }
                throw e;
            } else {
                RemoteException code = e.getClass().getAnnotation(RemoteException.class);
                if (code != null) {
                    errorCode = code.errorCode();
                    throw e;
                } else {
                    ExceptionCode eCode = e.getClass().getAnnotation(ExceptionCode.class);
                    if (eCode != null) {
                        errorCode = eCode.errorCode();
                        throw e;
                    } else {
                        errorCode = -1;
                        if (conn == null) {
                            throw new DefaultVenusException(e.getMessage(), e);
                        } else {
                            throw new DefaultVenusException(
                                    e.getMessage() + ". remoteAddress=" + conn.getRemoteAddress(), e);
                        }
                    }
                }
            }
        } finally {
            if (service.athenaFlag()) {
                AthenaTransactionDelegate.getDelegate().completeClientTransaction();
            }
            long end = TimeUtil.currentTimeMillis();
            long time = end - borrowed;
            StringBuffer buffer = new StringBuffer();
            buffer.append("[").append(borrowed - start).append(",").append(time)
                    .append("]ms (*client,sync*) traceID=").append(UUID.toString(traceID)).append(", api=")
                    .append(serviceRequestPacket.apiName);
            if (remoteAddress != null) {
                buffer.append(", remote=").append(remoteAddress);
            } else {
                buffer.append(", pool=").append(bioConnPool.toString());
            }
            buffer.append(", clientID=").append(PacketConstant.VENUS_CLIENT_ID).append(", requestID=")
                    .append(serviceRequestPacket.clientRequestId);

            if (packet != null) {
                if (packet instanceof ErrorPacket) {
                    buffer.append(", errorCode=").append(((ErrorPacket) packet).errorCode);
                    buffer.append(", message=").append(((ErrorPacket) packet).message);
                } else {
                    buffer.append(", errorCode=0");
                }
            }

            if (pLevel != null) {

                if (pLevel.printParams()) {
                    buffer.append(", params=");
                    buffer.append(JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE));
                }

                if (time > pLevel.error() && pLevel.error() > 0) {
                    if (performanceLogger.isErrorEnabled()) {
                        performanceLogger.error(buffer.toString());
                    }
                } else if (time > pLevel.warn() && pLevel.warn() > 0) {
                    if (performanceLogger.isWarnEnabled()) {
                        performanceLogger.warn(buffer.toString());
                    }
                } else if (time > pLevel.info() && pLevel.info() > 0) {
                    if (performanceLogger.isInfoEnabled()) {
                        performanceLogger.info(buffer.toString());
                    }
                } else {
                    if (performanceLogger.isDebugEnabled()) {
                        performanceLogger.debug(buffer.toString());
                    }
                }
            } else {
                buffer.append(", params=");
                buffer.append(JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE));

                if (time >= 30 * 1000) {
                    if (performanceLogger.isErrorEnabled()) {
                        performanceLogger.error(buffer.toString());
                    }
                } else if (time >= 10 * 1000) {
                    if (performanceLogger.isWarnEnabled()) {
                        performanceLogger.warn(buffer.toString());
                    }
                } else if (time >= 5 * 1000) {
                    if (performanceLogger.isInfoEnabled()) {
                        performanceLogger.info(buffer.toString());
                    }
                } else {
                    if (performanceLogger.isDebugEnabled()) {
                        performanceLogger.debug(buffer.toString());
                    }
                }
            }

            if (conn != null && !invalided) {
                if (!conn.isClosed() && soTimeout > 0) {
                    conn.setSoTimeout(oldTimeout);
                }
                bioConnPool.returnObject(conn);
            }

        }
    }
}

From source file:io.sinistral.proteus.server.tools.swagger.Reader.java

@SuppressWarnings("deprecation")
private Operation parseMethod(Class<?> cls, Method method, AnnotatedMethod annotatedMethod,
        List<Parameter> globalParameters, List<ApiResponse> classApiResponses, List<String> pathParamNames) {
    Operation operation = new Operation();
    if (annotatedMethod != null) {
        method = annotatedMethod.getAnnotated();
    }/*from w ww  . j  a  v  a 2  s. co  m*/
    ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
    ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class);

    String operationId;
    // check if it's an inherited or implemented method.
    boolean methodInSuperType = false;
    if (!cls.isInterface()) {
        methodInSuperType = ReflectionUtils.findMethod(method, cls.getSuperclass()) != null;
    }
    if (!methodInSuperType) {
        for (Class<?> implementedInterface : cls.getInterfaces()) {
            methodInSuperType = ReflectionUtils.findMethod(method, implementedInterface) != null;
            if (methodInSuperType) {
                break;
            }
        }
    }
    if (!methodInSuperType) {
        operationId = method.getName();
    } else {
        operationId = this.getOperationId(method.getName());
    }

    String responseContainer = null;

    Type responseType = null;
    Map<String, Property> defaultResponseHeaders = new LinkedHashMap<String, Property>();

    if (apiOperation != null) {
        if (apiOperation.hidden()) {
            return null;
        }
        if (operationId == null) {
            operationId = apiOperation.nickname();
        }

        defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders());

        operation.summary(apiOperation.value()).description(apiOperation.notes());

        if (!isVoid(apiOperation.response())) {
            responseType = apiOperation.response();
        }
        if (!apiOperation.responseContainer().isEmpty()) {
            responseContainer = apiOperation.responseContainer();
        }
        List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>();
        for (Authorization auth : apiOperation.authorizations()) {
            if (!auth.value().isEmpty()) {
                SecurityRequirement security = new SecurityRequirement();
                security.setName(auth.value());
                for (AuthorizationScope scope : auth.scopes()) {
                    if (!scope.scope().isEmpty()) {
                        security.addScope(scope.scope());
                    }
                }
                securities.add(security);
            }
        }
        for (SecurityRequirement sec : securities) {
            operation.security(sec);
        }
        if (!apiOperation.consumes().isEmpty()) {
            String[] consumesAr = ReaderUtils.splitContentValues(new String[] { apiOperation.consumes() });
            for (String consume : consumesAr) {
                operation.consumes(consume);
            }
        }
        if (!apiOperation.produces().isEmpty()) {
            String[] producesAr = ReaderUtils.splitContentValues(new String[] { apiOperation.produces() });
            for (String produce : producesAr) {
                operation.produces(produce);
            }
        }
    }

    /*
     * @TODO
     * Use apiOperation response class instead of unwrapping ServerResponse's inner type
     */

    if (apiOperation != null && StringUtils.isNotEmpty(apiOperation.responseReference())) {
        Response response = new Response().description(SUCCESSFUL_OPERATION);
        response.schema(new RefProperty(apiOperation.responseReference()));
        operation.addResponse(String.valueOf(apiOperation.code()), response);
    } else if (responseType == null) {
        // pick out response from method declaration
        LOGGER.debug("picking up response class from method {}", method);
        responseType = method.getGenericReturnType();
    }

    if (responseType != null) {
        final JavaType javaType = TypeFactory.defaultInstance().constructType(responseType);
        if (!isVoid(javaType)) {

            final Class<?> responseCls = javaType.getRawClass();

            if (responseCls != null) {
                if (responseCls.isAssignableFrom(ServerResponse.class)) {
                    responseType = javaType.containedType(0);
                } else if (responseCls.isAssignableFrom(CompletableFuture.class)) {
                    Class<?> futureCls = javaType.containedType(0).getRawClass();

                    if (futureCls.isAssignableFrom(ServerResponse.class)) {
                        final JavaType futureType = TypeFactory.defaultInstance()
                                .constructType(javaType.containedType(0));
                        responseType = futureType.containedType(0);
                    } else {
                        responseType = javaType.containedType(0);
                    }
                }
            }
        }
    }

    if (isValidResponse(responseType)) {
        final Property property = ModelConverters.getInstance().readAsProperty(responseType);
        if (property != null) {
            final Property responseProperty = ContainerWrapper.wrapContainer(responseContainer, property);
            final int responseCode = (apiOperation == null) ? 200 : apiOperation.code();
            operation.response(responseCode, new Response().description(SUCCESSFUL_OPERATION)
                    .schema(responseProperty).headers(defaultResponseHeaders));
            appendModels(responseType);
        }
    }

    operation.operationId(operationId);

    if (operation.getConsumes() == null || operation.getConsumes().isEmpty()) {
        final Consumes consumes = ReflectionUtils.getAnnotation(method, Consumes.class);
        if (consumes != null) {
            for (String mediaType : ReaderUtils.splitContentValues(consumes.value())) {
                operation.consumes(mediaType);
            }
        }
    }

    if (operation.getProduces() == null || operation.getProduces().isEmpty()) {
        final Produces produces = ReflectionUtils.getAnnotation(method, Produces.class);
        if (produces != null) {
            for (String mediaType : ReaderUtils.splitContentValues(produces.value())) {
                operation.produces(mediaType);
            }
        }
    }

    List<ApiResponse> apiResponses = new ArrayList<>();
    if (responseAnnotation != null) {
        apiResponses.addAll(Arrays.asList(responseAnnotation.value()));
    }

    Class<?>[] exceptionTypes = method.getExceptionTypes();
    for (Class<?> exceptionType : exceptionTypes) {
        ApiResponses exceptionResponses = ReflectionUtils.getAnnotation(exceptionType, ApiResponses.class);
        if (exceptionResponses != null) {
            apiResponses.addAll(Arrays.asList(exceptionResponses.value()));
        }
    }

    for (ApiResponse apiResponse : apiResponses) {
        addResponse(operation, apiResponse);
    }
    // merge class level @ApiResponse
    for (ApiResponse apiResponse : classApiResponses) {
        String key = (apiResponse.code() == 0) ? "default" : String.valueOf(apiResponse.code());
        if (operation.getResponses() != null && operation.getResponses().containsKey(key)) {
            continue;
        }
        addResponse(operation, apiResponse);
    }

    if (ReflectionUtils.getAnnotation(method, Deprecated.class) != null) {
        operation.setDeprecated(true);
    }

    // process parameters
    for (Parameter globalParameter : globalParameters) {

        LOGGER.debug("globalParameters TYPE: " + globalParameter);

        operation.parameter(globalParameter);
    }

    Annotation[][] paramAnnotations = ReflectionUtils.getParameterAnnotations(method);
    java.lang.reflect.Parameter[] methodParameters = method.getParameters();

    if (annotatedMethod == null) {
        Type[] genericParameterTypes = method.getGenericParameterTypes();

        for (int i = 0; i < genericParameterTypes.length; i++) {

            Type type = TypeFactory.defaultInstance().constructType(genericParameterTypes[i], cls);

            if (type.getTypeName().contains("Optional")
                    || type.getTypeName().contains("io.sinistral.proteus.server.ServerResponse")) {
                if (type instanceof com.fasterxml.jackson.databind.type.SimpleType) {
                    com.fasterxml.jackson.databind.type.SimpleType simpleType = (com.fasterxml.jackson.databind.type.SimpleType) type;

                    type = simpleType.containedType(0);
                }

            }

            if (type.equals(ServerRequest.class) || type.equals(HttpServerExchange.class)
                    || type.equals(HttpHandler.class)
                    || type.getTypeName().contains("io.sinistral.proteus.server.ServerResponse")) {
                continue;
            }

            List<Parameter> parameters = getParameters(type, Arrays.asList(paramAnnotations[i]),
                    methodParameters[i], pathParamNames);

            for (Parameter parameter : parameters) {
                operation.parameter(parameter);
            }
        }
    } else {
        for (int i = 0; i < annotatedMethod.getParameterCount(); i++) {
            AnnotatedParameter param = annotatedMethod.getParameter(i);

            if (param.getParameterType().equals(ServerRequest.class)
                    || param.getParameterType().equals(HttpServerExchange.class)
                    || param.getParameterType().equals(HttpHandler.class)
                    || param.getParameterType().getTypeName().contains("ServerResponse")) {
                continue;
            }

            Type type = TypeFactory.defaultInstance().constructType(param.getParameterType(), cls);

            List<Parameter> parameters = getParameters(type, Arrays.asList(paramAnnotations[i]),
                    methodParameters[i], pathParamNames);

            for (Parameter parameter : parameters) {

                operation.parameter(parameter);
            }
        }
    }

    if (operation.getResponses() == null) {
        Response response = new Response().description(SUCCESSFUL_OPERATION);

        operation.response(200, response);
    }

    processOperationDecorator(operation, method);

    return operation;
}

From source file:org.apache.avro.ipc.RestRequestor.java

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {/*from  www.  j a  v a  2s  .  co m*/
        // Check if this is a callback-based RPC:
        //            Type[] parameterTypes = method.getParameterTypes();
        //            if ((parameterTypes.length > 0) &&
        //                    (parameterTypes[parameterTypes.length - 1] instanceof Class) &&
        //                    Callback.class.isAssignableFrom(((Class<?>) parameterTypes[parameterTypes.length - 1]))) {
        //                // Extract the Callback from the end of of the argument list
        //                Object[] finalArgs = Arrays.copyOf(args, args.length - 1);
        //                Callback<?> callback = (Callback<?>) args[args.length - 1];
        //                request(method.getName(), finalArgs, callback);
        //                return null;
        //            } else {
        return request(method.getName(), args);
        //            }
    } catch (Exception e) {
        // Check if this is a declared Exception:
        for (Class<?> exceptionClass : method.getExceptionTypes()) {
            if (exceptionClass.isAssignableFrom(e.getClass())) {
                throw e;
            }
        }

        // Next, check for RuntimeExceptions:
        if (e instanceof RuntimeException) {
            throw e;
        }

        // Not an expected Exception, so wrap it in AvroRemoteException:
        throw new AvroRemoteException(e);
    }
}

From source file:org.apache.axis.description.JavaServiceDesc.java

private void createFaultMetadata(Method method, OperationDesc operation) {
    // Create Exception Types
    Class[] exceptionTypes = method.getExceptionTypes();

    for (int i = 0; i < exceptionTypes.length; i++) {
        // Every remote method declares a java.rmi.RemoteException
        // Only interested in application specific exceptions.
        // Ignore java and javax package exceptions.
        Class ex = exceptionTypes[i];
        if (ex != java.rmi.RemoteException.class && ex != org.apache.axis.AxisFault.class
                && !ex.getName().startsWith("java.") && !ex.getName().startsWith("javax.")) {

            // For JSR 101 v.1.0, there is a simple fault mapping
            // and a complexType fault mapping...both mappings
            // generate a class that extends (directly or indirectly)
            // Exception.
            // When converting java back to wsdl it is not possible
            // to determine which way to do the mapping,
            // so it is always mapped back using the complexType
            // fault mapping because it is more useful (i.e. it
            // establishes a hierarchy of exceptions).  Note that this
            // will not cause any roundtripping problems.
            // Rich

            /* Old Simple Type Mode
            Field[] f = ex.getDeclaredFields();
            ArrayList exceptionParams = new ArrayList();
            for (int j = 0; j < f.length; j++) {
            int mod = f[j].getModifiers();
            if (Modifier.isPublic(mod) &&
                 !Modifier.isStatic(mod)) {
                QName qname = new QName("", f[j].getName());
                QName typeQName = tm.getTypeQName(f[j].getType());
                ParameterDesc param = new ParameterDesc(qname,
                                                        ParameterDesc.IN,
                                                        typeQName);
                param.setJavaType(f[j].getType());
                exceptionParams.add(param);
            }//w ww.  ja  v  a  2 s  . c o m
            }
            String pkgAndClsName = ex.getName();
            FaultDesc fault = new FaultDesc();
            fault.setName(pkgAndClsName);
            fault.setParameters(exceptionParams);
            operation.addFault(fault);
            */

            FaultDesc fault = operation.getFaultByClass(ex, false);
            boolean isNew;

            // If we didn't find one, create a new one
            if (fault == null) {
                fault = new FaultDesc();
                isNew = true;
            } else {
                isNew = false;
            }

            // Try to fil in any parts of the faultDesc that aren't there

            // XMLType
            QName xmlType = fault.getXmlType();
            if (xmlType == null) {
                fault.setXmlType(getTypeMapping().getTypeQName(ex));
            }

            // Name and Class Name
            String pkgAndClsName = ex.getName();
            if (fault.getClassName() == null) {
                fault.setClassName(pkgAndClsName);
            }
            if (fault.getName() == null) {
                String name = pkgAndClsName.substring(pkgAndClsName.lastIndexOf('.') + 1,
                        pkgAndClsName.length());
                fault.setName(name);
            }

            // Parameters
            // We add a single parameter which points to the type
            if (fault.getParameters() == null) {
                if (xmlType == null) {
                    xmlType = getTypeMapping().getTypeQName(ex);
                }
                QName qname = fault.getQName();
                if (qname == null) {
                    qname = new QName("", "fault");
                }
                ParameterDesc param = new ParameterDesc(qname, ParameterDesc.IN, xmlType);
                param.setJavaType(ex);
                ArrayList exceptionParams = new ArrayList();
                exceptionParams.add(param);
                fault.setParameters(exceptionParams);
            }

            // QName
            if (fault.getQName() == null) {
                fault.setQName(new QName(pkgAndClsName));
            }

            if (isNew) {
                // Add the fault to the operation
                operation.addFault(fault);
            }
        }
    }
}

From source file:org.apache.axis2.deployment.util.Utils.java

public static AxisOperation getAxisOperationForJmethod(Method method) throws AxisFault {
    AxisOperation operation;/*from ww  w.java2 s .co  m*/
    if ("void".equals(method.getReturnType().getName())) {
        if (method.getExceptionTypes().length > 0) {
            operation = AxisOperationFactory.getAxisOperation(WSDLConstants.MEP_CONSTANT_ROBUST_IN_ONLY);
        } else {
            operation = AxisOperationFactory.getAxisOperation(WSDLConstants.MEP_CONSTANT_IN_ONLY);
        }
    } else {
        operation = AxisOperationFactory.getAxisOperation(WSDLConstants.MEP_CONSTANT_IN_OUT);
    }
    String opName = method.getName();

    WebMethodAnnotation methodAnnon = JSR181Helper.INSTANCE.getWebMethodAnnotation(method);
    if (methodAnnon != null) {
        String action = methodAnnon.getAction();
        if (action != null && !"".equals(action)) {
            operation.setSoapAction(action);
        }
        if (methodAnnon.getOperationName() != null) {
            opName = methodAnnon.getOperationName();
        }
    }

    operation.setName(new QName(opName));
    return operation;
}

From source file:org.apache.axis2.description.java2wsdl.DefaultSchemaGenerator.java

/**
 * This method will generate Schema element for all the excetion types in a given JMethod
 * - No matter what it will generate Schema element for java.lang.Exception so that for other
 * exception which extend java.lang.Excetion can use as the base class type
 *//*from   w  w  w  .  j  ava  2s.c o m*/
protected void processException(Method jMethod, AxisOperation axisOperation) throws Exception {
    XmlSchemaComplexType methodSchemaType;
    XmlSchemaSequence sequence;
    if (jMethod.getExceptionTypes().length > 0) {
        for (Class<?> extype : jMethod.getExceptionTypes()) {
            if (AxisFault.class.getName().equals(extype.getName())) {
                continue;
            }
            String partQname = this.service.getName() + getSimpleClassName(extype);
            methodSchemaType = createSchemaTypeForFault(partQname);
            QName elementName = new QName(this.schemaTargetNameSpace, partQname, this.schema_namespace_prefix);
            sequence = new XmlSchemaSequence();
            if (Exception.class.getName().equals(extype.getName())) {
                if (typeTable.getComplexSchemaType(Exception.class.getName()) == null) {
                    generateComplexTypeforException();
                }
                QName schemaTypeName = typeTable.getComplexSchemaType(Exception.class.getName());
                addContentToMethodSchemaType(sequence, schemaTypeName, partQname, false);
                methodSchemaType.setParticle(sequence);
                typeTable.addComplexSchema(Exception.class.getPackage().getName(), methodSchemaType.getQName());
                resolveSchemaNamespace(Exception.class.getPackage().getName());
                addImport(getXmlSchema(schemaTargetNameSpace), schemaTypeName);
            } else {
                generateSchemaForType(sequence, extype, getSimpleClassName(extype));
                methodSchemaType.setParticle(sequence);
            }

            typeTable.addComplexSchema(partQname, elementName);

            if (AxisFault.class.getName().equals(extype.getName())) {
                continue;
            }
            AxisMessage faultMessage = new AxisMessage();
            faultMessage.setName(this.service.getName() + getSimpleClassName(extype));
            faultMessage.setElementQName(typeTable.getQNamefortheType(partQname));

            Parameter param = service.getParameter(Java2WSDLConstants.MESSAGE_PART_NAME_OPTION_LONG);
            if (param != null) {
                faultMessage.setPartName((String) param.getValue());
            }

            axisOperation.setFaultMessages(faultMessage);
        }
    }
}

From source file:org.apache.axis2.jaxws.description.builder.converter.JavaClassToDBCConverter.java

/**
 * Adds any checked exceptions (i.e. declared on a method via a throws clause)
 * to the list of classes for which a DBC needs to be built.
 * @param rootClass//from w w w. ja  va2  s  .  com
 */
private void establishExceptionClasses(final Class rootClass) {
    Method[] methods = (Method[]) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return rootClass.getMethods();
        }
    });
    for (Method method : methods) {
        Class[] exceptionClasses = method.getExceptionTypes();
        if (exceptionClasses.length > 0) {
            for (Class checkedException : exceptionClasses) {
                classes.add(checkedException);
            }
        }
    }
}

From source file:org.apache.axis2.jaxws.utility.JavaUtils.java

/**
 * Get checked exception/* w w  w . j  a va2  s .c o m*/
 * @param throwable Throwable
 * @param method Method
 * @return Class of the checked exception or null
 */
public static Class getCheckedException(Throwable throwable, Method method) {
    if (method == null) {
        return null;
    }
    Class[] exceptions = method.getExceptionTypes();
    if (exceptions != null) {
        for (int i = 0; i < exceptions.length; i++) {
            if (exceptions[i].isAssignableFrom(throwable.getClass())) {
                return exceptions[i];
            }
        }
    }
    return null;
}

From source file:org.apache.axis2.rpc.receivers.RPCMessageReceiver.java

/**
 * reflect and get the Java method - for each i'th param in the java method - get the first
 * child's i'th child -if the elem has an xsi:type attr then find the deserializer for it - if
 * not found, lookup deser for th i'th param (java type) - error if not found - deserialize &
 * save in an object array - end for/*w  w w .j  a  va  2  s  . c om*/
 * <p/>
 * - invoke method and get the return value
 * <p/>
 * - look up serializer for return value based on the value and type
 * <p/>
 * - create response msg and add return value as grand child of <soap:body>
 *
 * @param inMessage incoming MessageContext
 * @param outMessage outgoing MessageContext
 * @throws AxisFault
 */

public void invokeBusinessLogic(MessageContext inMessage, MessageContext outMessage) throws AxisFault {
    Method method = null;
    try {
        // get the implementation class for the Web Service
        Object obj = getTheImplementationObject(inMessage);

        Class implClass = obj.getClass();

        AxisOperation op = inMessage.getOperationContext().getAxisOperation();
        method = (Method) (op.getParameterValue("myMethod"));
        // If the declaring class has changed, then the cached method is invalid, so we need to
        // reload it. This is to fix AXIS2-3947.
        if (method != null && method.getDeclaringClass() != implClass) {
            method = null;
        }
        AxisService service = inMessage.getAxisService();
        OMElement methodElement = inMessage.getEnvelope().getBody().getFirstElement();
        AxisMessage inAxisMessage = op.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
        String messageNameSpace = null;

        if (method == null) {
            String methodName = op.getName().getLocalPart();
            Method[] methods = implClass.getMethods();

            for (Method method1 : methods) {
                if (method1.isBridge()) {
                    continue;
                }
                if (method1.getName().equals(methodName)) {
                    method = method1;
                    op.addParameter("myMethod", method);
                    break;
                }
            }
            if (method == null) {
                throw new AxisFault("No such method '" + methodName + "' in class " + implClass.getName());
            }
        }
        Object resObject = null;
        if (inAxisMessage != null) {
            resObject = RPCUtil.invokeServiceClass(inAxisMessage, method, obj, messageNameSpace, methodElement,
                    inMessage);
        }

        SOAPFactory fac = getSOAPFactory(inMessage);

        // Handling the response
        AxisMessage outaxisMessage = op.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
        if (outaxisMessage != null && outaxisMessage.getElementQName() != null) {
            messageNameSpace = outaxisMessage.getElementQName().getNamespaceURI();
        } else {
            messageNameSpace = service.getTargetNamespace();
        }

        OMNamespace ns = fac.createOMNamespace(messageNameSpace, service.getSchemaTargetNamespacePrefix());
        SOAPEnvelope envelope = fac.getDefaultEnvelope();
        OMElement bodyContent = null;

        if (WSDL2Constants.MEP_URI_ROBUST_IN_ONLY.equals(op.getMessageExchangePattern())) {
            OMElement bodyChild = fac.createOMElement(outMessage.getAxisMessage().getName(), ns);
            envelope.getBody().addChild(bodyChild);
            outMessage.setEnvelope(envelope);
            return;
        }
        Parameter generateBare = service.getParameter(Java2WSDLConstants.DOC_LIT_BARE_PARAMETER);
        if (generateBare != null && "true".equals(generateBare.getValue())) {
            RPCUtil.processResonseAsDocLitBare(resObject, service, envelope, fac, ns, bodyContent, outMessage);
        } else {
            RPCUtil.processResponseAsDocLitWrapped(resObject, service, method, envelope, fac, ns, bodyContent,
                    outMessage);
        }
        outMessage.setEnvelope(envelope);
    } catch (InvocationTargetException e) {
        String msg = null;
        Throwable cause = e.getCause();
        if (cause != null) {
            msg = cause.getMessage();
        }
        if (msg == null) {
            msg = "Exception occurred while trying to invoke service method "
                    + (method != null ? method.getName() : "null");
        }
        if (cause instanceof AxisFault) {
            log.debug(msg, cause);
            throw (AxisFault) cause;
        }

        Class[] exceptionTypes = method.getExceptionTypes();
        for (Class exceptionType : exceptionTypes) {
            if (exceptionType.getName().equals(cause.getClass().getName())) {
                // this is an bussiness logic exception so handle it properly
                String partQName = inMessage.getAxisService().getName() + getSimpleClassName(exceptionType);
                TypeTable typeTable = inMessage.getAxisService().getTypeTable();
                QName elementQName = typeTable.getQNamefortheType(partQName);
                SOAPFactory fac = getSOAPFactory(inMessage);
                OMElement exceptionElement = fac.createOMElement(elementQName);

                if (exceptionType.getName().equals(Exception.class.getName())) {
                    // this is an exception class. so create a element by hand and add the message
                    OMElement innterExceptionElement = fac.createOMElement(elementQName);
                    OMElement messageElement = fac.createOMElement("Message",
                            inMessage.getAxisService().getTargetNamespace(), null);
                    messageElement.setText(cause.getMessage());

                    innterExceptionElement.addChild(messageElement);
                    exceptionElement.addChild(innterExceptionElement);
                } else {
                    // if it is a normal bussiness exception we need to generate the schema assuming it is a pojo
                    QName innerElementQName = new QName(elementQName.getNamespaceURI(),
                            getSimpleClassName(exceptionType));
                    XMLStreamReader xr = BeanUtil.getPullParser(cause, innerElementQName, typeTable, true,
                            false);
                    StAXOMBuilder stAXOMBuilder = new StAXOMBuilder(OMAbstractFactory.getOMFactory(),
                            new StreamWrapper(xr));
                    OMElement documentElement = stAXOMBuilder.getDocumentElement();
                    exceptionElement.addChild(documentElement);
                }

                AxisFault axisFault = new AxisFault(cause.getMessage());
                axisFault.setDetail(exceptionElement);
                throw axisFault;
            }
        }

        log.error(msg, e);
        throw new AxisFault(msg, e);
    } catch (RuntimeException e) {
        log.error(e.getMessage(), e);
        throw AxisFault.makeFault(e);
    } catch (Exception e) {
        String msg = "Exception occurred while trying to invoke service method "
                + (method != null ? method.getName() : "null");
        log.error(msg, e);
        throw AxisFault.makeFault(e);
    }
}

From source file:org.apache.beehive.controls.system.ejb.EJBControlImpl.java

protected static boolean methodThrows(Method m, Class exceptionClass) {
    Class[] exceptions = m.getExceptionTypes();
    for (int j = 0; j < exceptions.length; j++)
        if (exceptionClass.isAssignableFrom(exceptions[j]))
            return true;
    return false;
}