Category Archives: JAVA

[Solved] Openfeign Error: error: Failed to parse Date value…

1 date conversion problem

1. Error reporting

error: Failed to parse Date value '2021-09-13 23:59:59': Cannot parse date "2021-09-13 23:59:59": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency?null))

2. solution

Add the annotation of date format deserialization on the field attribute @ jsonformat (pattern = "yyyy MM DD HH: mm: SS")

	/**
     * the end of time
     */
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private Date endDate;

MVN compile Error: [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin…

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project hello-world: Compilation failure: Compilation failure:
[ERROR] Source option 5 is no longer supported; use version 6 or higher.
[ERROR] Target option 1.5 is no longer supported. please use version 1.6 or higher.

Add the following attributes to pom.xml

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
 
 		<java.version>1.8</java.version>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
	</properties>

[Solved] JSP tag forwarding forword error: org.apache.jasper.JasperException

Error reporting type

org.apache.jasper.JasperException: /jsptag1.jsp (行.: [11], 列: [0]) Expect the "jsp:param" standard operation using the "name" and "value" attributes

Problem Description:

29-Aug-2021 18:08:39.881 严重 [http-nio-8080-exec-5] org.apache.catalina.core.StandardWrapperValve.invoke 在路径为/jsp的上下文中,Servlet[jsp]的Servlet.service()引发了具有根本原因的异常/jsptag1.jsp (行.: [11], 列: [0]) 使用“name”和“value”属性期望“jsp:param”标准操作
	org.apache.jasper.JasperException: /jsptag1.jsp (行.: [11], 列: [0]) 使用“name”和“value”属性期望“jsp:param”标准操作
		at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:41)
		at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:292)
		at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:98)
		at org.apache.jasper.compiler.Parser.parseParam(Parser.java:843)
		at org.apache.jasper.compiler.Parser.parseBody(Parser.java:1696)
		at org.apache.jasper.compiler.Parser.parseOptionalBody(Parser.java:1020)
		at org.apache.jasper.compiler.Parser.parseForward(Parser.java:884)
		at org.apache.jasper.compiler.Parser.parseStandardAction(Parser.java:1136)
		at org.apache.jasper.compiler.Parser.parseElements(Parser.java:1474)
		at org.apache.jasper.compiler.Parser.parse(Parser.java:144)
		at org.apache.jasper.compiler.ParserController.doParse(ParserController.java:244)
		at org.apache.jasper.compiler.ParserController.parse(ParserController.java:105)
		at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:206)
		at org.apache.jasper.compiler.Compiler.compile(Compiler.java:391)
		at org.apache.jasper.compiler.Compiler.compile(Compiler.java:367)
		at org.apache.jasper.compiler.Compiler.compile(Compiler.java:351)
		at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:605)
		at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:399)
		at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:379)
		at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:327)
		at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
		at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
		at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
		at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
		at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
		at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
		at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
		at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
		at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
		at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
		at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
		at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
		at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
		at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
		at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
		at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
		at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
		at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1726)
		at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
		at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
		at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
		at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
		at java.lang.Thread.run(Thread.java:748)

Solution:

Dynamically introduce or forward tags with spaces or comments in the middle

In addition to writing < jsp:param name="" value="" /> The sub tag will not report an error, and any other character will report an error.

Error:
<jsp:forward page="/jsptag2.jsp">
    <jsp:param name="username" value="root"></jsp:param>
    <jsp:param name="password" value="admin"></jsp:param>
</jsp:forward>



Error-Free:
<jsp:forward page="/jsptag2.jsp">
    <jsp:param name="username" value="root"></jsp:param>
    <jsp:param name="password" value="admin"></jsp:param>
</jsp:forward>

spring cloud 2020 gateway Error 503 [How to Solve]

POM file dependency

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <!--gateway fhadmin.org-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
        <version>3.0.2</version>
    </dependency>
    <!--spring-boot fhadmin.org-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

The related dependencies of Nacos I added in the parent component are as follows:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    <version>${nacos.version}</version>
</dependency>
<!--alibaba fhadmin.org-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    <version>${nacos.version}</version>
</dependency>

The version of Nacos is as follows:

<properties>
    <nacos.version>2021.1</nacos.version>
</properties>

The application.yml file of gateway is configured as follows:

#fhadmin.org
server:
  port: 9040

spring:
  application:
    name: gateway
  cloud:
    gateway:
      routes:
        - id: consumer
          uri: lb://consumer
          #          uri: http://localhost:9010
          predicates:
            - Path=/**
    nacos:
      discovery:
        server-addr: localhost:8848
        metadata:
          preserved.heart.beat.interval: 3 
          preserved.heart.beat.timeout: 6 
          preserved.ip.delete.timeout: 9 

When I pass URI: http://localhost:9010 When calling a service, it can be called, but when I use URI LB:// consumer, I cannot call the service, and an error 503 is reported

The solution is:
Add feign dependency.

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
        <version>3.0.2</version>
    </dependency>

    <!--fegin fhadmin.cn-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
        <version>3.0.2</version>
    </dependency>
    <!-- Feign Client for loadBalancing -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-loadbalancer</artifactId>
        <version>3.0.2</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Guess the reason: Nacos is compatible with feign. Feign integrates ribbon and realizes load balancing by default; Maybe Nacos is not compatible with the ribbon of springcloud gateway.

Mybatisenumtypehandler upgrade error of mybatis plus

Background

After I recently upgraded mybatis plus from 3.4.1 to 3.4.3.1, a series of errors occurred. The first error is that an attribute of the configuration file is red:

Prompt that there is a problem with the path of mybatisenumtypehandler. It is true that this class does not exist in the source package

Solution

Later, I queried the whole project by copying this type, and finally found this class. It turned out that it was moved to other places, and it can be moved to other packages at will. It’s too casual!

Original address:

default-enum-type-handler: com.baomidou.mybatisplus.extension.handlers.MybatisEnumTypeHandler

New address:

default-enum-type-handler: com.baomidou.mybatisplus.core.handlers.MybatisEnumTypeHandler

After modification, it will not be popular and solve the problem.

There is also an error:

A setusedeprecetedexecutor attribute in config became popular. It turned out that a plug-in was removed in the new version. You need to configure the latest version of paging plug-in

Screenshot of error reporting:

Solution:

Configure the latest version of paging plug-in on the official website:

Official website link: https://mp.baomidou.com/guide/page.html

Latest configuration:

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
        return interceptor;
    }

SpringBoot+Swagger Error: 403 Forbidden [How to Solve]

Springboot + swagger2 reports error 403 Forbidden

Error reporting reason

When creating a springboot project, if spring security dependencies are introduced into the POM file, after spring boot starter security, springboot will enable authentication by default, and also enable CSRF (Cross Site Request Forgery Prevention) verification by default. Therefore, the post request will be intercepted, that is, an error 403 Forbidden will be reported, and the get request will not be intercepted

Solution

Use ignore to ignore interception and manually turn off CSRF protection. Remember to turn on annotation @ enablewebsecurity manually

@EnableWebSecurity
public class WebSecurityCongfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable();
    }
}

Comparison method violates its general contract [How to Solve]

Error code:

//Error Codes
        Comparator<InspectReportListItemMpVo> comparator = new Comparator<InspectReportListItemMpVo>() {
            @Override
            public int compare(InspectReportListItemMpVo o1, InspectReportListItemMpVo o2) {
                try {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date reportTime_o1 = simpleDateFormat.parse(o1.getReportTime());
                    Date reportTime_o2 = simpleDateFormat.parse(o2.getReportTime());
//                    return reportTime_o1.compareTo(reportTime_o2);
                    return reportTime_o2.compareTo(reportTime_o1);
                } catch (ParseException e) {
                    e.printStackTrace();
                    return 1;
                }
            }
        };
        result.getItems().sort(comparator);

Screenshot of error reporting:

Comparison method violates its general contract

Problem-solving:

(not rigorous!) return 1 in the catch block; Change to return 0;

Supplement: rigorous writing

       Collections.sort(list, new Comparator<String>() {
            public int compare(String arg1, String arg2) {
                /**
                 * Modified
                 */
                if(StringUtils.isBlank(arg1) ) {
                    if(StringUtils.isBlank(arg2)) {
                        return 0;
                    }else {
                        return -1;
                    }
                    
                }else if(StringUtils.isBlank(arg2)){
                    return 1;
                }
                
                return arg1.compareTo(arg2);
            }
        });

Cause: timsort has a reflexivity check

Timport algorithm rules:
after JDK7, after implementing the comparable interface, the following three characteristics should be met:
1) Reflexivity: the comparison results of X and y are opposite to those of Y and X
2) transitivity: X > y,y> z. Then x > z。
3) symmetry: if x = y, the comparison results of X and Z are the same as those of Y and Z.

For the above error code, if you directly return 1, assume that a is empty, a.compareto (b) = 1, and b.compareto (a) = 1, which does not satisfy reflexivity

[Solved] XFire Error: org.codehaus.xfire.fault.XFireFault

When the client calls, the following errors are found in the package:

rg.codehaus.xfire.fault.XFireFault: There must be a method name element.
at org.codehaus.xfire.service.binding.RPCBinding.readMessage(RPCBinding.java:36)

There is a problem with the URL in the client code. Just remove ?wsdl

That is to say:

String url = "http://localhost:8080/xfire/services/AdvancedService?wsdl"; 

Amend to read:

String url = "http://localhost:8080/xfire/services/AdvancedService";

It’s OK.

Tomcat service startup error: cannot allocate memory [How to Solve]

Today, an environment hung up. First, restart it. It was found that it didn’t get up. The following error was reported:

....
Cannot allocate memory

1. Check whether the thread is full first:
# check the maximum allowed processes

[[email protected] ~] sysctl kernel.pid_max
kernel.pid_max = 32768

#View the number of processes in progress on this server

[[email protected] ~] ps -eLf | wc -l
1597

2. Compare the above two values. If the two values are similar, increase the number of allowed processes:
Modify PID_ Max value (custom)

[[email protected] ~] echo 999999 > /proc/sys/kernel/pid_max

Settings take effect permanently

[[email protected] ~] echo "kernel.pid_max=999999" >> /etc/sysctl.conf
[[email protected] ~] sysctl -p

3. If it is not, check the Tomcat log:

then modify the memory allocation:

1. [[email protected] ~] vim/etc/sysctl.conf 
vm.overcommit_memory=1
   [[email protected] ~] sysctl -p  

2.[[email protected] ~] echo 1 > /proc/sys/vm/overcommit_memory
  [[email protected] ~] sysctl –p  

3. [[email protected] ~] sysctl  vm.overcommit_memory=1 

Explanation:
memory allocation strategy in the kernel: overcommit_Memory
optional values: 0, 1, 2

0,: indicates that the kernel will check whether there is enough available memory for the process to use; If there is enough available memory, the memory application is allowed; Otherwise, the memory request fails and the error is returned to the application process
1: indicates that the kernel is allowed to allocate all physical memory regardless of the current memory state
2: indicates that the kernel allows to allocate more memory than the sum of all physical memory and swap space.

springboot sqlserver druid reward: validateConnection false

The exception information is as follows:

java.sql.SQLException: validateConnection false
	at com.alibaba.druid.pool.DruidAbstractDataSource.validateConnection(DruidAbstractDataSource.java:1418)
	at com.alibaba.druid.pool.DruidAbstractDataSource.createPhysicalConnection(DruidAbstractDataSource.java:1733)
	at com.alibaba.druid.pool.DruidDataSource$CreateConnectionThread.run(DruidDataSource.java:2801)
Caused by: java.lang.NullPointerException: null
	at com.alibaba.druid.wall.WallProvider.checkInternal(WallProvider.java:707)
	at com.alibaba.druid.wall.WallProvider.check(WallProvider.java:584)
	at com.alibaba.druid.wall.WallFilter.checkInternal(WallFilter.java:826)
	at com.alibaba.druid.wall.WallFilter.check(WallFilter.java:821)
	at com.alibaba.druid.wall.WallFilter.statement_execute(WallFilter.java:454)
	at com.alibaba.druid.filter.FilterChainImpl.statement_execute(FilterChainImpl.java:3008)
	at com.alibaba.druid.filter.FilterAdapter.statement_execute(FilterAdapter.java:2484)
	at com.alibaba.druid.filter.FilterEventAdapter.statement_execute(FilterEventAdapter.java:188)
	at com.alibaba.druid.filter.FilterChainImpl.statement_execute(FilterChainImpl.java:3008)
	at com.alibaba.druid.proxy.jdbc.StatementProxyImpl.execute(StatementProxyImpl.java:147)
	at com.alibaba.druid.pool.vendor.MSSQLValidConnectionChecker.isValidConnection(MSSQLValidConnectionChecker.java:50)
	at com.alibaba.druid.pool.DruidAbstractDataSource.validateConnection(DruidAbstractDataSource.java:1398)

Follow this method: com.alibaba.druid.pool.druidabstractdatasource.validateconnection

result = validConnectionChecker.isValidConnection(conn, validationQuery, validationQueryTimeout);

Find the exception of this line of code and enter this method

Find the method of this implementation class (because it is SQL server)

public boolean isValidConnection(final Connection c, String validateQuery, int validationQueryTimeout) throws Exception {
        if (c.isClosed()) {
            return false;
        }

        Statement stmt = null;

        try {
            stmt = c.createStatement();
            if (validationQueryTimeout > 0) {
                stmt.setQueryTimeout(validationQueryTimeout);
            }
            stmt.execute(validateQuery);
            return true;
        } catch (SQLException e) {
            throw e;
        } finally {
            JdbcUtils.close(stmt);
        }
    }

Finally, it is found that the method parameter validatequery is null, so a null pointer is reported. Let’s go back and see why it is null

protected volatile String                          validationQuery                           = DEFAULT_VALIDATION_QUERY;

Class defines that validationquery is equal to default_ VALIDATION_ Query, and default_ VALIDATION_ Query initialization is defined as null. In fact, this parameter comes from the springboot configuration file

Add the following configuration in the springboot data source configuration file:

druid:
                        validation-query: SELECT 1

Just do it!

PS, data source configuration:

driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
url: jdbc:sqlserver://IP:PORT;DatabaseName=database name
username: username
password: password
druid:
    validation-query: SELECT 1

[Solved] XxlJob Error: XxlJobFileAppender [101] -| Permission denied

1. Xxljob reports an error. Xxljobfileappender [101] – [permission denied

An error is reported in xxljob: xxljobfileappender [101] – [permission denied. The detailed error is as follows:

2021-09-15 09:28:45.686 |-ERROR [Thread-1565] com.xxl.job.core.log.XxlJobFileAppender [101] -| Permission denied
java.io.IOException: Permission denied
        at java.io.UnixFileSystem.createFileExclusively(Native Method)
        at java.io.File.createNewFile(File.java:1012)
        at com.xxl.job.core.log.XxlJobFileAppender.appendLog(XxlJobFileAppender.java:99)
        at com.xxl.job.core.context.XxlJobHelper.logDetail(XxlJobHelper.java:164)
        at com.xxl.job.core.context.XxlJobHelper.log(XxlJobHelper.java:118)
        at com.cuai.cbam.monitor.task.SystemOperateTask.checkSystemTask(SystemOperateTask.java:41)
        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 com.xxl.job.core.handler.impl.MethodJobHandler.execute(MethodJobHandler.java:31)
        at com.xxl.job.core.thread.JobThread.run(JobThread.java:163)

2. Positioning problem

After analyzing the log, you can find that it is normal to use logback to output the log, but use * * xxljobhelper.log (“…”)** When an error is reported, check the relevant configuration of xxljob and find a logpath parameter. Combined with the error, it is speculated that the server does not have the configured logpath path or the current operating user does not have the operation permission of the logpath path

3. Problem solving

Grant the logpath path the permission that the current user can operate, and then restart the application. It is found that the program is normal. So far, the problem has been solved.