1
votes

The following is the error message

java.lang.IllegalStateException: Failed to load ApplicationContext

at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125) at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108) at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190) at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'wokerLogController': Unsatisfied dependency expressed through field 'client'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'client' defined in class path resource [com/aurora/backend/config/ESConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.elasticsearch.client.Client]: Factory method 'client' threw exception; nested exception is java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:127) at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99) at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117) ... 24 more

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'client' defined in class path resource [com/aurora/backend/config/ESConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.elasticsearch.client.Client]: Factory method 'client' threw exception; nested exception is java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4] at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627) at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1288) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1244) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1164) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ... 42 more

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.elasticsearch.client.Client]: Factory method 'client' threw exception; nested exception is java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4] at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ... 55 more Caused by: java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4] at io.netty.util.NettyRuntime$AvailableProcessorsHolder.setAvailableProcessors(NettyRuntime.java:51) at io.netty.util.NettyRuntime.setAvailableProcessors(NettyRuntime.java:87) at org.elasticsearch.transport.netty4.Netty4Utils.setAvailableProcessors(Netty4Utils.java:83) at org.elasticsearch.transport.netty4.Netty4Transport.(Netty4Transport.java:112) at org.elasticsearch.transport.Netty4Plugin.lambda$getTransports$0(Netty4Plugin.java:86) at org.elasticsearch.client.transport.TransportClient.buildTemplate(TransportClient.java:189) at org.elasticsearch.client.transport.TransportClient.(TransportClient.java:283) at org.elasticsearch.transport.client.PreBuiltTransportClient.(PreBuiltTransportClient.java:128) at org.elasticsearch.transport.client.PreBuiltTransportClient.(PreBuiltTransportClient.java:114) at org.elasticsearch.transport.client.PreBuiltTransportClient.(PreBuiltTransportClient.java:104) at com.aurora.backend.config.ESConfig.client(ESConfig.java:45) at com.aurora.backend.config.ESConfig$$EnhancerBySpringCGLIB$$d0b29c5a.CGLIB$client$0() at com.aurora.backend.config.ESConfig$$EnhancerBySpringCGLIB$$d0b29c5a$$FastClassBySpringCGLIB$$93c49e6a.invoke() at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) at com.aurora.backend.config.ESConfig$$EnhancerBySpringCGLIB$$d0b29c5a.client() at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ... 56 more

A springboot project that uses elasticSearch, mysql, redis, etc. Google has a lot, but he is just a new spingboot. The online stuff doesn't work. I don't know how to change it.

application-local.yml

server:
  port: 8000
  servlet:
    context-path: /api/v3
  error:
    whitelabel:
      enabled: false

spring:
  http:
    multipart:

    encoding:
      charset: UTF-8
      force: true
      enabled: true


  datasource:
    url: jdbc:mysql://localhost:3306/aurora?useUnicode=yes&characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
    username: root
    password: 123456789
    driverClassName: com.mysql.jdbc.Driver
  jpa:
    database-platform: org.hibernate.dialect.MySQL57Dialect
    generate-ddl: true
    show-sql: true
  liquibase:
    change-log: classpath:db/db.master.xml
  data:
    elasticsearch:
      cluster-name: elasticsearch
      cluster-nodes: 127.0.0.1:9300
      repositories:
        enabled: true
  redis:
    host: 127.0.0.1
    port: 6379
    password:  
    database: 0
    lettuce:
      pool:
        max-active: 8 
        max-wait: -1 
        max-idle: 8 
        min-idle: 0 
        timeout: 0 
  servlet:
    multipart:
      max-file-size: 200MB # Max file size.
      max-request-size: 215MB # Max Request Size
      enabled: true

logging:
  pattern:
    file: "%d{yy-MM-dd HH:mm:ss.SSS} [%thread] %-5level : %X{user} %logger{36}.%M - %msg%n"
    console: "%d{yy-MM-dd HH:mm:ss.SSS} [%thread] %-5level : %X{user} %logger{36}.%M - %msg%n"
  level:
    org.springframework.web: DEBUG
    guru.springframework.controllers: DEBUG
    org.hibernate: DEBUG

app:
  wechat:
    notification: true
  design:
    root-path: /home/cloudeda/Aurora/UploadData
  jwt:
    base64-secret: NjkwNjU5ZTg0YmYxZmE0ZDJmYmFlNmMwMGNjMjJjZTc4MjFiZjkyNTk3N2IyN2M5OGQyNzg3ZTExN2M1MGYzMzNkNTg2MzMwODgzZTE3YzIwMDdhMTg1Y2M4ZWFmYmFjOGEyYWNiOTU3ZGYzNTY3NDdmMzg3ZWNjNjRmNjdjNzI=
    # Token is valid 24 hours
    token-validity-in-seconds: 86400
    token-validity-in-seconds-for-remember-me: 2592000
  id:
    data-center: 1
    machine: 1


  server:
    broker: tcp://localhost:5555
  flask:
    ibis-parser-url: http://localhost:5050/api/v3/server/parse-ibis-model
    generate-report-url: http://localhost:5050/api/v3/server/report

security:
  user:
    name: aurora
    password: aurora-monitor-password

elasticsearch:
  host: 127.0.0.1
  port: 9300
  cluster:
    name: elasticsearch

Should be related to the configuration of the ES

ESConfig.java

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Configuration
public class ESConfig {

    @Value("${elasticsearch.host:127.0.0.1}")
    private String host;

    @Value("${elasticsearch.port:9300}")
    private int port;

    @Value("${elasticsearch.cluster.name:elasticsearch}")
    private String clusterName;

    public String getHost() {
        return this.host;
    }

    public int getPort() {
        return this.port;
    }

    @Bean
    public Client client() {
        TransportClient client = null;

        Settings settings = Settings.builder()
            .put("cluster.name", clusterName)
            .put("client.transport.ignore_cluster_name", false)
            .build();

        try {
            client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName(host), port));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        return client;
    }
}

Controller

import com.aurora.backend.beans.ResultBean;
import com.aurora.backend.beans.WorkerLogBean;
import com.aurora.backend.param.SearchSimulationLogParam;
import com.aurora.backend.security.CurrentUser;
import com.aurora.backend.security.UserPrincipal;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/es")
@Slf4j
public class WokerLogController {

    @Autowired Client client;

    @PostMapping(value = "/simulation/log")
    public ResultBean getSimulationLog(
        @CurrentUser UserPrincipal user,
        @RequestBody SearchSimulationLogParam param
    ) {

        SearchResponse response = client.prepareSearch("logstash-worker")
            .setTypes("doc")
            .setSearchType(SearchType.QUERY_THEN_FETCH)
            .setQuery(QueryBuilders.matchQuery("logtype", 1))
            .setQuery(QueryBuilders.matchQuery("token", param.getToken()))
            .setPostFilter(
                QueryBuilders.rangeQuery("@timestamp")
                    .from(param.getStartTime()).to(param.getEndTime()))
            .get();

        SearchHit[] hits = response.getHits().getHits();
        List<WorkerLogBean> mapList = new ArrayList<>();
        for (int i = 0; i < hits.length; i++) {
            WorkerLogBean logBean = new WorkerLogBean();
            logBean.setId(hits[i].getId());
            logBean.setLog(hits[i].getSourceAsMap().get("log").toString());
            logBean.setMessage(hits[i].getSourceAsMap().get("message").toString());
            mapList.add(logBean);
        }
        return new ResultBean(mapList);
    }
}
2

2 Answers

0
votes

This is where your exception is:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'wokerLogController': Unsatisfied dependency expressed through field 'client'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'client' defined in class path resource

and

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'client' defined in class path resource [com/aurora/backend/config/ESConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.elasticsearch.client.Client]: Factory method 'client' threw exception; nested exception is java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4] at

and

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.elasticsearch.client.Client]: Factory method 'client' threw exception; nested exception is java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4] at

This problem has been reported in this link. Haven't faced this problem with elastic search. The following might solve your problem but this might be webserver dependent. Check this.

@Component
public class ElasticSearchConfiguration implements InitializingBean {
    static {
        System.setProperty("es.set.netty.runtime.available.processors", "false");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println(System.getProperty("es.set.netty.runtime.available.processors"));
    }
}
0
votes

It could be a dependency issue. Anyway, if you are using spring boot 2.., go with rest client instead of transport client which is deprecated.

Use the following code: build.gradle:

compile "com.fasterxml.jackson.datatype:jackson-datatype-hppc"
    compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310"
    compile "com.fasterxml.jackson.datatype:jackson-datatype-hibernate5"
    compile "com.fasterxml.jackson.core:jackson-annotations"
    compile "com.fasterxml.jackson.core:jackson-databind"
    compile "com.fasterxml.jackson.module:jackson-module-afterburner"
    runtime group: 'com.fasterxml.jackson.module', name: 'jackson-modules-java8', version: '2.9.8', ext: 'pom'
    // https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-parameter-names
compile group: 'com.fasterxml.jackson.module', name: 'jackson-module-parameter-names', version: '2.9.8'

compile 'org.elasticsearch:elasticsearch'
    compile 'org.elasticsearch.client:transport'
    compile 'org.elasticsearch.client:elasticsearch-rest-client'
    compile 'org.elasticsearch.client:elasticsearch-rest-high-level-client'

    compile 'org.springframework.data:spring-data-elasticsearch'

Versions: Should be Compatible

org.elasticsearch.client:elasticsearch-rest-client -> 6.4.3 (*)
org.elasticsearch.client:elasticsearch-rest-high-level-client -> 6.4.3
org.elasticsearch:elasticsearch -> 6.4.3
org.springframework.data:spring-data-elasticsearch -> 3.1.4.RELEASE
com.fasterxml.jackson.datatype:jackson-datatype-hppc -> 2.9.8
com.fasterxml.jackson.core:jackson-core:2.9.8
com.fasterxml.jackson.core:jackson-databind:2.9.8 (*)
com.fasterxml.jackson.datatype:jackson-datatype-jsr310 -> 2.9.8 (*)
com.fasterxml.jackson.datatype:jackson-datatype-hibernate5 -> 2.9.8
com.fasterxml.jackson.core:jackson-annotations -> 2.9.0
com.fasterxml.jackson.module:jackson-module-afterburner -> 2.9.8
com.fasterxml.jackson.module:jackson-module-parameter-names:2.9.8 (*)
com.fasterxml.jackson.module:jackson-modules-java8:2.9.8

ElasticSearchConfiguration:

RestHighLevelClient client = null; 

@Bean
public RestHighLevelClient buildClient() {
    return new RestHighLevelClient(
            RestClient.builder(
                    new HttpHost("localhost", 9200, "http"),
                    new HttpHost("localhost", 9201, "http")));
}


@Bean
@Primary
public ElasticsearchOperations elasticsearchTemplate() {
    return new ElasticsearchTemplate((Client) buildClient(), new CustomEntityMapper(new ObjectMapper()));
}


public class CustomEntityMapper implements EntityMapper {

    private ObjectMapper objectMapper;

    public CustomEntityMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        //objectMapper.registerModule(new JavaTimeModule());
        JavaTimeModule javaTimeModule=new JavaTimeModule();
        // Hack time module to allow 'Z' at the end of string (i.e. javascript json's) 
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ISO_DATE_TIME));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ISO_DATE));
        objectMapper.registerModule(javaTimeModule);

        objectMapper.findAndRegisterModules();
    }

    @Override
    public String mapToString(Object object) throws IOException {
        return objectMapper.writeValueAsString(object);
    }

    @Override
    public <T> T mapToObject(String source, Class<T> clazz) throws IOException {
        return objectMapper.readValue(source, clazz);
    }
}