Author Archives: Robins

for..in loops iterate over the entire prototype chain, which is virtually never what you want.

for..in loops iterate over the entire prototype chain, which is virtually never what you want.

It means that using for..in will traverse the entire prototype chain, which is not a good way to implement it. Object.keys is recommended

formRules : {
  name : true,
  cardType: true,
  certificateNo: true
 },
 formData : {
  name :  '' ,
  certificateType:  '' ,
  certificateNo:  ''
 }

Original code

for ( const key in  this .formData) {
     if (! this .formData[key]) { this .formRules[key] = false ; valid = false }
     if ( this .formData[key]) this .formRules[key] = true
}

Modified code

Object.keys( this .formData).forEach(key => {
 if (! this .formData[key]) { this .formRules[key] = false ; valid = false }
 if ( this .formData[key]) this .formRules[key] = true
})

React Hook “useState“ is called in function “xxx“ which is neither a React function component or

Error code

import {useState,useEffect} from 'react'
const useData = () => {
    const [data,setData] = useState({count:0});
    useEffect(()=>{
        setTimeout(()=> {
            setData((data)=>({...data,count:data.count+1}))
        }, 1000 );
    },[])
    return {data}
}
 
export default useData

Modified code

import React from 'react'
import useData from '../hooks/AppData'
const AppData = ()=>{
    const {data} = useData()
    return <div>
    count->{data.count}
    </div>
}
export default AppData; // Change the first letter of the name to uppercase

How to Solve Error vim :call CompileRunGcc()

Fault description
Modify the ~/.vimrc configuration file to run the py script with one click. The
content of the vimrc configuration file is as follows

map <F5> :call CompileRunGcc()<CR>

func! CompileRunGcc()
    exec "w" 
    if &filetype == 'c' 
        exec '!g++ % -o %<'
        exec '!time ./%<'
    elseif &filetype == 'cpp'
        exec '!g++ % -o %<'
        exec '!time ./%<'
    elseif &filetype == 'python'
        exec '!time python %'
    elseif &filetype == 'sh'
        :!time bash %
    endif                                                                              
endfunc 

vim a.py press F5 as follows

Use script

" <f5> run python programmer
map <f5> :w<cr>:!python %<cr>

Can run normally

In other words, the contents of the function body cannot be executed.

 

The cause of the fault
was resolved on December 23, 2020. The cause of the /etc/profilealias alias vim='/usr/bin/vi, there is an alias in the file , that is, the vim command actually uses vi

Solution
to /etc/profilefile alias vim='/usr/bin/vichange alias vim='/usr/bin/vimcan be.

Here are the solutions to other problems
. The VI in Centos only installs vim-minimal-7.x by default. No matter you enter vi or vim to view the file, the syntax function cannot be enabled normally. Therefore, two other components need to be installed with yum: vim-common-7.x and vim-enhanced-7.x.

#View vim components
[root@client1 ~]# rpm -qa | grep vim
vim-enhanced-7.4.629-7.el7.x86_64
vim-filesystem-7.4.629-7.el7.x86_64
vim-X11-7.4.629-7.el7.x86_64
vim-common-7.4.629-7.el7.x86_64
vim-minimal-7.4.629-7.el7.x86_64

#install vim
yum -y install vim*

ls: cannot access /com: Host is down

Fault description

[root@client1 home]# ls /
ls: cannot access /com: Host is down

 

Cause of the failure
There is a folder in your current directory that is a network folder, and this folder points to a folder on a remote host on the network.
And when you use ls now, the remote host has been shut down, this will happen.

Solution
umount /com
comment /etc/fstab about the content of /com

ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock’

The binary installation mysql reports the following error

[root@tzPC sdb1]# mysql -v
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

It is found that /tmp/mysql.sock does not exist. The reason for this is generally due to inconsistent configuration files. If mysqld is started by mistake, mysqld_safe will clear mysql.sock once.

Solution

First check whether the current process has a surviving mysql, kill it, and then restart the database

$ ps -ef | grep mysql
$ kill -9 xxxx
$ /etc/init.d/mysqld start

If it still cannot be resolved, check whether the configuration file is correct

$ cat /etc/my.cnf
[mysqld]
user=mysql
basedir=/mnt/sdb1/mysql
datadir=/mnt/sdb1/mysql_data
socket=/tmp/mysql.sock
server_id=6
port=3306
[mysql]
socket=/tmp/mysql.sock

Use the command to find the mysql.sock file

$ find / -name mysql.sock

If not found, re-execute mysql_install_db to rebuild the authorization table

$ mysql/bin/mysql_install_db

Then execute the following command, the mysql.sock file will be there

$ mysql/bin/mysqld_safe &

$ find / -name mysql.sock
/tmp/mysql.sock

MySql Warning: The server quit without updating PID file error

There are 5 solutions as follows, I generally use the first one to solve the problem, and the other online searches are organized as follows for reference

1. Kill the existing mysql process

ps -ef | grep mysqld
kill -9 xxx

2. Insufficient mysql file permissions

chown -R mysql:mysql /mnt/mysql
chmod -R 755 /mnt/mysql
/etc/init.d/mysqld restart

3. When mysql is installed for the second time, there is residual data that affects the service startup

Delete the mysql-bin.index file in the /mysql_data directory

4. View the configuration file my.cnf

[root@tzPC mysql]# cat /etc/ my.cnf 
[mysqld] 
user = mysql 
basedir =/mnt/ mysql 
datadir =/mnt/ mysql_data #Check if there is this line 
socket =/tmp/ mysql.sock 
server_id = 6 
port = 3306 
[mysql] 
socket =/tmp/mysql.sock

5. Turn off selinux

[root@tzPC mysql]# cat /etc/selinux/config 

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of three two values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected. 
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted

jasypt springboot Error: Error creating bean with name ‘enableEncryptablePropertySourcesPostProcessor’ defined in class path resource

background

When using jasypt to encrypt sensitive information in the spring boot configuration file, an exception was encountered when using statuser to start directly

<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>3.0.3</version>
</dependency>

Encountered the following exception:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'enableEncryptablePropertySourcesPostProcessor' defined in class path resource [com/ulisesbocchio/jasyptspringboot/configuration/EnableEncryptablePropertiesConfiguration.class]: Unsatisfied dependency expressed through method 'enableEncryptablePropertySourcesPostProcessor' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'xxxDao' defined in xxxDao defined in @EnableJpaRepositories declared on Application: Unsatisfied dependency expressed through constructor parameter 1: Ambiguous argument values for parameter of type [javax.persistence.EntityManager] - did you specify the correct bean references as arguments?
	at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:797)
	at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:538)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1336)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1176)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:556)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516)
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207)
	at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:172)
	at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:707)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:533)
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143)
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758)
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750)
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
...

The above information refers to the enableEncryptablePropertySourcesPostProcessorfailure due to the failure to create other types of Bean when it was created.

Let me talk about this problem first because the spring boot BeanFactoryPostProcessor and the custom repositoryFactoryBeanClass in the custom @EnableJpaRepositories are not compatible when they are created at startup. The @Repository annotated bean is initialized in advance (when the enableEncryptablePropertySourcesPostProcessor is created, because of the spring boot mechanism As a result, some classes are instantiated in advance, but the BeanFactoryPostProcessor processing @Repository has not been loaded)

If you do not customize the custom repositoryFactoryBeanClass in @EnableJpaRepositories, the above exception will not occur

Solution

After that, I wanted to implement the jasypt method by myself, but the BeanFactoryPostProcessor implementation method that still needs jasypt appeared, so I gave up, and finally used the rewriting PropertySource method, plus reflection to complete itself to decrypt the encrypted information that has been read (in the Before the bean is placed in the container, that is, before the annotations such as @Value take effect)

1. Introduce the following packages, remove the spring boot stater package of jasypt

<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot</artifactId>
    <version>3.0.3</version>
</dependency>

2. Define @Configuration to inject PropertySource beans

//JasyptPropertyValueConfig.java

import org.springframework.beans.factory.config.PropertyOverrideConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JasyptPropertyValueConfig {

    @Bean
    public PropertyOverrideConfigurer jasyptPropertyOverrideConfigurer() {
        return new JasyptPropertyValueHandler();
    }
}

//JasyptPropertyValueHandler.java

import org.jasypt.util.text.BasicTextEncryptor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyOverrideConfigurer;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.boot.origin.OriginTrackedValue;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.SimpleCommandLinePropertySource;
import org.springframework.web.context.support.StandardServletEnvironment;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.StreamSupport;


public class JasyptPropertyValueHandler extends PropertyOverrideConfigurer implements EnvironmentAware {

    private static BasicTextEncryptor textEncryptor = null;
    private final String KEY_SEED = "jasypt.encryptor.password";
    private final String PREFIX = "ENC(";
    private final String SUFFIX = ")";
    private final byte[] tmp_lock = new byte[1];
    private boolean isInit;
    private String seed;
    private Environment environment;

    public JasyptPropertyValueHandler() {

    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        MutablePropertySources propertySources = ((StandardServletEnvironment) environment).getPropertySources();
        convertPropertySources(propertySources);
        super.postProcessBeanFactory(beanFactory);
    }


    public void convertPropertySources(MutablePropertySources propSources) {
        initSeed();
        // Command line parameter SimpleCommandLinePropertySource
        // yml profile parametersOriginTrackedMapPropertySource
        StreamSupport.stream(propSources.spliterator(), false)
                .filter(ps -> (ps instanceof OriginTrackedMapPropertySource) || (ps instanceof SimpleCommandLinePropertySource))
                .forEach(ps -> {
                    if (ps instanceof OriginTrackedMapPropertySource) {
                        handleConfigFile(ps);
                    } else if (ps instanceof SimpleCommandLinePropertySource) {
                        handleCommandLine(ps);
                    }
                    propSources.replace(ps.getName(), ps);
                });
    }
    //Handle spring boot's default configuration file, such as application.yml or application.properties to load all the content
    private void handleConfigFile(PropertySource ps) {
        Map<String, OriginTrackedValue> result = (Map<String, OriginTrackedValue>) ps.getSource();
        for (String key : result.keySet()) {
            OriginTrackedValue value = result.get(key);
            if (checkNeedProcessOverride(key, String.valueOf(value.getValue()))) {
                System.out.println(value);
                String decryptedValue = decryptValue(seed, String.valueOf(value.getValue()));
                try {
                    Field valueField = OriginTrackedValue.class.getDeclaredField("value");
                    valueField.setAccessible(true);
                    valueField.set(value, decryptedValue);
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //Handle the replacement of spring boot arguments on the command line, for example in the form of the --spring.datasource.password argument
    private void handleCommandLine(PropertySource ps) {
        try {
            Object commandLineArgs = ps.getSource();
            Field valueField = commandLineArgs.getClass().getDeclaredField("optionArgs");
            valueField.setAccessible(true);
            boolean hasEncrypt = false;
            Map<String, List<String>> result = (Map<String, List<String>>) valueField.get(commandLineArgs);
            for (String key : result.keySet()) {
                List<String> values = result.get(key);
                if (values.size() == 1) {
                    if (checkNeedProcessOverride(key, String.valueOf(values.get(0)))) {
                        hasEncrypt = true;
                        String decryptedValue = decryptValue(seed, String.valueOf(values.get(0)));
                        values.clear();
                        values.add(decryptedValue);
                    }
                }
            }

            if (hasEncrypt) {
                valueField.set(commandLineArgs, result);
            }


        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }


    private boolean checkNeedProcessOverride(String key, String value) {
        if (KEY_SEED.equals(key)) {
            return false;
        }
        return StringUtils.isNotBlank(value) && value.startsWith(PREFIX) && value.endsWith(SUFFIX);
    }

    private void initSeed() {
        if (!this.isInit) {
            this.isInit = true;
            this.seed = this.environment.getProperty(KEY_SEED);
            if (StringUtils.isNotBlank(this.seed)) {
                return;
            }
            try {
                Properties properties = mergeProperties();
                //From the startup command line, get the value of -Djasypt.encryptor.password
                this.seed = properties.getProperty(KEY_SEED);
            } catch (Exception e) {
                System.out.println("No encryption key configured");
            }
        }
    }

    private String decryptValue(String seed, String value) {
        value = value.replace(PREFIX, "").replace(SUFFIX, "");
        value = getEncryptor(seed).decrypt(value);
        return value;
    }

    private BasicTextEncryptor getEncryptor(String seed) {
        if (textEncryptor == null) {
            synchronized (tmp_lock) {
                if (textEncryptor == null) {
                    textEncryptor = new BasicTextEncryptor();
                    textEncryptor.setPassword(seed);
                }
            }
        }
        return textEncryptor;
    }
}

//JasyptController.java

import org.jasypt.util.text.BasicTextEncryptor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("jasypt")
public class JasyptController {
    @Value(${jasypt.encryptor.password})
    private String seed;
    private static BasicTextEncryptor textEncryptor = null;
    private final byte[] tmp_lock = new byte[1];

    @RequestMapping("encrypt")
    public String encrypt(String value){
        textEncryptor=getEncryptor(seed);
        return textEncryptor.encrypt(value);
    }

    @RequestMapping("decrypt")
    public String decrypt(String value){
        textEncryptor=getEncryptor(seed);
        return textEncryptor.decrypt(value);
    }

    private BasicTextEncryptor getEncryptor(String seed) {
        if (textEncryptor == null) {
            synchronized (tmp_lock) {
                if (textEncryptor == null) {
                    textEncryptor = new BasicTextEncryptor();
                    textEncryptor.setPassword(seed);
                }
            }
        }
        return textEncryptor;
    }
}

  • After the project is started /jasypt/encrypt?value=Need to encrypt content, you can request the interface to get the ciphertext

how to use

After the above configuration is completed, you can use the configuration file and command line method of jasypt

1. In the configuration file

Write an application.properties here

spring.datasource.password=ENC(Encrypted ciphertext)

Then the command line uses the password to start the jar package

java -Djasypt.encrypt.password=Encrypted password -jar  xxx.jar

2. Command line

java -Djasypt.encrypt.password=Encrypted password -jar --spring.datasource.password=ENC(Encrypted ciphertext) xxx.jar

The above follows the coverage priority of spring boot.

to sum up

Because this is not an implementation of jasypt, it just simulates the commonly used configuration files and command decryption methods by default, so the custom content of jasypt cannot be used, and those who are interested can implement it by themselves

tips:  
    1. jasypt the same content is encrypted with different ciphertext every time  
    2. The ciphertext after different items encrypt the same content cannot be decrypted by the same password

Android integration of iFLYTEK’s speech recognition (voice dictation) error message “Failed to create the object, please confirm that libmsc.so is placed correctly, and createUtility is called to initialize”

The corresponding lib resource downloaded from the official website has been placed under the project lib or an error is reported. The reason is that the project does not load the lib

sourceSets { 
    main { 
        jniLibs.srcDirs = ['libs'] 
    } 
} 

put this in build.gradle inside android inside 
android{ 
............... 
.....
sourceSets { 
    main { 
        jniLibs.srcDirs = ['libs'] 
    } 
}
.... 
}

How to solve Uncaught (in promise) error in VUE?

When writing the vue project interface today, there was an Uncaught (in promise) error error.

 

 

 

I took a closer look, the interface is ok,

 

 

 

Me where the problem seems to have nothing, why the console which will be reported this wrong?

 

Later I found out that I did not write catch and he forcibly threw the error, so I changed the code to the following.

 

 

 

 

But after the change, it did not report the Uncaught (in promise) error error, and the other errors were reported, and a bunch of such errors were reported ↓

 

 

 

 

 

Reported so many mistakes, almost forced me. (But don’t panic, raise Erlang’s legs, drink a glass of water, and continue to look down)

 

 

      .catch(err=>{
this.$message.error(err.message);
console.log(err);
})

 

Just write message after err.