Tag Archives: java

[Solved] IDEA Start Maven Project Error: “Error starting ApplicationContext. To display the conditions report …”

When IDEA starts a maven project, it fails to start and displays an error reporting:

Error starting ApplicationContext. To display the conditions report re-run your application with ‘debug’ enabled.
2021-12-22 09:21:42.183 ERROR 14964 — [           main] o.s.b.d.LoggingFailureAnalysisReporter   :
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: ‘url’ attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class

Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (the profiles local are currently active).

Cause:
The datasource related package environment is referenced, but no related configuration is performed

Solution:
1, start the class to add automatic configuration parameters: (exclude = {DataSourceAutoConfiguration.class})

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class ApiserviceApplication {

    public static void main(final String[] args) {
        SpringApplication.run(ApiserviceApplication.class, args);
    }
}

2. If the code does not use the relevant package environment, the relevant Maven package can be deleted

<!--        <dependency>-->
<!--            <groupId>org.springframework.boot</groupId>-->
<!--            <artifactId>spring-boot-starter-data-cassandra-jpa</artifactId>-->
<!--        </dependency>-->

3. If used, add relevant configurations

[Solved] Error running ‘TomEE 10.0.121‘: The selected directory is not a TomEE hom

Today, I watched the video of Lao Du’s servlet and tried to start the Tomcat server after typing the code. I found this: error running ‘tomee 10.0.121 ‘: the selected directory is not a tomee Hom error.

Then I didn’t look at the error carefully. Subconsciously, I thought my Tomcat path was wrong. I looked it up and found that there was no problem

Finally, take a closer look at the good guy Tomcat created to tomcatee. No wonder it can’t be started.

Solution:

Just change back to normal Tomcat

Finally, click the servlet according to the old Du code

[Solved] docker Start jar package and Set JVM parameter Error

Error Messages:
Unrecognized option: -server -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=256m -Xms512m -Xmx1024m -Xmn512m -Xss256k -XX:SurvivorRatio=8 -XX:+UseConcMarkSweepGC -Dtask=true
Error: Could not create the Java Virtual Machine.
Background:
Setting JVM parameters and then using docker file to start jar package reported an error.
Solution:
Use the ENTRYPOINT exec command.
ENV jvm_opts=”-server -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=256m -Xms512m -Xmx1024m -Xmn512m -Xss256k -XX:S
urvivorRatio=8 -XX:+UseConcMarkSweepGC -Dtask=true”

ENTRYPOINT exec java -jar $jvm_opts trade-chat.jar $app_arg

[Solved] Springboot uses redis to add LocaldateTime Java 8 error

To store an object in redis, you need to serialize the object. If a field is of localdatetime type, an error will appear

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling (through reference chain: com.gd.base.vo.redis.RedisSysUser["Corresponding fields"])

The program needs to deserialize the data in redis. The deserializer I use here is the following:

@Configuration
@EnableCaching//Allow us to use the cache
public class RedisConfig {
    /**
     * Cache expiration time (seconds)
     */
    public static final long CACHE_EXPIRE_SECEND = 3600 * 2;

    @Bean // At this point, load our redisTemplate into the context of our spring, applicationContext
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        //1. Initialize a redisTemplate
        RedisTemplate<String,Object> redisTemplate=new RedisTemplate<String,Object>();
        //2. Serial words (generally used for key values)
        RedisSerializer<String> redisSerializer=new StringRedisSerializer();
        //3. Introduce the json string conversion class (generally used for value processing)
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper=new ObjectMapper();
        //3.1 Set the access rights of objectMapper
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        //3.2 Specify the serialized input type, that is, store the data in the database to the redis cache according to certain types.
        </objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);// Recently upgraded SpringBoot, found that enableDefaultTyping method expired. You can use the following method instead
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As. WRAPPER_ARRAY);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        //4. Create the link
        redisTemplate.setConnectionFactory(factory);
        //4.1 redis key value serialization
        redisTemplate.setKeySerializer(redisSerializer);
        //4.2 value serialization, because most of our values are converted through objects, so use jackson2JsonRedisSerializer
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        // 4.3 Serialization of value, serialization of hashmap
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        return redisTemplate;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory){
        // 1. Serial words (generally used for key values)
        RedisSerializer<String> redisSerializer=new StringRedisSerializer();
        //2. Introduce the json string conversion class (generally used for value processing)
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper=new ObjectMapper();
        //2.1 Set the access rights of objectMapper
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        //2.2 Specify the serialized input type, that is, store the data in the database to the redis cache according to a certain type.
        </objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);// Recently upgraded SpringBoot, found that enableDefaultTyping method expired. You can use the following method instead
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As. WRAPPER_ARRAY);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        //3. Serialization configuration, garbled problem solving and timeliness of our cache
        RedisCacheConfiguration config=RedisCacheConfiguration.defaultCacheConfig().
                entryTtl(Duration.ofSeconds(CACHE_EXPIRE_SECEND)). // Cache timeliness setting
                serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)). //key serialization
                serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)). //value serialization
                disableCachingNullValues();//null values are not stored in the cache
        //4. Create the cacheManager link and set the properties
        RedisCacheManager cacheManager= RedisCacheManager.builder(factory).cacheDefaults(config).build();
        return cacheManager;
    }

}

Processing error reports:
① add comments to the corresponding fields

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonSerialize(using = LocalDateTimeSerializer.class)

The error report is gone

IDEA pom.xml dependency version error [How to Solve]

Self problem solving record, tossed all morning and finally solved:

I tried other solutions first, but there was no response. You can still try:

1. Modify the Maven version number, download the old version again, configure the environment variables, and install cleanLastUpdated.bat small script to clear the package that has not been downloaded successfully/completely. It is useless

Share this script:

Copy to Notepad and save the file as cleanLastUpdated.bat, select the file format as all file formats.

set REPOSITORY_PATH=Absolute path to your own local repository
rem is searching...
for /f "delims=" %%i in ('dir /b /s "%REPOSITORY_PATH%\*lastUpdated*"') do (
    del /s /q %%i
)
rem search completed
pause

2. Re-check other configurations in settings \ Maven and check these two again. It’s useless

3. Final solution

I went to the local warehouse and found that the jar package had been downloaded, but it was inconsistent with the version number that my pom.xml relied on, so the modification was over.

[Solved] Spring upload file Error: Multipartfile Transferto() reported an error FileNotFoundException

When uploading files, use multipartfile Transferto() saves the file to the local path:

report errors:

java.io.IOException: java.io.FileNotFoundException: C:\Users\XXXXX\AppData\Local\Temp\tomcat. 8350081478984499756.8080\work\Tomcat\localhost\ROOT\app\file\xxxx. Xlsx (the system cannot find the specified path.)

    @Override
    public String store(MultipartFile file, String fileName) throws IOException {

        String destPath "/app/file/";
        File filePath = new File(destPath);
        File dest = new File(filePath, fileName);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        try {
            file.transferTo(dest);
            log.info("file save success");
        } catch (IOException e) {
            log.error("File upload Error: ", e);
            throw e;
        }
        return dest.getCanonicalPath();
    }

Cause analysis:

file. When the transferto method is called, it is judged that if it is a relative path, the temp directory is used as the parent directory
so it is saved in the temporary work directory of Tomcat.

Solution:

Use absolute path: filepath.getAbsolutePath()

    @Override
    public String store(MultipartFile file, String fileName) throws IOException {

        String destPath "/app/file/";
        File filePath = new File(destPath);
        
        // Convert to absolute path
        File dest = new File(filePath.getAbsolutePath(), fileName);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        try {
            file.transferTo(dest);
            log.info("file save success");
        } catch (IOException e) {
            log.error("File upload Error: ", e);
            throw e;
        }
        return dest.getCanonicalPath();
    }

Supplement:

You can also file Getbytes() gets the byte array, or file Getinputstream() performs stream data operation and writes it to disk.

Access to uploaded files

spring:
	resources:
    	static-locations: file:/app/file/  #Access external system resources and map the files in this directory to the system

or

import java.io.File;
import java.util.concurrent.TimeUnit;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String absolutePath = new File("/app/file/").getAbsolutePath();
        
        registry.addResourceHandler("/upload/**") // External Access Addresses
                .addResourceLocations("file:" + absolutePath)// SpringBoot needs to add the file protocol prefix
                .setCacheControl(CacheControl.maxAge(30, TimeUnit.MINUTES));// set the browser cache
    }
}

OpenFeignClient Use Object to Receive text/plain Type Return Error

report errors

Could not extract response: no suitable HttpMessageConverter found for
response type [classxxxx] and content type [text/plain]

reason

The return type content type is not application/JSON, but text/plain. It cannot be deserialized into object type, as shown in the figure

spring cloud openfeign essentially uses okhttpclient for request. If it is text/plain, it will be treated as text and cannot be deserialized automatically like JSON string, The following is my feinclient:

in this case, it is necessary to do compatibility processing for the return of this content type
add the jackson2httpmessageconverter conversion class, and increase the compatibility of text/plain and text/HTML return types

import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href="mailto:[email protected]">Tino.Tang</a>
 * @version ${project.version} - 2021/12/9
 */
public class MyJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {

  public LokiJackson2HttpMessageConverter() {
    List<MediaType> mediaTypes = new ArrayList<>();
    mediaTypes.add(MediaType.TEXT_PLAIN);
    mediaTypes.add(MediaType.TEXT_HTML);
    setSupportedMediaTypes(mediaTypes);
  }
}

Add openfeign custom configuration and inject Decoder Bean.

import feign.Logger;
import feign.codec.Decoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author <a href="mailto:[email protected]">Tino.Tang</a>
 * @version ${project.version} - 2021/11/29
 */
@Configuration
public class OpenFeignLogConfig {

  @Bean
  public Logger.Level feignLoggerLeave() {
    return Logger.Level.FULL;
  }

  @Bean
  public Decoder feignDecoder() {
    LokiJackson2HttpMessageConverter converter = new LokiJackson2HttpMessageConverter();
    ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(converter);
    return new SpringDecoder(objectFactory);
  }
}```

After processing, the call to the feign client will no longer report errors, regardless of whether the type is application/json or text/plain, it can be correctly deserialized to Object.

[Solved] tomcat Startup Error: java.lang.SecurityException: Invalid signature file digest for Manifest main attributes

Error: invalid signature file digest for manifest main attributes

The project runs normally on the local machine, but it cannot be started when deployed to the Tomcat of the server. The following error is reported:

Caused by: java.lang.SecurityException: Invalid signature file digest for Manifest main attributes
        at sun.security.util.SignatureFileVerifier.processImpl(SignatureFileVerifier.java:239) [:1.6.0_30]
        at sun.security.util.SignatureFileVerifier.process(SignatureFileVerifier.java:193) [:1.6.0_30]
        at java.util.jar.JarVerifier.processEntry(JarVerifier.java:296) [:1.6.0_30]
        at java.util.jar.JarVerifier.update(JarVerifier.java:207) [:1.6.0_30]
        at java.util.jar.JarFile.initializeVerifier(JarFile.java:342) [:1.6.0_30]
        at java.util.jar.JarFile.getInputStream(JarFile.java:410) [:1.6.0_30]
        at org.jboss.vfs.spi.JavaZipFileSystem.getFile(JavaZipFileSystem.java:159) [jboss-vfs.jar:3.0.0.GA]
        at org.jboss.vfs.VirtualFile.getPhysicalFile(VirtualFile.java:262) [jboss-vfs.jar:3.0.0.GA]
        at org.jboss.web.deployers.AbstractWarDeployer$1.visit(AbstractWarDeployer.java:853) [:6.0.0.Final]
        at org.jboss.vfs.VirtualFile.visit(VirtualFile.java:408) [jboss-vfs.jar:3.0.0.GA]
        at org.jboss.vfs.VirtualFile.visit(VirtualFile.java:410) [jboss-vfs.jar:3.0.0.GA]
        at org.jboss.vfs.VirtualFile.visit(VirtualFile.java:410) [jboss-vfs.jar:3.0.0.GA]
        at org.jboss.vfs.VirtualFile.visit(VirtualFile.java:410) [jboss-vfs.jar:3.0.0.GA]
        at org.jboss.vfs.VirtualFile.visit(VirtualFile.java:396) [jboss-vfs.jar:3.0.0.GA]
        at org.jboss.web.deployers.AbstractWarDeployer.getExplodedWarUrl(AbstractWarDeployer.java:866) [:6.0.0.Final]
        at org.jboss.web.deployers.AbstractWarDeployer.deploy(AbstractWarDeployer.java:400) [:6.0.0.Final]
        ... 47 more

Almost all the Internet queries have problems. There are files in the meta-inf folder of the packaged jar or war.JBoss is trying to process these files or doesn’t want to process them there.

However, I found that my meta-inf folder was empty and there was no * RSA,*.DSA,*.SF and other documents are hard to understand
I have also tried to repackage and replace the Tomcat version, but this problem has not been solved.

Finally, I thought that the project is divided into modules. Are there these files in the jar package generated by the referenced submodule? Finally, I checked one by one and finally found the problem:
there are these * RSA,*. DSA,*. SF files

remove these files from the jar package:

zip -d <jar file name>.jar META-INF/*.RSA META-INF/*.DSA META-INF/*.SF

But this is a temporary solution but not a permanent solution. The problem will still occur in the next packaging. Finally, go to the pom.xml file to exclude META-INF/*.SF and other files

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-shade-plugin</artifactId>
	<version>3.1.1</version>
	<executions>
		<execution>
			<phase>package</phase>
			<goals>
				<goal>shade</goal>
			</goals>
			<configuration>
				<filters>
					<filter>
						<artifact>*:*</artifact>
						<excludes>
							<!-- Exclude the following files to prevent verification errors when the program is started  -->
							<exclude>META-INF/*.SF</exclude>
							<exclude>META-INF/*.DSA</exclude>
							<exclude>META-INF/*.RSA</exclude>
						</excludes>
					</filter>
				</filters>
			</configuration>
		</execution>
	</executions>
</plugin>

[Solved] IDEA globally replace yml Error: you have entered malformed replacement

Problem Description: because the YML configuration file needs to be replaced uniformly in the microservice project, but the replacement string contains’ $’, the editor reports an illegal format error.

Solution:

Just transfer the ‘$’ symbol and add the escape character ‘\’ in front of it: http://nacos-headless \.\${info.namespace}\.svc\.cluster\.local:8848

How to Solve nacos Startup Error and Connect to MYSQL

Error reason for Nacos startup: the default configuration of Nacos is cluster startup, which can be modified to stand-alone startup (after Nacos 1.3.2, the default mode of Nacos is cluster mode).

The Nacos directory structure is as follows (the version of Nacos I use is 2.0.3):

1.open the bin directory and modify startup.com script

2.connects to MySQL, executes the SQL statement

opens the conf folder, creates a Nacos database, executes the following script

after execution, the results are as follows

3.opens the conf folder, modifies the configuration information

finds the following configuration in the conf folder and modifies the marked configuration items

test access 127.0 0.1:8848/Nacos account/password: Nacos/Nacos successfully opened the following page