Search in sources :

Example 1 with ForestConverter

use of com.dtflys.forest.converter.ForestConverter 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 2 with ForestConverter

use of com.dtflys.forest.converter.ForestConverter in project forest by dromara.

the class DownloadLifeCycle method onSuccess.

@Override
public void onSuccess(Object data, ForestRequest request, ForestResponse response) {
    String dirPath = getAttributeAsString(request, "dir");
    String filename = getAttributeAsString(request, "filename");
    Type resultType = getAttribute(request, "__resultType", Type.class);
    if (StringUtils.isBlank(filename)) {
        filename = response.getFilename();
    }
    LogConfiguration logConfiguration = request.getLogConfiguration();
    ForestLogHandler logHandler = logConfiguration.getLogHandler();
    File dir = new File(dirPath);
    if (!dir.exists()) {
        try {
            dir.mkdirs();
            if (logConfiguration.isLogEnabled()) {
                logHandler.logContent("Created directory '" + dirPath + "' successful.");
            }
        } catch (Throwable th) {
            throw new ForestRuntimeException(th);
        }
    }
    InputStream in = null;
    if (data != null && data instanceof byte[]) {
        in = new ByteArrayInputStream((byte[]) data);
    } else {
        try {
            in = response.getInputStream();
        } catch (Exception e) {
            throw new ForestRuntimeException(e);
        }
    }
    String path = dir.getAbsolutePath() + File.separator + filename;
    File file = new File(path);
    try {
        FileUtils.copyInputStreamToFile(in, file);
        FileUtils.waitFor(file, 10);
        if (logConfiguration.isLogEnabled() || !file.exists()) {
            logHandler.logContent("Saved file '" + path + "' successful.");
        }
        request.addAttachment(ATTACHMENT_NAME_FILE, file);
        if (resultType != null) {
            ForestConverter converter = request.getConfiguration().getConverterMap().get(ForestDataType.AUTO);
            data = converter.convertToJavaObject(file, resultType);
            response.setResult(data);
        }
    } catch (IOException e) {
        throw new ForestRuntimeException(e);
    }
}
Also used : ForestLogHandler(com.dtflys.forest.logging.ForestLogHandler) ForestRuntimeException(com.dtflys.forest.exceptions.ForestRuntimeException) LogConfiguration(com.dtflys.forest.logging.LogConfiguration) ForestRuntimeException(com.dtflys.forest.exceptions.ForestRuntimeException) Type(java.lang.reflect.Type) ForestDataType(com.dtflys.forest.utils.ForestDataType) ForestConverter(com.dtflys.forest.converter.ForestConverter) DownloadFile(com.dtflys.forest.extensions.DownloadFile)

Example 3 with ForestConverter

use of com.dtflys.forest.converter.ForestConverter 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)

Example 4 with ForestConverter

use of com.dtflys.forest.converter.ForestConverter in project forest by dromara.

the class ForestBeanRegister method registerConverter.

private void registerConverter(ForestConfiguration configuration, ForestDataType dataType, ForestConverterItemProperties converterItemProperties) {
    if (converterItemProperties == null) {
        return;
    }
    Class type = converterItemProperties.getType();
    if (type != null) {
        ForestConverter converter = null;
        try {
            Constructor<?>[] constructors = type.getConstructors();
            for (Constructor<?> constructor : constructors) {
                Parameter[] params = constructor.getParameters();
                if (params.length == 0) {
                    converter = (ForestConverter) constructor.newInstance(new Object[0]);
                    break;
                } else if (params.length == 1 && ForestConfiguration.class.isAssignableFrom(constructor.getParameterTypes()[0])) {
                    converter = (ForestConverter) constructor.newInstance(new Object[] { constructor });
                    break;
                }
            }
            Map<String, Object> parameters = converterItemProperties.getParameters();
            PropertyDescriptor[] descriptors = ReflectUtils.getBeanSetters(type);
            for (PropertyDescriptor descriptor : descriptors) {
                String name = descriptor.getName();
                Object value = parameters.get(name);
                Method method = descriptor.getWriteMethod();
                if (method != null) {
                    try {
                        method.invoke(converter, value);
                    } catch (IllegalAccessException e) {
                        throw new ForestRuntimeException("An error occurred during setting the property " + type.getName() + "." + name, e);
                    } catch (InvocationTargetException e) {
                        throw new ForestRuntimeException("An error occurred during setting the property " + type.getName() + "." + name, e);
                    }
                }
            }
            configuration.getConverterMap().put(dataType, converter);
        } catch (InstantiationException e) {
            throw new ForestRuntimeException("[Forest] Convert type '" + type.getName() + "' cannot be initialized!", e);
        } catch (IllegalAccessException e) {
            throw new ForestRuntimeException("[Forest] Convert type '" + type.getName() + "' cannot be initialized!", e);
        } catch (InvocationTargetException e) {
            throw new ForestRuntimeException("[Forest] Convert type '" + type.getName() + "' cannot be initialized!", e);
        }
    }
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) Constructor(java.lang.reflect.Constructor) ForestRuntimeException(com.dtflys.forest.exceptions.ForestRuntimeException) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) ForestConverter(com.dtflys.forest.converter.ForestConverter) Parameter(java.lang.reflect.Parameter)

Example 5 with ForestConverter

use of com.dtflys.forest.converter.ForestConverter in project forest by dromara.

the class TestConverterBeanListener method test1.

@Test
public void test1() {
    ForestConverter forestConverter = forestConfiguration.getConverterMap().get(ForestDataType.JSON);
    assertTrue(forestConverter instanceof ForestFastjsonConverter);
    ForestRequest<String> request = giteeClient.index2();
    System.out.println(request.execute());
}
Also used : ForestFastjsonConverter(com.dtflys.forest.converter.json.ForestFastjsonConverter) ForestConverter(com.dtflys.forest.converter.ForestConverter) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Aggregations

ForestConverter (com.dtflys.forest.converter.ForestConverter)8 ForestDataType (com.dtflys.forest.utils.ForestDataType)5 ForestRuntimeException (com.dtflys.forest.exceptions.ForestRuntimeException)3 ContentType (com.dtflys.forest.backend.ContentType)2 ForestConfiguration (com.dtflys.forest.config.ForestConfiguration)2 ForestFastjsonConverter (com.dtflys.forest.converter.json.ForestFastjsonConverter)2 LogConfiguration (com.dtflys.forest.logging.LogConfiguration)2 Type (java.lang.reflect.Type)2 HashMap (java.util.HashMap)2 Test (org.junit.Test)2 ForestEncoder (com.dtflys.forest.converter.ForestEncoder)1 ForestHandlerException (com.dtflys.forest.exceptions.ForestHandlerException)1 DownloadFile (com.dtflys.forest.extensions.DownloadFile)1 ForestQueryParameter (com.dtflys.forest.http.ForestQueryParameter)1 ForestRequest (com.dtflys.forest.http.ForestRequest)1 ForestRequestType (com.dtflys.forest.http.ForestRequestType)1 ForestResponse (com.dtflys.forest.http.ForestResponse)1 DefaultLogHandler (com.dtflys.forest.logging.DefaultLogHandler)1 ForestLogHandler (com.dtflys.forest.logging.ForestLogHandler)1 MappingParameter (com.dtflys.forest.mapping.MappingParameter)1