Search in sources :

Example 1 with ForestDataType

use of com.dtflys.forest.utils.ForestDataType in project forest by dromara.

the class ForestConfigurationBeanDefinitionParser method parseChildren.

public void parseChildren(NodeList nodeList, RootBeanDefinition beanDefinition) {
    int nodesLength = nodeList.getLength();
    if (nodesLength > 0) {
        ManagedMap<String, Object> varMap = new ManagedMap<String, Object>();
        ManagedMap<String, BeanDefinition> sslKeyStoreMap = new ManagedMap<>();
        ManagedMap<ForestDataType, BeanDefinition> converterMap = new ManagedMap<>();
        for (int i = 0; i < nodesLength; i++) {
            Node node = nodeList.item(i);
            if (node instanceof Element) {
                Element elem = (Element) node;
                String elemName = elem.getLocalName();
                if (elemName.equals("var")) {
                    parseVariable(elem, varMap);
                } else if (elemName.equals("ssl-keystore")) {
                    parseSSLKeyStore(elem, sslKeyStoreMap);
                } else if (elemName.equals("converter")) {
                    parseConverter(elem, converterMap);
                }
            }
        }
        beanDefinition.getPropertyValues().addPropertyValue("variables", varMap);
        beanDefinition.getPropertyValues().addPropertyValue("sslKeyStores", sslKeyStoreMap);
        beanDefinition.getPropertyValues().addPropertyValue("toMergeConverterMap", converterMap);
    }
}
Also used : Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) ForestDataType(com.dtflys.forest.utils.ForestDataType) ObjectWithReflectiveEqualsHashCodeToString(org.mockserver.model.ObjectWithReflectiveEqualsHashCodeToString) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) GenericBeanDefinition(org.springframework.beans.factory.support.GenericBeanDefinition) ManagedMap(org.springframework.beans.factory.support.ManagedMap)

Example 2 with ForestDataType

use of com.dtflys.forest.utils.ForestDataType in project forest by dromara.

the class ForestConfigurationBeanDefinitionParser method parseConverter.

private static void parseConverter(Element elem, ManagedMap<ForestDataType, BeanDefinition> converterMap) {
    String dataTypeName = elem.getAttribute("dataType");
    ForestDataType dataType = ForestDataType.findOrCreateDataType(dataTypeName);
    if (dataType == null) {
        throw new ForestRuntimeException("Cannot find data type named '" + dataTypeName + "'");
    }
    String className = elem.getAttribute("class");
    BeanDefinition definition = createConverterBean(className);
    NodeList nodeList = elem.getChildNodes();
    int nodeLength = nodeList.getLength();
    if (nodeLength > 0) {
        for (int i = 0; i < nodeLength; i++) {
            Node node = nodeList.item(i);
            if (node instanceof Element) {
                Element childElem = (Element) node;
                String childElemName = childElem.getLocalName();
                if (childElemName.equals("parameter")) {
                    String paramName = childElem.getAttribute("name");
                    String paramValue = childElem.getAttribute("value");
                    definition.getPropertyValues().addPropertyValue(paramName, paramValue);
                }
            }
        }
    }
    converterMap.put(dataType, definition);
}
Also used : ForestRuntimeException(com.dtflys.forest.exceptions.ForestRuntimeException) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) ForestDataType(com.dtflys.forest.utils.ForestDataType) ObjectWithReflectiveEqualsHashCodeToString(org.mockserver.model.ObjectWithReflectiveEqualsHashCodeToString) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) GenericBeanDefinition(org.springframework.beans.factory.support.GenericBeanDefinition)

Example 3 with ForestDataType

use of com.dtflys.forest.utils.ForestDataType in project forest by dromara.

the class ForestConfiguration method setToMergeConverterMap.

/**
 * 设置合并全局数据转换器表,但不会覆盖整个转换器表
 *
 * @param converterMap 数据转换器表
 * @return 当前ForestConfiguration实例
 */
public ForestConfiguration setToMergeConverterMap(Map<ForestDataType, ForestConverter> converterMap) {
    if (converterMap == null) {
        return this;
    }
    for (Map.Entry<ForestDataType, ForestConverter> entry : converterMap.entrySet()) {
        ForestDataType dataType = entry.getKey();
        ForestConverter converter = entry.getValue();
        this.converterMap.put(dataType, converter);
    }
    return this;
}
Also used : ForestConverter(com.dtflys.forest.converter.ForestConverter) ForestDataType(com.dtflys.forest.utils.ForestDataType) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 4 with ForestDataType

use of com.dtflys.forest.utils.ForestDataType in project forest by dromara.

the class ForestMethod method makeRequest.

/**
 * 创建请求
 * @param args 调用本对象对应方法时传入的参数数组
 * @return Forest请求对象,{@link ForestRequest}类实例
 */
private ForestRequest makeRequest(Object[] args) {
    MetaRequest baseMetaRequest = interfaceProxyHandler.getBaseMetaRequest();
    ForestURL baseURL = null;
    ForestQueryMap queries = new ForestQueryMap();
    if (baseUrlTemplate != null) {
        baseURL = baseUrlTemplate.render(args, queries);
    }
    if (urlTemplate == null) {
        throw new ForestRuntimeException("request URL is empty");
    }
    ForestURL renderedURL = urlTemplate.render(args, queries);
    ForestRequestType type = type(args);
    String baseContentEncoding = null;
    if (baseEncodeTemplate != null) {
        baseContentEncoding = baseEncodeTemplate.render(args);
    }
    String contentEncoding = null;
    if (encodeTemplate != null) {
        contentEncoding = encodeTemplate.render(args);
    }
    String baseContentType = null;
    if (baseContentTypeTemplate != null) {
        baseContentType = baseContentTypeTemplate.render(args);
    }
    String baseUserAgent = null;
    if (baseUserAgentTemplate != null) {
        baseUserAgent = baseUserAgentTemplate.render(args);
    }
    String charset = null;
    String renderedCharset = charsetTemplate.render(args);
    if (StringUtils.isNotBlank(renderedCharset)) {
        charset = renderedCharset;
    } else if (baseCharsetTemplate != null) {
        charset = baseCharsetTemplate.render(args);
    } else if (StringUtils.isNotBlank(configuration.getCharset())) {
        charset = configuration.getCharset();
    }
    String responseEncoding = null;
    if (responseEncodingTemplate != null) {
        responseEncoding = responseEncodingTemplate.render(args);
    }
    String sslProtocol = null;
    String renderedSslProtocol = sslProtocolTemplate.render(args);
    if (StringUtils.isNotBlank(renderedSslProtocol)) {
        sslProtocol = renderedSslProtocol;
    } else if (baseSslProtocolTemplate != null) {
        sslProtocol = baseSslProtocolTemplate.render(args);
    } else {
        sslProtocol = configuration.getSslProtocol();
    }
    String renderedContentType = null;
    if (contentTypeTemplate != null) {
        renderedContentType = contentTypeTemplate.render(args).trim();
    }
    String renderedUserAgent = null;
    if (userAgentTemplate != null) {
        renderedUserAgent = userAgentTemplate.render(args).trim();
    }
    List<RequestNameValue> nameValueList = new ArrayList<>();
    String[] headerArray = baseMetaRequest.getHeaders();
    MappingTemplate[] baseHeaders = null;
    if (headerArray != null && headerArray.length > 0) {
        baseHeaders = new MappingTemplate[headerArray.length];
        for (int j = 0; j < baseHeaders.length; j++) {
            MappingTemplate header = new MappingTemplate(BaseRequest.class, "headers", this, headerArray[j], this, configuration.getProperties(), forestParameters);
            baseHeaders[j] = header;
        }
    }
    AddressSource addressSource = configuration.getBaseAddressSource();
    ForestAddress address = configuration.getBaseAddress();
    if (address == null) {
        // 默认根地址
        address = DEFAULT_ADDRESS;
    }
    ForestURL addressURL = null;
    if (baseURL != null) {
        renderedURL.setBaseURL(baseURL);
    }
    try {
        addressURL = new ForestURL(new URL("http://localhost"));
        addressURL.setBaseAddress(address);
        renderedURL = renderedURL.mergeURLWith(addressURL);
    } catch (MalformedURLException e) {
        throw new ForestRuntimeException(e);
    }
    boolean autoRedirection = configuration.isAutoRedirection();
    String bodyTypeName = "text";
    if (bodyTypeTemplate != null) {
        bodyTypeName = bodyTypeTemplate.render(args);
    }
    ForestDataType bodyType = ForestDataType.findByName(bodyTypeName);
    // createExecutor and initialize http instance
    ForestRequest<T> request = new ForestRequest(configuration, this, args);
    request.url(renderedURL).type(type).bodyType(bodyType).addAllQuery(queries).charset(charset).autoRedirects(autoRedirection).setSslProtocol(sslProtocol).setLogConfiguration(logConfiguration).setAsync(async);
    if (addressSource != null) {
        address = addressSource.getAddress(request);
        request.address(address);
    }
    if (StringUtils.isNotEmpty(responseEncoding)) {
        request.setResponseEncode(responseEncoding);
    }
    if (StringUtils.isNotEmpty(renderedContentType)) {
        request.setContentType(renderedContentType);
    }
    if (StringUtils.isNotEmpty(contentEncoding)) {
        request.setContentEncoding(contentEncoding);
    }
    if (StringUtils.isNotEmpty(renderedUserAgent)) {
        request.setUserAgent(renderedUserAgent);
    }
    for (int i = 0; i < namedParameters.size(); i++) {
        MappingParameter parameter = namedParameters.get(i);
        if (parameter.isObjectProperties()) {
            int target = parameter.isUnknownTarget() ? type.getDefaultParamTarget() : parameter.getTarget();
            Object obj = args[parameter.getIndex()];
            if (obj == null && StringUtils.isNotEmpty(parameter.getDefaultValue())) {
                obj = parameter.getConvertedDefaultValue(configuration.getJsonConverter());
            }
            if (parameter.isJsonParam()) {
                String json = "";
                if (obj != null) {
                    ForestJsonConverter jsonConverter = configuration.getJsonConverter();
                    obj = parameter.getFilterChain().doFilter(configuration, obj);
                    json = jsonConverter.encodeToString(obj);
                }
                if (MappingParameter.isHeader(target)) {
                    request.addHeader(new RequestNameValue(parameter.getJsonParamName(), json, target).setDefaultValue(parameter.getDefaultValue()));
                } else {
                    nameValueList.add(new RequestNameValue(parameter.getJsonParamName(), json, target, parameter.getPartContentType()).setDefaultValue(parameter.getDefaultValue()));
                }
            } else if (!parameter.getFilterChain().isEmpty()) {
                obj = parameter.getFilterChain().doFilter(configuration, obj);
                if (obj == null && StringUtils.isNotEmpty(parameter.getDefaultValue())) {
                    obj = parameter.getDefaultValue();
                }
                if (obj != null) {
                    if (MappingParameter.isHeader(target)) {
                        request.addHeader(new RequestNameValue(null, obj, target));
                    } else if (MappingParameter.isQuery(target)) {
                        request.addQuery(obj.toString(), (Object) null, parameter.isUrlEncode(), parameter.getCharset());
                    } else if (MappingParameter.isBody(target)) {
                        ForestRequestBody body = RequestBodyBuilder.type(obj.getClass()).build(obj, parameter.getDefaultValue());
                        request.addBody(body);
                    } else {
                        nameValueList.add(new RequestNameValue(obj.toString(), target, parameter.getPartContentType()).setDefaultValue(parameter.getDefaultValue()));
                    }
                }
            } else if (obj instanceof CharSequence) {
                if (MappingParameter.isQuery(target)) {
                    request.addQuery(ForestQueryParameter.createSimpleQueryParameter(obj).setDefaultValue(parameter.getDefaultValue()));
                } else if (MappingParameter.isBody(target)) {
                    request.addBody(new StringRequestBody(obj.toString()).setDefaultValue(parameter.getDefaultValue()));
                }
            } else if (obj instanceof Map) {
                Map map = (Map) obj;
                if (MappingParameter.isQuery(target)) {
                    request.addQuery(map, parameter.isUrlEncode(), parameter.getCharset());
                } else if (MappingParameter.isBody(target)) {
                    request.addBody(map, parameter.getPartContentType());
                } else if (MappingParameter.isHeader(target)) {
                    request.addHeader(map);
                }
            } else if (obj instanceof Iterable || (obj != null && (obj.getClass().isArray() || ReflectUtils.isPrimaryType(obj.getClass())))) {
                if (MappingParameter.isQuery(target)) {
                    if (parameter.isJsonParam()) {
                        request.addQuery(parameter.getName(), obj, parameter.isUrlEncode(), parameter.getCharset());
                    } else {
                        if (obj instanceof Iterable) {
                            for (Object subItem : (Iterable) obj) {
                                if (subItem instanceof ForestQueryParameter) {
                                    request.addQuery((ForestQueryParameter) subItem);
                                } else {
                                    request.addQuery(ForestQueryParameter.createSimpleQueryParameter(subItem));
                                }
                            }
                        } else if (obj.getClass().isArray()) {
                            if (obj instanceof ForestQueryParameter[]) {
                                request.addQuery((ForestQueryParameter[]) obj);
                            }
                        }
                    }
                } else if (MappingParameter.isBody(target)) {
                    ForestRequestBody body = RequestBodyBuilder.type(obj.getClass()).build(obj, parameter.getDefaultValue());
                    request.addBody(body);
                }
            } else if (MappingParameter.isBody(target)) {
                ForestRequestBody body = RequestBodyBuilder.type(obj.getClass()).build(obj, parameter.getDefaultValue());
                request.addBody(body);
            } else {
                try {
                    List<RequestNameValue> list = getNameValueListFromObjectWithJSON(parameter, configuration, obj, type);
                    for (RequestNameValue nameValue : list) {
                        if (nameValue.isInHeader()) {
                            request.addHeader(nameValue);
                        } else {
                            nameValueList.add(nameValue);
                        }
                    }
                } catch (Throwable th) {
                    throw new ForestRuntimeException(th);
                }
            }
        } else if (parameter.getIndex() != null) {
            int target = parameter.isUnknownTarget() ? type.getDefaultParamTarget() : parameter.getTarget();
            RequestNameValue nameValue = new RequestNameValue(parameter.getName(), target, parameter.getPartContentType()).setDefaultValue(parameter.getDefaultValue());
            Object obj = args[parameter.getIndex()];
            if (obj == null && StringUtils.isNotEmpty(nameValue.getDefaultValue())) {
                obj = parameter.getConvertedDefaultValue(configuration.getJsonConverter());
            }
            if (obj != null) {
                if (MappingParameter.isQuery(target) && obj.getClass().isArray() && !(obj instanceof byte[]) && !(obj instanceof Byte[])) {
                    int len = Array.getLength(obj);
                    for (int idx = 0; idx < len; idx++) {
                        Object arrayItem = Array.get(obj, idx);
                        ForestQueryParameter queryParameter = new ForestQueryParameter(parameter.getName(), arrayItem, parameter.isUrlEncode(), parameter.getCharset());
                        request.addQuery(queryParameter);
                    }
                } else {
                    nameValue.setValue(obj);
                    if (MappingParameter.isHeader(target)) {
                        request.addHeader(nameValue);
                    } else if (MappingParameter.isQuery(target)) {
                        if (!parameter.isJsonParam() && obj instanceof Iterable) {
                            int index = 0;
                            MappingTemplate template = makeTemplate(parameter);
                            VariableScope parentScope = template.getVariableScope();
                            for (Object subItem : (Iterable) obj) {
                                SubVariableScope scope = new SubVariableScope(parentScope);
                                scope.addVariableValue("_it", subItem);
                                scope.addVariableValue("_index", index++);
                                template.setVariableScope(scope);
                                String name = template.render(args);
                                request.addQuery(name, subItem, parameter.isUrlEncode(), parameter.getCharset());
                            }
                        } else if (parameter.isJsonParam()) {
                            request.addJSONQuery(parameter.getName(), obj);
                        } else {
                            request.addQuery(parameter.getName(), obj, parameter.isUrlEncode(), parameter.getCharset());
                        }
                    } else {
                        MappingTemplate template = makeTemplate(parameter);
                        if (obj instanceof Iterable && template.hasIterateVariable()) {
                            int index = 0;
                            VariableScope parentScope = template.getVariableScope();
                            for (Object subItem : (Iterable) obj) {
                                SubVariableScope scope = new SubVariableScope(parentScope);
                                template.setVariableScope(scope);
                                scope.addVariableValue("_it", subItem);
                                scope.addVariableValue("_index", index++);
                                String name = template.render(args);
                                nameValueList.add(new RequestNameValue(name, subItem, target, parameter.getPartContentType()).setDefaultValue(parameter.getDefaultValue()));
                            }
                        } else {
                            nameValueList.add(nameValue);
                        }
                    }
                }
            }
        }
    }
    if (request.getContentType() == null) {
        if (StringUtils.isNotEmpty(baseContentType)) {
            request.setContentType(baseContentType);
        }
    }
    if (request.getContentEncoding() == null) {
        if (StringUtils.isNotEmpty(baseContentEncoding)) {
            request.setContentEncoding(baseContentEncoding);
        }
    }
    if (request.getUserAgent() == null) {
        if (StringUtils.isNotEmpty(baseUserAgent)) {
            request.setUserAgent(baseUserAgent);
        }
    }
    List<ForestMultipart> multiparts = new ArrayList<>(multipartFactories.size());
    String contentType = request.getContentType();
    if (!multipartFactories.isEmpty()) {
        if (StringUtils.isBlank(contentType)) {
            String boundary = StringUtils.generateBoundary();
            request.setContentType(ContentType.MULTIPART_FORM_DATA + "; boundary=" + boundary);
        } else if (ContentType.MULTIPART_FORM_DATA.equalsIgnoreCase(contentType) && request.getBoundary() == null) {
            request.setBoundary(StringUtils.generateBoundary());
        }
    }
    for (int i = 0; i < multipartFactories.size(); i++) {
        ForestMultipartFactory factory = multipartFactories.get(i);
        MappingTemplate nameTemplate = factory.getNameTemplate();
        MappingTemplate fileNameTemplate = factory.getFileNameTemplate();
        int index = factory.getIndex();
        Object data = args[index];
        factory.addMultipart(nameTemplate, fileNameTemplate, data, multiparts, args);
    }
    request.setMultiparts(multiparts);
    // setup ssl keystore
    if (sslKeyStoreId != null) {
        SSLKeyStore sslKeyStore = null;
        String keyStoreId = sslKeyStoreId.render(args);
        if (StringUtils.isNotEmpty(keyStoreId)) {
            sslKeyStore = configuration.getKeyStore(keyStoreId);
            request.setKeyStore(sslKeyStore);
        }
    }
    if (encoder != null) {
        request.setEncoder(encoder);
    }
    if (decoder != null) {
        request.setDecoder(decoder);
    }
    if (progressStep >= 0) {
        request.setProgressStep(progressStep);
    }
    if (configuration.getDefaultParameters() != null) {
        request.addNameValue(configuration.getDefaultParameters());
    }
    if (baseHeaders != null && baseHeaders.length > 0) {
        for (MappingTemplate baseHeader : baseHeaders) {
            String headerText = baseHeader.render(args);
            String[] headerNameValue = headerText.split(":", 2);
            if (headerNameValue.length > 1) {
                String name = headerNameValue[0].trim();
                if (request.getHeader(name) == null) {
                    request.addHeader(name, headerNameValue[1].trim());
                }
            }
        }
    }
    if (configuration.getDefaultHeaders() != null) {
        request.addHeaders(configuration.getDefaultHeaders());
    }
    List<RequestNameValue> dataNameValueList = new ArrayList<>();
    renderedContentType = request.getContentType();
    if (renderedContentType == null || renderedContentType.equalsIgnoreCase(ContentType.APPLICATION_X_WWW_FORM_URLENCODED)) {
        for (int i = 0; i < dataTemplateArray.length; i++) {
            MappingTemplate dataTemplate = dataTemplateArray[i];
            String data = dataTemplate.render(args);
            String[] paramArray = data.split("&");
            for (int j = 0; j < paramArray.length; j++) {
                String dataParam = paramArray[j];
                String[] dataNameValue = dataParam.split("=", 2);
                if (dataNameValue.length > 0) {
                    String name = dataNameValue[0].trim();
                    RequestNameValue nameValue = new RequestNameValue(name, type.getDefaultParamTarget());
                    if (dataNameValue.length == 2) {
                        nameValue.setValue(dataNameValue[1].trim());
                    }
                    nameValueList.add(nameValue);
                    dataNameValueList.add(nameValue);
                }
            }
        }
    } else {
        for (int i = 0; i < dataTemplateArray.length; i++) {
            MappingTemplate dataTemplate = dataTemplateArray[i];
            String data = dataTemplate.render(args);
            request.addBody(data);
        }
    }
    request.addNameValue(nameValueList);
    for (int i = 0; i < headerTemplateArray.length; i++) {
        MappingTemplate headerTemplate = headerTemplateArray[i];
        String header = headerTemplate.render(args);
        String[] headNameValue = header.split(":", 2);
        if (headNameValue.length > 0) {
            String name = headNameValue[0].trim();
            RequestNameValue nameValue = new RequestNameValue(name, TARGET_HEADER);
            if (headNameValue.length == 2) {
                nameValue.setValue(headNameValue[1].trim());
            }
            request.addHeader(nameValue);
        }
    }
    if (timeout != null) {
        request.setTimeout(timeout);
    } else if (baseTimeout != null) {
        request.setTimeout(baseTimeout);
    } else if (configuration.getTimeout() != null) {
        request.setTimeout(configuration.getTimeout());
    }
    if (connectTimeout != null) {
        request.setConnectTimeout(connectTimeout);
    } else if (baseConnectTimeout != null) {
        request.setConnectTimeout(baseConnectTimeout);
    } else if (configuration.getConnectTimeout() != null) {
        request.setConnectTimeout(configuration.getConnectTimeout());
    }
    if (readTimeout != null) {
        request.setReadTimeout(readTimeout);
    } else if (baseReadTimeout != null) {
        request.setReadTimeout(baseReadTimeout);
    } else if (configuration.getReadTimeout() != null) {
        request.setReadTimeout(configuration.getReadTimeout());
    }
    if (retryCount != null) {
        request.setMaxRetryCount(retryCount);
    } else if (baseRetryCount != null) {
        request.setMaxRetryCount(baseRetryCount);
    } else if (configuration.getMaxRetryCount() != null) {
        request.setMaxRetryCount(configuration.getMaxRetryCount());
    }
    if (maxRetryInterval >= 0) {
        request.setMaxRetryInterval(maxRetryInterval);
    } else if (baseMaxRetryInterval != null) {
        request.setMaxRetryInterval(baseMaxRetryInterval);
    } else if (configuration.getMaxRetryInterval() >= 0) {
        request.setMaxRetryInterval(configuration.getMaxRetryInterval());
    }
    Class globalRetryerClass = configuration.getRetryer();
    if (retryerClass != null && ForestRetryer.class.isAssignableFrom(retryerClass)) {
        request.setRetryer(retryerClass);
    } else if (baseRetryerClass != null && ForestRetryer.class.isAssignableFrom(baseRetryerClass)) {
        request.setRetryer(baseRetryerClass);
    } else if (globalRetryerClass != null && ForestRetryer.class.isAssignableFrom(globalRetryerClass)) {
        request.setRetryer(globalRetryerClass);
    }
    if (onSuccessParameter != null) {
        OnSuccess<?> onSuccessCallback = (OnSuccess<?>) args[onSuccessParameter.getIndex()];
        request.setOnSuccess(onSuccessCallback);
    }
    if (onErrorParameter != null) {
        OnError onErrorCallback = (OnError) args[onErrorParameter.getIndex()];
        request.setOnError(onErrorCallback);
    }
    if (onRedirectionParameter != null) {
        OnRedirection onRedirectionCallback = (OnRedirection) args[onRedirectionParameter.getIndex()];
        request.setOnRedirection(onRedirectionCallback);
    }
    if (onProgressParameter != null) {
        OnProgress onProgressCallback = (OnProgress) args[onProgressParameter.getIndex()];
        request.setOnProgress(onProgressCallback);
    }
    if (onSaveCookieParameter != null) {
        OnSaveCookie onSaveCookieCallback = (OnSaveCookie) args[onSaveCookieParameter.getIndex()];
        request.setOnSaveCookie(onSaveCookieCallback);
    }
    if (onLoadCookieParameter != null) {
        OnLoadCookie onLoadCookieCallback = (OnLoadCookie) args[onLoadCookieParameter.getIndex()];
        request.setOnLoadCookie(onLoadCookieCallback);
    }
    String dataType = dataTypeTemplate.render(args);
    if (StringUtils.isEmpty(dataType)) {
        request.setDataType(ForestDataType.TEXT);
    } else {
        dataType = dataType.toUpperCase();
        ForestDataType forestDataType = ForestDataType.findByName(dataType);
        request.setDataType(forestDataType);
    }
    if (interceptorAttributesList != null && interceptorAttributesList.size() > 0) {
        for (InterceptorAttributes attributes : interceptorAttributesList) {
            InterceptorAttributes newAttrs = attributes.clone();
            request.addInterceptorAttributes(newAttrs.getInterceptorClass(), newAttrs);
            request.getInterceptorAttributes(newAttrs.getInterceptorClass()).render(args);
        }
    }
    if (globalInterceptorList != null && globalInterceptorList.size() > 0) {
        for (Interceptor item : globalInterceptorList) {
            request.addInterceptor(item);
        }
    }
    if (baseInterceptorList != null && baseInterceptorList.size() > 0) {
        for (Interceptor item : baseInterceptorList) {
            request.addInterceptor(item);
        }
    }
    if (interceptorList != null && interceptorList.size() > 0) {
        for (Interceptor item : interceptorList) {
            request.addInterceptor(item);
        }
    }
    return request;
}
Also used : MalformedURLException(java.net.MalformedURLException) OnError(com.dtflys.forest.callback.OnError) OnProgress(com.dtflys.forest.callback.OnProgress) SSLKeyStore(com.dtflys.forest.ssl.SSLKeyStore) ForestDataType(com.dtflys.forest.utils.ForestDataType) ForestURL(com.dtflys.forest.http.ForestURL) ForestMultipartFactory(com.dtflys.forest.multipart.ForestMultipartFactory) AddressSource(com.dtflys.forest.callback.AddressSource) OnRedirection(com.dtflys.forest.callback.OnRedirection) ForestAddress(com.dtflys.forest.http.ForestAddress) OnSaveCookie(com.dtflys.forest.callback.OnSaveCookie) ForestQueryMap(com.dtflys.forest.http.ForestQueryMap) VariableScope(com.dtflys.forest.config.VariableScope) SubVariableScope(com.dtflys.forest.mapping.SubVariableScope) OnLoadCookie(com.dtflys.forest.callback.OnLoadCookie) ForestJsonConverter(com.dtflys.forest.converter.json.ForestJsonConverter) MappingTemplate(com.dtflys.forest.mapping.MappingTemplate) ForestMultipart(com.dtflys.forest.multipart.ForestMultipart) OnSuccess(com.dtflys.forest.callback.OnSuccess) ForestQueryMap(com.dtflys.forest.http.ForestQueryMap) URL(java.net.URL) ForestURL(com.dtflys.forest.http.ForestURL) ForestRequestType(com.dtflys.forest.http.ForestRequestType) RequestNameValue(com.dtflys.forest.utils.RequestNameValue) SubVariableScope(com.dtflys.forest.mapping.SubVariableScope) Interceptor(com.dtflys.forest.interceptor.Interceptor) ForestRequestBody(com.dtflys.forest.http.ForestRequestBody) MappingParameter(com.dtflys.forest.mapping.MappingParameter) ForestRuntimeException(com.dtflys.forest.exceptions.ForestRuntimeException) ForestRequest(com.dtflys.forest.http.ForestRequest) StringRequestBody(com.dtflys.forest.http.body.StringRequestBody) ForestQueryParameter(com.dtflys.forest.http.ForestQueryParameter) InterceptorAttributes(com.dtflys.forest.interceptor.InterceptorAttributes) ForestRetryer(com.dtflys.forest.retryer.ForestRetryer)

Example 5 with ForestDataType

use of com.dtflys.forest.utils.ForestDataType in project forest by dromara.

the class ResultHandler method getResult.

public Object getResult(ForestRequest request, ForestResponse response, Type resultType, Class resultClass) {
    if (request.isDownloadFile()) {
        return null;
    }
    Object result = response.getResult();
    if (result != null && resultClass.isAssignableFrom(result.getClass())) {
        return result;
    }
    if (isReceivedResponseData(response)) {
        try {
            if (void.class.isAssignableFrom(resultClass)) {
                return null;
            }
            if (ForestResponse.class.isAssignableFrom(resultClass) || ForestRequest.class.isAssignableFrom(resultClass)) {
                if (resultType instanceof ParameterizedType) {
                    ParameterizedType parameterizedType = (ParameterizedType) resultType;
                    Class rowClass = (Class) parameterizedType.getRawType();
                    if (ForestResponse.class.isAssignableFrom(rowClass) || ForestRequest.class.isAssignableFrom(resultClass)) {
                        Type realType = parameterizedType.getActualTypeArguments()[0];
                        Class realClass = ReflectUtils.toClass(parameterizedType.getActualTypeArguments()[0]);
                        if (realClass == null) {
                            realClass = String.class;
                        }
                        Object realResult = getResult(request, response, realType, realClass);
                        response.setResult(realResult);
                    }
                } else {
                    Object realResult = getResult(request, response, Object.class, Object.class);
                    response.setResult(realResult);
                }
                return response;
            }
            if (Future.class.isAssignableFrom(resultClass)) {
                if (resultType instanceof ParameterizedType) {
                    ParameterizedType parameterizedType = (ParameterizedType) resultType;
                    Class rowClass = (Class) parameterizedType.getRawType();
                    if (Future.class.isAssignableFrom(rowClass)) {
                        Type realType = parameterizedType.getActualTypeArguments()[0];
                        Class realClass = ReflectUtils.toClass(parameterizedType.getActualTypeArguments()[0]);
                        return getResult(request, response, realType, realClass);
                    }
                }
            }
            if (resultClass.isArray()) {
                if (byte[].class.isAssignableFrom(resultClass)) {
                    return response.getByteArray();
                }
            }
            Object attFile = request.getAttachment(DownloadLifeCycle.ATTACHMENT_NAME_FILE);
            if (attFile != null && attFile instanceof File) {
                ForestConverter converter = request.getConfiguration().getConverter(ForestDataType.JSON);
                return converter.convertToJavaObject(attFile, resultClass);
            }
            String responseText = null;
            if (result != null && CharSequence.class.isAssignableFrom(result.getClass())) {
                responseText = result.toString();
            } else if (CharSequence.class.isAssignableFrom(resultClass)) {
                try {
                    responseText = response.readAsString();
                } catch (Throwable th) {
                    request.getLifeCycleHandler().handleError(request, response, th);
                }
            } else {
                try {
                    responseText = response.getContent();
                } catch (Throwable th) {
                    request.getLifeCycleHandler().handleError(request, response, th);
                }
            }
            response.setContent(responseText);
            if (CharSequence.class.isAssignableFrom(resultClass)) {
                return responseText;
            }
            if (InputStream.class.isAssignableFrom(resultClass)) {
                return response.getInputStream();
            }
            ContentType contentType = response.getContentType();
            if (request.getDecoder() != null) {
                if (contentType != null && contentType.canReadAsString()) {
                    return request.getDecoder().convertToJavaObject(responseText, resultType);
                } else {
                    return request.getDecoder().convertToJavaObject(response.getByteArray(), resultType);
                }
            }
            ForestDataType dataType = request.getDataType();
            ForestConverter converter = request.getConfiguration().getConverter(dataType);
            if (contentType != null && contentType.canReadAsString()) {
                return converter.convertToJavaObject(responseText, resultType);
            }
            Charset charset = null;
            String resCharset = response.getCharset();
            if (resCharset != null) {
                charset = Charset.forName(resCharset);
            }
            return converter.convertToJavaObject(response.getByteArray(), resultType, charset);
        } catch (Exception e) {
            throw new ForestHandlerException(e, request, response);
        }
    } else if (ForestResponse.class.isAssignableFrom(resultClass)) {
        return response;
    }
    return null;
}
Also used : ForestResponse(com.dtflys.forest.http.ForestResponse) ContentType(com.dtflys.forest.backend.ContentType) ForestDataType(com.dtflys.forest.utils.ForestDataType) Charset(java.nio.charset.Charset) ForestRequest(com.dtflys.forest.http.ForestRequest) ForestHandlerException(com.dtflys.forest.exceptions.ForestHandlerException) ParameterizedType(java.lang.reflect.ParameterizedType) ContentType(com.dtflys.forest.backend.ContentType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) ForestDataType(com.dtflys.forest.utils.ForestDataType) ForestHandlerException(com.dtflys.forest.exceptions.ForestHandlerException) ForestConverter(com.dtflys.forest.converter.ForestConverter) File(java.io.File)

Aggregations

ForestDataType (com.dtflys.forest.utils.ForestDataType)7 ForestConverter (com.dtflys.forest.converter.ForestConverter)3 ContentType (com.dtflys.forest.backend.ContentType)2 ForestRuntimeException (com.dtflys.forest.exceptions.ForestRuntimeException)2 ForestRequest (com.dtflys.forest.http.ForestRequest)2 ObjectWithReflectiveEqualsHashCodeToString (org.mockserver.model.ObjectWithReflectiveEqualsHashCodeToString)2 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)2 GenericBeanDefinition (org.springframework.beans.factory.support.GenericBeanDefinition)2 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)2 Element (org.w3c.dom.Element)2 Node (org.w3c.dom.Node)2 AddressSource (com.dtflys.forest.callback.AddressSource)1 OnError (com.dtflys.forest.callback.OnError)1 OnLoadCookie (com.dtflys.forest.callback.OnLoadCookie)1 OnProgress (com.dtflys.forest.callback.OnProgress)1 OnRedirection (com.dtflys.forest.callback.OnRedirection)1 OnSaveCookie (com.dtflys.forest.callback.OnSaveCookie)1 OnSuccess (com.dtflys.forest.callback.OnSuccess)1 ForestConfiguration (com.dtflys.forest.config.ForestConfiguration)1 VariableScope (com.dtflys.forest.config.VariableScope)1