Tag Archives: java

Byte 1 of UTF-8 sequence of error creating document instance. And bytes is invalid

Records of mybatis related bugs

For mybatis learning, I encountered many inexplicable bugs from the beginning! After Baidu and barrage, they didn’t solve it. Later, they changed inexplicably, but they were right. First look at the bug:

"D:\SoftWare\Idea\IntelliJ IDEA 2020.3.2\jbr\bin\java.exe" -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:D:\SoftWare\Idea\IntelliJ IDEA 2020.3.2\lib\idea_rt.jar=54216:D:\SoftWare\Idea\IntelliJ IDEA 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath "D:\SoftWare\Idea\IntelliJ IDEA 2020.3.2\lib\idea_rt.jar;D:\SoftWare\Idea\IntelliJ IDEA 2020.3.2\plugins\junit\lib\junit5-rt.jar;D:\SoftWare\Idea\IntelliJ IDEA 2020.3.2\plugins\junit\lib\junit-rt.jar;D:\Desktop\MyBatis02\mybatis-02\target\test-classes;D:\Desktop\MyBatis02\mybatis-02\target\classes;D:\Environment\apache-maven-3.8.1\maven-repo\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar;D:\Environment\apache-maven-3.8.1\maven-repo\org\mybatis\mybatis\3.5.2\mybatis-3.5.2.jar;D:\Environment\apache-maven-3.8.1\maven-repo\junit\junit\4.13.2\junit-4.13.2.jar;D:\Environment\apache-maven-3.8.1\maven-repo\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar" com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 com.lxz.dao.UserDaoTest,getUserLike

java.lang.ExceptionInInitializerError
	at com.lxz.dao.UserDaoTest.getUserLike(UserDaoTest.java:14)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
	at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
	at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
	at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
	at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
Caused by: org.apache.ibatis.exceptions.PersistenceException: 
### Error building SqlSession.
### Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance.  Cause: org.xml.sax.SAXParseException; lineNumber: 11; columnNumber: 9; 1 字节的 UTF-8 序列的字节 1 无效。
	at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
	at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:80)
	at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:64)
	at com.lxz.utils.MybatisUtils.<clinit>(MybatisUtils.java:21)
	... 26 more
Caused by: org.apache.ibatis.builder.BuilderException: Error creating document instance.  Cause: org.xml.sax.SAXParseException; lineNumber: 11; columnNumber: 9; 1 字节的 UTF-8 序列的字节 1 无效。
	at org.apache.ibatis.parsing.XPathParser.createDocument(XPathParser.java:260)
	at org.apache.ibatis.parsing.XPathParser.<init>(XPathParser.java:126)
	at org.apache.ibatis.builder.xml.XMLConfigBuilder.<init>(XMLConfigBuilder.java:81)
	at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:77)
	... 28 more
Caused by: org.xml.sax.SAXParseException; lineNumber: 11; columnNumber: 9; 1 字节的 UTF-8 序列的字节 1 无效。
	at java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:204)
	at java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:178)
	at java.xml/com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:400)
	at java.xml/com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:306)
	at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3085)
	at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:605)
	at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:534)
	at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:888)
	at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:824)
	at java.xml/com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
	at java.xml/com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:246)
	at java.xml/com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339)
	at org.apache.ibatis.parsing.XPathParser.createDocument(XPathParser.java:258)
	... 31 more
Caused by: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: 1 字节的 UTF-8 序列的字节 1 无效。
	at java.xml/com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.invalidByte(UTF8Reader.java:702)
	at java.xml/com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.read(UTF8Reader.java:568)
	at java.xml/com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.load(XMLEntityScanner.java:1904)
	at java.xml/com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.scanData(XMLEntityScanner.java:1377)
	at java.xml/com.sun.org.apache.xerces.internal.impl.XMLScanner.scanComment(XMLScanner.java:800)
	at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanComment(XMLDocumentFragmentScannerImpl.java:1069)
	at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2898)
	... 39 more


Process finished with exit code -1

First, for reading bugs. In idea, you should read backwards, from bottom to top. Just look at the line of cause by. For the above error reports, * * * * just remove the Chinese comments in the interface mapping file and configuration file of mybatis, or change the encoding method to utf8.

About priority of. Properties file (supplementary)

We knew before that the reference configuration file can be realized through the properties attribute: the reference configuration file code given in the official mybatis document is:

	<!--Introduction of external configuration files-->
    <properties resource="db.properties">
        <property name="username" value="root"/>
        <property name="pwd" value="123123"/>
    </properties>

We can also write the code to import the configuration file as:

<properties resource="db.properties"/>

The premise of this writing is that our resource file contains the name and PWD attributes! When we use the official method of importing the configuration file, but write the name and PWD attributes in the external configuration file, idea will automatically execute the code based on the external file as the standard.

[Solved] cannot call sendError() after the response has been committed

framework: springboot+IDEA+spring security oauth2
background: user login to get token, username or password authentication failure, the execution of onAuthenticationFailure method, has returned the normal error code and error message, but the console still throws an exception, the error message is as follows.

2021-09-12 07:16:25.490  WARN 964 — [nio-8090-exec-1] d.c.h.CustomAuthenticationFailureHandler : Authentication failed, the return message is: {“code”:1100, “info”: “User does not exist.”}
2021-09-12 07:16:25.500 ERROR 964 — [nio-8090-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet]      : Servlet.service() for servlet [dispatcherServlet] in context with path [/api/sso] threw exceptionjava.lang.IllegalStateException: Cannot call sendError() after the response has been committed
at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:456) ~[tomcat-embed-core-9.0.52.jar:9.0.52]
at javax.servlet.http.HttpServletResponseWrapper.sendError(HttpServletResponseWrapper.java:120) ~[tomcat-embed-core-9.0.52.jar:4.0.FR]
at javax.servlet.http.HttpServletResponseWrapper.sendError(HttpServletResponseWrapper.java:120) ~[tomcat-embed-core-9.0.52.jar:4.0.FR]
at org.springframework.security.web.util.OnCommittedResponseWrapper.sendError(OnCommittedResponseWrapper.java:126) ~[spring-security-web-5.5.2.jar:5.5.2]
at org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler.onAuthenticationFailure(SimpleUrlAuthenticationFailureHandler.java:86) ~[spring-security-web-5.5.2.jar:5.5.2]
at com.datong.liran.datongssoserver.config.handle.CustomAuthenticationFailureHandler.onAuthenticationFailure(CustomAuthenticationFailureHandler.java:39) ~[classes/:na]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.unsuccessfulAuthentication(AbstractAuthenticationProcessingFilter.java:342) ~[spring-security-web-5.5.2.jar:5.5.2]

The error code and error message have been returned normally, but the console still reports an error, not the result I want, so what should I do? The custom exception handling code looks like this.

@Component("CustomAuthenticationFailureHandler")
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.reset();
//        PrintWriter printWriter = httpServletResponse.getWriter();
        OutputStream out = response.getOutputStream();
        response.setContentType("application/json;charset=UTF-8");
        Result result = Result.error(1100,exception.getMessage(),null);
        String rspBodyStr = JSONObject.toJSONString(result);
        logger.warn("The authentication fails and the return message is:"+rspBodyStr);
        out.write(rspBodyStr.getBytes(StandardCharsets.UTF_8));
        out.close();
        super.onAuthenticationFailure(request,response,exception);
    }
}

Cannot call senderror() after the response has been committed.

Analysis: according to the error log, it is preliminarily judged that it should be repeated submission or repeated return, but only response is involved here, so you can only go to the parent class (onauthenticationfailure). Open it and have a look. The code is as follows.

public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        if (this.defaultFailureUrl == null) {
            if (this.logger.isTraceEnabled()) {
                this.logger.trace("Sending 401 Unauthorized error since no failure URL is set");
            } else {
                this.logger.debug("Sending 401 Unauthorized error");
            }

            response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
        } else {
            this.saveException(request, exception);
            if (this.forwardToDestination) {
                this.logger.debug("Forwarding to " + this.defaultFailureUrl);
                request.getRequestDispatcher(this.defaultFailureUrl).forward(request, response);
            } else {
                this.redirectStrategy.sendRedirect(request, response, this.defaultFailureUrl);
            }

        }
    }

Obviously, when the defaultfailureurl is null, the senderror () method is executed, which should be the same as the previous setting, and this method also reports an error in the error log. Since the error code and error information I want have been returned, I simply do not call the parent method. After a try, sure enough, the console no longer reports an error and returns normally.

Solution: no longer call the parent class method, and annotate super.onauthenticationfailure (request, response, exception); sentence.

OK, get it done and start sharing the joy of success.

[Solved] Compilation failed: internal java compiler error

Error: java: Compilation failed: internal java compiler error
1. Open File –> Setting —> Build,Exception,Deployment –> Compiler –> Java Compiler  Set the value of Target bytecode version to jdk version in Module.

2. Project 2 jdk:File ->Project Structure->Project Settings ->Project

3. Project jdk: File ->Project Structure->Project Settings ->Modules

4. pom.xml file in jdk version check

[Solved] error: method does not override or implement a method from a supertype

Compilation error:

error: method does not override or implement a method from a supertype

@Override

error: TestDocumentClipper is not abstract and does not override abstract method copyFromClipboard(DocumentInfo,DocumentStack,Callback,Injector) in DocumentClipper

The above is the compilation error caused by increasing or decreasing the parameters in the method when overriding the method of the parent class in a subclass, or when implementing the interface and overriding the method of the interface in a class
the above error messages are translated as:

1. Method does not override or implement the method in the supertype
2. Testdocumentclipper is not abstract and does not override the abstract method copyfromclipboard (documentinfo, documentstack, callback, injector) in documentclipper

Analysis:
when the documentclipper class implements the methods of the documentclipper interface, it adds (reduces) one more parameter, but there is no corresponding method in the interface to match, so it leads to compilation errors.

Solution:
Add (reduce) the same parameter to the corresponding method in the interface (parent class).

For example, you override the copyfromclipboard() method of the documentclipper interface in the documentclipper class. Because of necessity or carelessness, you add the parameter injector of type injector. The code is as follows:

@Override
public void copyFromClipboard(
        DocumentInfo destination,
        DocumentStack docStack,
        FileOperations.Callback callback,Injector injector){……

At this time, you need to find the copyfromclipboard() method in the documentclipper interface and add the same type of parameters

void copyFromClipboard(
            DocumentInfo destination,
            DocumentStack docStack,
            FileOperations.Callback callback,Injector injector);

Initialization of bean failed; nested exception is java.lang.StackOverflowError

Too many assemblies in mybatis spring mapper cause stackoverflow

It is applicable to idea starting a new SSM project
environment Tomcat deployment
reason: the space size of Tomcat catalina.sh is not configured

terms of settlement

1. Modify the catalina.sh file of Tomcat

Directory: Apache Tomcat \ bin \ Catalina. Sh
self allocated space size
Directory: JDK \ 1.8 \ JRE \ lib \ AMD64 \ JVM. CFG
self allocated space size

2. Easy: modify the current project configuration of idea

two point one

Generally, 2100 variables are enough

  Tomcat startup space configuration

 

-Xms512m -Xmx512m -Xss2m -XX:PermSize=512m -XX:MaxPermSize=1024m

Restart to solve the problem

I am the second configuration. Because there is a configured space allocation on the server, my locally developed tester is simply configured on the idea.

Solve the problem of error running xxxapplication command line is too long when compiling and running IntelliJ idea

This article is an original article of Joshua 317. Please note that it is reproduced from Joshua 317 blog   Solve the problem of error running xxxapplication command line is too long – Joshua 317 when compiling IntelliJ idea

Idea reports an error when compiling the project, and the saved information is as follows:

15:42	Error running 'xxxxApplication': Command line is too long. Shorten command line for xxxxApplication or also for Spring Boot default configuration.

Solution 1

Found in the project folder. Idea/workspace.xml

<component name="PropertiesComponent">

  ...

</component>

Then add a row of attributes to solve the problem:

<property name="dynamic.classpath" value="true" />

Solution 2

Open the running configuration of the program and change short command line to jar manifest or classpath file , as shown in the figure:

This article is an original article of Joshua 317. Please note that it is reproduced from Joshua 317 blog   Solve the problem of error running xxxapplication command line is too long – Joshua 317 when compiling IntelliJ idea

org.thymeleaf.exceptions.TemplateInputException: Error resolving template [XXX]

Error record:

org.thymeleaf.exceptions.TemplateInputException: Error resolving template [currentUserCartItems]

Background: Spring + thymeleaf reports an error

Reason: no @ respontroller or @ ResponseBody annotation is written on the method of data returned by the controller, and the returned data will be converted to JSON format

note: if it is necessary to return page Jump, it is best to add @ ResponseBody annotation on the specific method of data returned, otherwise other controllers cannot jump to the page normally

When idea generates a spring boot project, error: read timed out appears

When using idea to generate spring boot projects, the following occurs: error: read timed out ,

The solution is as follows:

    click file in the upper right corner of idea and select settings in the list. Click settings
    to open the settings box, and select appearance & amp; on the left; Behavior –> System Settings –> HTTP proxy, select auto detect proxy settings on the right, click Check connection below, and fill in in the pop-up box https://start.spring.io , click OK
    , and the connection successful information will be displayed in the pop-up box, and it will succeed.

Idea SpringBoot:Error creating bean with name ‘XXXXController‘

Problem Description:

Red when starter starts springboot:

  Error creating bean with name ‘indexController’

Error creating bean named ‘indexcontroller’

Error in bean of ‘sqlsessionfactory’: failed to instantiate bean through factory method

Problem solving:

According to the error report, it can be seen that the mapper layer is not injected and the mapper instance cannot be found. First, check the springboot core configuration file application.yml. In the mybatis configuration structure, the bean is not configured in the custom scan package type aliases package. Just reconfigure it (the package name depends on the individual)

com.crm.bean;

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>

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.