Category Archives: Error

[Solved] java.sql.SQLException: Connection is read-only. Queries leading to data modification are not allowed

error

Error updating database.  Cause: java.sql.SQLException: Connection is read-only. Queries leading to data modification are not allowed
### The error may exist in file [E:\javaproject\Demo11\spring-01-hellospring\spring-09-transaction\target\classes\com\kuang\mapper\UserMapper.xml]
### The error may involve com.kuang.mapper.UserMapper.addUser-Inline

error code

Solution:

Directly remove

[Solved] Error: bash: syntax error near unexpected token ` (‘

You need to delete a zip package in the server and execute the operation deletion prompt: – bash: syntax error near unexpected token ` (‘

Failed to delete normally

Reason: after Linux 5.0, parentheses cannot be used, and translation is required

There are two methods of Translation:

  1. adding escape characters\
  2. 2.just add “” in parentheses

I add double quotation marks directly, and then delete it successfully.

[Solved] Error creating bean with name ‘transactionManager’ defined in class path resource [spring-dao.xml]

error

Error creating bean with name 'transactionManager' defined in class path resource [spring-dao.xml]:
 Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required

Reason: when matching things, there is no injected value

error code

Solution: inject value into him

Correct code

[Solved] RuntimeError: DataLoader worker (pid 463) is killed by signal: Bus error. It is possible that datalo

There is a line surface error during yolov5 training in the image. The reason is that there is not enough SHM allocated by the docker container, so you need to manually set the SHM size to be small.

RuntimeError: DataLoader worker (pid 463) is killed by signal: Bus error. It is possible that dataloq

Rerun a container

sudo docker run --name '' -p 5000:5000 -v /home:/home --runtime=nvidia --shm-size 8g -itd torch:v1 bash

[Solved] Error in v-on handler: “TypeError: this.$confirm is not a function“

Error in v-on handler: “TypeError: this.$confirm is not a function“

In the Vue project, an error is reported after changing the global import of element UI to on-demand import

Solution:

1. Introduce MessageBox plug-in

import {MessageBox} from ‘element-ui’

2 mount confirm
on the prototype object of Vue

Vue.prototype.$confirm = MessageBox.confirm

[Solved] Mybatis Error: org.apache.ibatis.cache.CacheException: Error serializing object. Cause: java.io.NotSerializableExc

org.apache.ibatis.cache.CacheException: Error serializing object. Cause: java.io.NotSerializableException: com.baizhi.entity.User
at org.apache.ibatis.cache.decorators.SerializedCache.serialize(SerializedCache.java:100)
atorg.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.io.NotSerializableException: com.baizhi.entity.User
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
org.apache.ibatis.cache.decorators.SerializedCache.serialize(SerializedCache.java:96)
… 47 more

Reason: when using the L2 cache in mybatis, the entity class must be serialized. Implements serializable. My mapper file uses tags and the L2 cache provided by mybatis, so it must be serialized in my entity class

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.baizhi.dao.UserDao">
     <!-- The L2 cache is used here The entity class must implement the serialization interface -->
    <cache/>  
    <select id="selectAllUsers" resultType="User">
        select id,
               phone,
               password,
                name,
        from c_user
    </select>
</mapper>

[Solved] remote calling three-party interface error: javax.net.ssl.SSLHandshakeException

1. Foreword

Recently, when interfacing with Tencent conference API interface, it started calling the other party’s interface after authentication. During this process, an error occurred: javax.net.ssl.sslhandshakeexception.

2. Cause of occurrence

When you make an HTTPS request, the trust certificate of the third-party service does not exist in the JDK, resulting in the error javax.net.ssl.sslhandshakeexception: sun.security.validator.validatorexception: PKIX path construction failed.

3. Solution

1. Obtain the root certificate and install the certificate into your JRE’s Java cacerts (install the certificate into the pathoyourjdk/JRE/lib directory/cacerts).

2. Ignore verification of SSL certificates.

In many cases, there is no certificate, so the second scheme is used to ignore the SSL certificate verification in your code.

4. Code

Here, you should distinguish between the way you use to call three-party services (resttemplate, okhttpclient).

1.RestTemplate

package com.hikvision.meeting.config;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;


/**
 * @author dongliang7
 * @projectName 
 * @ClassName Config2RestTemplate.java
 * @description: Skip Certificate Validation
 * @createTime 2021年11月23日 09:59:00
 */
@Configuration
public class Config2RestTemplate {

    @Bean
    public RestTemplate restTemplate() throws Exception {
        TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

        SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                .loadTrustMaterial(null, acceptingTrustStrategy)
                .build();

//        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(createIgnoreVerifySSL(),
                // Specify the TLS version
                null,
                // Specify the algorithm
                null,
                // Cancel domain validation
                new HostnameVerifier() {
                    @Override
                    public boolean verify(String string, SSLSession ssls) {
                        return true;
                    }
                });

        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(csf)
                .build();

        HttpComponentsClientHttpRequestFactory requestFactory =
                new HttpComponentsClientHttpRequestFactory();

        requestFactory.setHttpClient(httpClient);
        requestFactory.setReadTimeout(60 * 1000);// ms
        requestFactory.setConnectTimeout(60 * 1000);// ms
        // The code means whether the request factory class is applied to buffer the request body internal, the default value is true, when the post or put large files will cause memory overflow situation, set to false will flow data directly into the underlying HttpURLConnection
        requestFactory.setBufferRequestBody(false);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        return restTemplate;
    }

    /**
     * Skip certificate validation sslcontext
     *
     * @return
     * @throws Exception
     */
    private static SSLContext createIgnoreVerifySSL() throws Exception {
        SSLContext sc = SSLContext.getInstance("TLS");

        // Implement an X509TrustManager interface for bypassing authentication without modifying the methods inside
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate,
                                           String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate,
                                           String paramString) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        sc.init(null, new TrustManager[] { trustManager }, null);
        return sc;
    }
}

2, OkHttpClient

package com.tencent.wemeet.gateway.restapisdk.util;

import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;

import javax.net.ssl.*;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * @author dongliang7
 * @projectName tenxun-meeting-api
 * @ClassName SSLSocketClient.java
 * @description: Create OkHttpClient without SSL (certificate) validation
 * @createTime 2021年11月19日 09:50:00
 */
@Slf4j
public class SSLSocketClient {

    public static OkHttpClient getUnsafeOkHttpClient() {
        try {
            // Create a trust manager that does not validate the certificate chain
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {}
                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {}
                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };
            if (trustAllCerts.length != 1 || !(trustAllCerts[0] instanceof X509TrustManager)) {
                throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustAllCerts));
            }
            X509TrustManager x509TrustManager = (X509TrustManager) trustAllCerts[0];

            // Install the full trust trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create the ssl socket factory using our fully trusted manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder()
                    .connectTimeout(60 , TimeUnit.SECONDS).readTimeout(60 , TimeUnit.SECONDS).writeTimeout(120 , TimeUnit.SECONDS);
            builder.sslSocketFactory(sslSocketFactory , x509TrustManager);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            OkHttpClient okHttpClient = builder.build();
            return okHttpClient;
        } catch (Exception e) {
            log.error("Failed to create OkHttpClient without SSL (certificate) validation: {}", e.getMessage());
            throw new RuntimeException(e);
        }
    }
}

Get okhttpclient:

 // Create OkHttpClient without SSL (certificate) authentication
    private static final OkHttpClient okHttpClient = SSLSocketClient.getUnsafeOkHttpClient();

Nacos-client Call Error: failed to create cache dir [How to Solve]

Problem background:

In our project, the gateway is used to realize the diversion of microservices, that is, to control the proportion of traffic to different instances of a microservice. Therefore, many methods to call Nacos API are written in geteway.

When deploying a new environment, the following errors are reported. Our server uses k8s and the images are unified.

2021-11-23 16:53:54.568 ERROR [***-gateway,,,] 1 --- [           main] com.alibaba.nacos.client.naming          : [NA] failed to write cache for dom:DEFAULT_GROUP@@***-****

java.lang.IllegalStateException: failed to create cache dir: /root/nacos/naming/753378b3-d4ad-4f1a-859b-f9d57df33c9f
    at com.alibaba.nacos.client.naming.cache.DiskCache.makeSureCacheDirExists(DiskCache.java:154) ~[nacos-client-1.1.4.jar:na]
    at com.alibaba.nacos.client.naming.cache.DiskCache.write(DiskCache.java:45) ~[nacos-client-1.1.4.jar:na]
    at com.alibaba.nacos.client.naming.core.HostReactor.processServiceJSON(HostReactor.java:184) [nacos-client-1.1.4.jar:na]

Troubleshooting process:

The error content is obvious, that is, to write the cache file to the server, but it failed. Through the error prompt, we found the error reporting class in nacos-client-1.1.4.jar

package com.alibaba.nacos.client.naming.cache;

public class DiskCache {

    public static void write(ServiceInfo dom, String dir) {
        try {
            makeSureCacheDirExists(dir);
            File file = new File(dir, dom.getKeyEncoded());
            if (!file.exists()) {
                // add another !file.exists() to avoid conflicted creating-new-file from multi-instances
                if (!file.createNewFile() && !file.exists()) {
                    throw new IllegalStateException("failed to create cache file");
                }
            }
            StringBuilder keyContentBuffer = new StringBuilder("");
            String json = dom.getJsonFromServer();
            if (StringUtils.isEmpty(json)) {
                json = JSON.toJSONString(dom);
            }
            keyContentBuffer.append(json);
            //Use the concurrent API to ensure the consistency.
            ConcurrentDiskUtil.writeFileContent(file, keyContentBuffer.toString(), Charset.defaultCharset().toString());
        } catch (Throwable e) {
            NAMING_LOGGER.error("[NA] failed to write cache for dom:" + dom.getName(), e);
        }
    }

    *******

  private static File makeSureCacheDirExists(String dir) {
        File cacheDir = new File(dir);
        if (!cacheDir.exists() && !cacheDir.mkdirs()) {
            throw new IllegalStateException("failed to create cache dir: " + dir);
        }
        return cacheDir;
    }
}

The write method calls makesurecachedirexists. In the makesurecachedirexists method, if the cache file does not exist and the directory creation fails, an exception will be thrown.

Through the transfer relationship, we find out who called the write method of diskcache. I find hostreactor. The cache address cachedir is passed in through the construction method.

package com.alibaba.nacos.client.naming.core;
public class HostReactor {
  
  public HostReactor(EventDispatcher eventDispatcher, NamingProxy serverProxy, String cacheDir, boolean loadCacheAtStart, int pollingThreadCount) {
    ......
   }
}

Looking forward, I found that when nacosnamingservice was instantiated, it was called   HostReactor

package com.alibaba.nacos.client.naming;

@SuppressWarnings("PMD.ServiceOrDaoClassShouldEndWithImplRule")
public class NacosNamingService implements NamingService {
  private HostReactor hostReactor;

  public NacosNamingService(String serverList) {
        Properties properties = new Properties();
        properties.setProperty(PropertyKeyConst.SERVER_ADDR, serverList);

        init(properties);
    }

    public NacosNamingService(Properties properties) {
        init(properties);
    }

    private void init(Properties properties) {
        namespace = InitUtils.initNamespaceForNaming(properties);
        initServerAddr(properties);
        InitUtils.initWebRootContext();
        initCacheDir();
        initLogName(properties);

        eventDispatcher = new EventDispatcher();
        serverProxy = new NamingProxy(namespace, endpoint, serverList);
        serverProxy.setProperties(properties);
        beatReactor = new BeatReactor(serverProxy, initClientBeatThreadCount(properties));
        hostReactor = new HostReactor(eventDispatcher, serverProxy, cacheDir, isLoadCacheAtStart(properties), initPollingThreadCount(properties));
    }
  private void initCacheDir() {
        cacheDir = System.getProperty("com.alibaba.nacos.naming.cache.dir");
        if (StringUtils.isEmpty(cacheDir)) {
            cacheDir = System.getProperty("user.home") + "/nacos/naming/" + namespace;
        }
    }

    ......
}

The construction methods of nacosnamingservice all call the init method, and the init method calls the initcachedir() method to assign a value to the cachedir variable, and finally completes the initialization of the hostreactor class.

When you see the contents of the initcachedir method, you should understand that there are two ways to specify the Nacos cache path:

1. Specify the parameters in the project configuration file: com.alibaba.nacos.naming.cache.dir

2. The root directory of the running user of the server+  /nacos/naming/

Solution:

1. If there is only root account on the server, you can try to let the operation and maintenance students release the write permission of/root/Nacos/naming/directory

2. Generally, the root directory is not allowed to be written casually. You can change other accounts on the server, start the application, and open the write permission of/user/Nacos/naming/directory

3. Configure in the YML file of the program Com.alibaba.nacos.naming.cache.dir, write the cache to an open file directory.