Search in sources :

Example 26 with ForestRuntimeException

use of com.dtflys.forest.exceptions.ForestRuntimeException 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 27 with ForestRuntimeException

use of com.dtflys.forest.exceptions.ForestRuntimeException in project forest by dromara.

the class ForestBeanRegister method registerForestConfiguration.

public ForestConfiguration registerForestConfiguration(ForestConfigurationProperties forestConfigurationProperties) {
    BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(ForestConfiguration.class);
    String id = forestConfigurationProperties.getBeanId();
    if (StringUtils.isBlank(id)) {
        id = "forestConfiguration";
    }
    Class<? extends ForestLogHandler> logHandlerClass = forestConfigurationProperties.getLogHandler();
    ForestLogHandler logHandler = null;
    if (logHandlerClass != null) {
        try {
            logHandler = logHandlerClass.newInstance();
        } catch (InstantiationException e) {
            throw new ForestRuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new ForestRuntimeException(e);
        }
    }
    beanDefinitionBuilder.addPropertyValue("maxAsyncThreadSize", forestConfigurationProperties.getMaxAsyncThreadSize()).addPropertyValue("maxConnections", forestConfigurationProperties.getMaxConnections()).addPropertyValue("maxRouteConnections", forestConfigurationProperties.getMaxRouteConnections()).addPropertyValue("timeout", forestConfigurationProperties.getTimeout()).addPropertyValue("connectTimeout", forestConfigurationProperties.getConnectTimeoutMillis()).addPropertyValue("readTimeout", forestConfigurationProperties.getReadTimeoutMillis()).addPropertyValue("charset", forestConfigurationProperties.getCharset()).addPropertyValue("retryer", forestConfigurationProperties.getRetryer()).addPropertyValue("maxRetryCount", forestConfigurationProperties.getMaxRetryCount()).addPropertyValue("maxRetryInterval", forestConfigurationProperties.getMaxRetryInterval()).addPropertyValue("autoRedirection", forestConfigurationProperties.isAutoRedirection()).addPropertyValue("logEnabled", forestConfigurationProperties.isLogEnabled()).addPropertyValue("logRequest", forestConfigurationProperties.isLogRequest()).addPropertyValue("logResponseStatus", forestConfigurationProperties.isLogResponseStatus()).addPropertyValue("logResponseContent", forestConfigurationProperties.isLogResponseContent()).addPropertyValue("logHandler", logHandler).addPropertyValue("backendName", forestConfigurationProperties.getBackend()).addPropertyValue("baseAddressScheme", forestConfigurationProperties.getBaseAddressScheme()).addPropertyValue("baseAddressHost", forestConfigurationProperties.getBaseAddressHost()).addPropertyValue("baseAddressPort", forestConfigurationProperties.getBaseAddressPort()).addPropertyValue("baseAddressSourceClass", forestConfigurationProperties.getBaseAddressSource()).addPropertyValue("successWhenClass", forestConfigurationProperties.getSuccessWhen()).addPropertyValue("retryWhenClass", forestConfigurationProperties.getRetryWhen()).addPropertyValue("interceptors", forestConfigurationProperties.getInterceptors()).addPropertyValue("sslProtocol", forestConfigurationProperties.getSslProtocol()).addPropertyValue("variables", forestConfigurationProperties.getVariables()).setLazyInit(false).setFactoryMethod("configuration");
    BeanDefinition forestPropertiesBean = registerForestPropertiesBean();
    beanDefinitionBuilder.addPropertyValue("properties", forestPropertiesBean);
    BeanDefinition forestObjectFactoryBeanDefinition = registerForestObjectFactoryBean();
    beanDefinitionBuilder.addPropertyValue("forestObjectFactory", forestObjectFactoryBeanDefinition);
    BeanDefinition interceptorFactoryBeanDefinition = registerInterceptorFactoryBean();
    beanDefinitionBuilder.addPropertyValue("interceptorFactory", interceptorFactoryBeanDefinition);
    List<ForestSSLKeyStoreProperties> sslKeyStorePropertiesList = forestConfigurationProperties.getSslKeyStores();
    ManagedMap<String, BeanDefinition> sslKeystoreMap = new ManagedMap<>();
    for (ForestSSLKeyStoreProperties keyStoreProperties : sslKeyStorePropertiesList) {
        registerSSLKeyStoreBean(sslKeystoreMap, keyStoreProperties);
    }
    BeanDefinition beanDefinition = beanDefinitionBuilder.getRawBeanDefinition();
    beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
    beanDefinition.getPropertyValues().addPropertyValue("sslKeyStores", sslKeystoreMap);
    BeanDefinitionRegistry beanFactory = (BeanDefinitionRegistry) applicationContext.getBeanFactory();
    beanFactory.registerBeanDefinition(id, beanDefinition);
    ForestConfiguration configuration = applicationContext.getBean(id, ForestConfiguration.class);
    Map<String, Class> filters = forestConfigurationProperties.getFilters();
    for (Map.Entry<String, Class> entry : filters.entrySet()) {
        String filterName = entry.getKey();
        Class filterClass = entry.getValue();
        configuration.registerFilter(filterName, filterClass);
    }
    ForestConvertProperties convertProperties = forestConfigurationProperties.getConverters();
    if (convertProperties != null) {
        registerConverter(configuration, ForestDataType.TEXT, convertProperties.getText());
        registerConverter(configuration, ForestDataType.JSON, convertProperties.getJson());
        registerConverter(configuration, ForestDataType.XML, convertProperties.getXml());
        registerConverter(configuration, ForestDataType.BINARY, convertProperties.getBinary());
        registerConverter(configuration, ForestDataType.PROTOBUF, convertProperties.getProtobuf());
    }
    registerConverterBeanListener(configuration);
    return configuration;
}
Also used : ForestSSLKeyStoreProperties(com.dtflys.forest.springboot.properties.ForestSSLKeyStoreProperties) ForestConvertProperties(com.dtflys.forest.springboot.properties.ForestConvertProperties) ForestLogHandler(com.dtflys.forest.logging.ForestLogHandler) ForestRuntimeException(com.dtflys.forest.exceptions.ForestRuntimeException) BeanDefinitionRegistry(org.springframework.beans.factory.support.BeanDefinitionRegistry) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) ForestConfiguration(com.dtflys.forest.config.ForestConfiguration) Map(java.util.Map) ManagedMap(org.springframework.beans.factory.support.ManagedMap) ManagedMap(org.springframework.beans.factory.support.ManagedMap)

Example 28 with ForestRuntimeException

use of com.dtflys.forest.exceptions.ForestRuntimeException 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 29 with ForestRuntimeException

use of com.dtflys.forest.exceptions.ForestRuntimeException in project forest by dromara.

the class Test0 method testRetry.

@Test
public void testRetry() {
    ForestLogger logger = Mockito.mock(ForestLogger.class);
    config0.getLogHandler().setLogger(logger);
    try {
        beastshopClient.testRetry();
    } catch (ForestRuntimeException e) {
    }
    HttpBackend backend = config0.getBackend();
    String backendName = backend.getName();
    Mockito.verify(logger).info("[Forest] Request (" + backendName + "): \n" + "\t[Retry]: 1\n" + "\tGET https://www.thebeastshop.com/autopage/shops.htm HTTPS");
    Mockito.verify(logger).info("[Forest] Request (" + backendName + "): \n" + "\t[Retry]: 2\n" + "\tGET https://www.thebeastshop.com/autopage/shops.htm HTTPS");
    Mockito.verify(logger).info("[Forest] Request (" + backendName + "): \n" + "\t[Retry]: 3\n" + "\tGET https://www.thebeastshop.com/autopage/shops.htm HTTPS");
    Mockito.verify(logger).info("[Forest] Request (" + backendName + "): \n" + "\t[Retry]: 4\n" + "\tGET https://www.thebeastshop.com/autopage/shops.htm HTTPS");
    Mockito.verify(logger).info("[Forest] Request (" + backendName + "): \n" + "\t[Retry]: 5\n" + "\tGET https://www.thebeastshop.com/autopage/shops.htm HTTPS");
// Mockito.verify(logger).info("[Forest] [Network Error]: connect timed out");
}
Also used : ForestRuntimeException(com.dtflys.forest.exceptions.ForestRuntimeException) ForestLogger(com.dtflys.forest.logging.ForestLogger) HttpBackend(com.dtflys.forest.backend.HttpBackend) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 30 with ForestRuntimeException

use of com.dtflys.forest.exceptions.ForestRuntimeException in project forest by dromara.

the class TestInterceptorChain method testInterceptorChain.

@Test
public void testInterceptorChain() {
    final AtomicInteger count = new AtomicInteger(0);
    final AtomicBoolean inter1Before = new AtomicBoolean(false);
    final AtomicBoolean inter2Before = new AtomicBoolean(false);
    final AtomicBoolean inter3Before = new AtomicBoolean(false);
    final AtomicBoolean inter1Success = new AtomicBoolean(false);
    final AtomicBoolean inter2Success = new AtomicBoolean(false);
    final AtomicBoolean inter1Error = new AtomicBoolean(false);
    final AtomicBoolean inter2Error = new AtomicBoolean(false);
    final AtomicBoolean inter1After = new AtomicBoolean(false);
    final AtomicBoolean inter2After = new AtomicBoolean(false);
    final AtomicBoolean only2After = new AtomicBoolean(false);
    Interceptor interceptor1 = new Interceptor() {

        @Override
        public boolean beforeExecute(ForestRequest request) {
            inter1Before.set(true);
            return true;
        }

        @Override
        public void onSuccess(Object data, ForestRequest request, ForestResponse response) {
            inter1Success.set(true);
            count.incrementAndGet();
        }

        @Override
        public void onError(ForestRuntimeException ex, ForestRequest request, ForestResponse response) {
            inter1Error.set(true);
        }

        @Override
        public void afterExecute(ForestRequest request, ForestResponse response) {
            inter1After.set(true);
        }
    };
    Interceptor interceptor2 = new Interceptor() {

        @Override
        public boolean beforeExecute(ForestRequest request) {
            inter2Before.set(true);
            return true;
        }

        @Override
        public void onSuccess(Object data, ForestRequest request, ForestResponse response) {
            inter2Success.set(true);
            count.incrementAndGet();
        }

        @Override
        public void onError(ForestRuntimeException ex, ForestRequest request, ForestResponse response) {
            inter2Error.set(true);
        }

        @Override
        public void afterExecute(ForestRequest request, ForestResponse response) {
            inter2After.set(true);
            only2After.set(true);
        }
    };
    Interceptor interceptor3 = new Interceptor() {

        @Override
        public boolean beforeExecute(ForestRequest request) {
            inter3Before.set(true);
            return false;
        }

        @Override
        public void onSuccess(Object data, ForestRequest request, ForestResponse response) {
        }

        @Override
        public void onError(ForestRuntimeException ex, ForestRequest request, ForestResponse response) {
        }

        @Override
        public void afterExecute(ForestRequest request, ForestResponse response) {
        }
    };
    InterceptorChain chain = new InterceptorChain();
    chain.addInterceptor(interceptor1).addInterceptor(interceptor2);
    assertEquals(2, chain.getInterceptorSize());
    assertTrue(chain.beforeExecute(null));
    assertTrue(inter1Before.get());
    assertTrue(inter2Before.get());
    chain.addInterceptor(interceptor3);
    assertFalse(inter3Before.get());
    chain.onSuccess(null, null, null);
    assertTrue(inter1Success.get());
    assertTrue(inter2Success.get());
    assertEquals(2, count.get());
    chain.onError(null, null, null);
    assertTrue(inter1Error.get());
    assertTrue(inter2Error.get());
    chain.afterExecute(null, null);
    assertTrue(inter1After.get());
    assertTrue(inter2After.get());
    assertTrue(only2After.get());
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) InterceptorChain(com.dtflys.forest.interceptor.InterceptorChain) ForestResponse(com.dtflys.forest.http.ForestResponse) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ForestRuntimeException(com.dtflys.forest.exceptions.ForestRuntimeException) ForestRequest(com.dtflys.forest.http.ForestRequest) Interceptor(com.dtflys.forest.interceptor.Interceptor) Test(org.junit.Test)

Aggregations

ForestRuntimeException (com.dtflys.forest.exceptions.ForestRuntimeException)64 Test (org.junit.Test)14 Map (java.util.Map)9 ForestConfiguration (com.dtflys.forest.config.ForestConfiguration)7 MetaRequest (com.dtflys.forest.reflection.MetaRequest)6 ForestLogHandler (com.dtflys.forest.logging.ForestLogHandler)5 MappingParameter (com.dtflys.forest.mapping.MappingParameter)5 Method (java.lang.reflect.Method)5 Parameter (java.lang.reflect.Parameter)5 HashMap (java.util.HashMap)5 LinkedHashMap (java.util.LinkedHashMap)5 SSLKeyStore (com.dtflys.forest.ssl.SSLKeyStore)4 IOException (java.io.IOException)4 Annotation (java.lang.annotation.Annotation)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 MalformedURLException (java.net.MalformedURLException)4 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)4 ForestConverter (com.dtflys.forest.converter.ForestConverter)3 ForestRequest (com.dtflys.forest.http.ForestRequest)3 Interceptor (com.dtflys.forest.interceptor.Interceptor)3