Category Archives: JAVA

[Solved] Specified key was too long; max key length is 767 bytes

Encountered the above-mentioned bug in production today:

       When the system variable innodb_large_prefix is ​​enabled, for InnoDB tables that use DYNAMIC or COMPRESSED row format, the index key prefix is ​​limited to 3072 bytes. If innodb_large_prefix is ​​disabled, no matter what table it is, the index key prefix is ​​limited to 767 bytes.

       The above bug is obviously that the index exceeds the limited length of 767 (innodb_large_prefix is ​​disabled in our production):

       I found that the table where the error was reported has established a varchar type index, varchar(255). I think there is no problem. In fact, it is not. The above 767 is a byte, and the varchar type is a character. At the same time, I found that the character set I used is ( utf8mb4), this means that the maximum number of bytes per character is 4, so it is obvious that 4*255> 767

So the above error was reported (Specified key was too long; max key length is 767 bytes).

       Solution:

     Change the number of characters in varchar, I changed it to 64. varchar(64)

 Or enable innodb_large_prefix, then the limit value will increase to 3072

The difference between Scanner.next() and Scanner.nextLine()

1. The space, tab key and enter key encountered before the next() method encounters a valid character cannot be used as a terminator, the next() method will automatically remove it, only when the next() method encounters a valid character After that, the next() method treats the space key, Tab key, or Enter key entered later as a separator or terminator, so next() cannot get the string with spaces, only part of the string (space front).

2. The terminator of the nextLine() method is the Enter key, that is, the nextLine() method returns all the strings before the Enter key, so the nextLine() method can get the string with spaces.

JAVA Error Illegal access: this web application instance has been stopped already. Could not load net.sf

This exception occurs when you restart tomcat, but it does not affect the normal function.

Exception code:

Message: Illegal access: this web application instance has been stopped already.  Could not load net.sf.ehcache.store.disk.DiskStore$KeySet.  The eventual following stack trace is caused by an error thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access, and has no functional impact.
java.lang.IllegalStateException
	at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1776)
	at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1734)
	at net.sf.ehcache.store.disk.DiskStore.keySet(DiskStore.java:521)
	at net.sf.ehcache.store.disk.DiskStorageFactory$DiskExpiryTask.run(DiskStorageFactory.java:828)
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
	at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:304)
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178)
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
	at java.lang.Thread.run(Thread.java:745)

Exception analysis: restart Tomcat repeatedly and frequently, resulting in the thread in the last tomat not closing normally
solutions:

Change the reloadable in server.xml in Tomcat from true to false.

After setting reloadable = “true”, Tomcat will monitor the source code of the project in real time, and restart the Tomcat server in case of any change. When debugging a program, relaodable = true is usually not set. It is unreasonable to restart Tomcat frequently. If you set reloadable = false, or do not set this property, only when you add, delete or rename method or instance fields, do you require the service to restart, which is suitable for you to debug programs.

File settings: server.xml & gt; reloadable=“false”。

How to get the current time in java time string

How to get the current time by Java
and convert it into java.sql.date format.

		long l = System.currentTimeMillis();
		//new date pair
		Date date = new Date(l);
		//convert to date output format
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println(dateFormat.format(date)); 
		
		String response = dateFormat.format(date).replaceAll("[[\\s-:punct:]]","");
		System.out.println("response="+response);

2021-05-07 09:35:47response=202105

Non empty judgment method: the difference between isnotempty and isnotblank. isNullOrEmpty

In the project, we mostly use the non empty judgment method in stringutils. I believe most people have used the isnotempty or isempty method
public static Boolean isnotempty (string STR)
to judge whether a string is non empty, equal to! Isempty (string STR), where the space character cannot be excluded

Public static Boolean isnotblank (string STR)
to determine whether a string is not empty, its length is not 0, and it is not composed of whitespace! isBlank(String str)

Therefore, in many business logics, isnotblank is better than isnotempty. One is to judge whether the string is not empty and the length is not 0, and it is not composed of whitespace

isNullOrEmpty

StringUtils.IsNullOrEmpty(null) = true
StringUtils.IsNullOrEmpty("") = true
StringUtils.IsNullOrEmpty(" ") = true
StringUtils.IsNullOrEmpty("12345") = false
StringUtils.IsNullOrEmpty(" 12345 ") = false

When doing a query: List detail = systemService.findListbySql(getNewDataId);
Determine if it is emptyif (!ListUtils.isNullOrEmpty(detail)) {}

[Solved] Consider defining a bean of type ‘org.springframework.data.redis.core.RedisTemplate‘ in your configu

Today, I only added this paragraph to find that the project can’t start

@Autowired
private RedisTemplate<String, Object> template;

Project error report

Description:

Field template in com.yy.service.impl.YuumiUserServiceImpl required a bean of type 'org.springframework.data.redis.core.RedisTemplate' that could not be found.

The injection point has the following annotations:
	- @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'org.springframework.data.redis.core.RedisTemplate' in your configuration.

Solution:
Add Class

package com.yy.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component; 

@Component
public class Config {

    @Bean(name = "template")
    public RedisTemplate<String, Object> template(RedisConnectionFactory factory) {
        // create RedisTemplate<String, Object>
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // Configuring the connection factory
        template.setConnectionFactory(factory);
        // Define the Jackson2JsonRedisSerializer serialization object
        Jackson2JsonRedisSerializer<Object> jacksonSeial = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        // Specify the fields to serialize, field, get and set, and the range of modifiers, ANY is both private and public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // Specify the type of serialized input, the class must be non-final modified, final modified class, such as String, Integer, etc. will report an exception
        om.activateDefaultTyping(

                LaissezFaireSubTypeValidator.instance ,
                ObjectMapper.DefaultTyping.NON_FINAL,

                JsonTypeInfo.As.WRAPPER_ARRAY);
        jacksonSeial.setObjectMapper(om);
        StringRedisSerializer stringSerial = new StringRedisSerializer();
        // redis key Serialization method using stringSerial
        template.setKeySerializer(stringSerial);
        // redis value serialization method using jackson
        template.setValueSerializer(jacksonSeial);
        // redis hash key serialized using stringSerial
        template.setHashKeySerializer(stringSerial);
        // redis hash value serialized using jackson
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();
        return template;
    }
}

The project runs successfully

jemter java.net.BindException:Address alreardy in use [How to Solve]

Phenomenon:

reason:

Windows itself provides port access mechanism.

Windows provides TCP/IP link ports of 1024 ~ 5000, and it takes 4 minutes to recycle these ports. At this time, if we run a large number of requests in a short time, the ports will be full.

Solution:

win + r   Enter regedit to open the registry   Find the following path

Computer_ LOCAL_ MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters

Right click parameters to create a new DWORD   The name is maxuserport   The value is 65534 (maximum 65535, set 65534 to prevent all ports from being occupied)

Right click parameters to create a new DWORD   The name is   TCPTimedWaitDelay   Value is 30 (default unit is seconds)

Reference: HTTPS://support.microsoft.com/zh-cn/help/196271/when-you-try-to-connect-from-tcp-ports-greater-than-5000-you-recover-t

[Solved] Failed to bind properties under ‘spring.servlet.multipart.file-size-threshold‘ to

Description:

Failed to bind properties under 'spring.servlet.multipart.file-size-threshold' to org.springframework.util.unit.DataSize:

    Property: spring.servlet.multipart.file-size-threshold
    Value: 20M
    Origin: class path resource [application.properties]:16:46
    Reason: failed to convert java.lang.String to org.springframework.util.unit.DataSize

Action:

Update your application's configuration

Disconnected from the target VM, address: '127.0.0.1:55242', transport: 'socket'

Process finished with exit code 1

Spring Boot 1.3 or earlier, configure :
multipart.maxFileSize = 100Mb
multipart.maxRequestSize=150Mb
After Spring Boot version 1.4 the configuration was changed to :
spring.http.multipart.maxFileSize = 100Mb
spring.http.multipart.maxRequestSize = 150Mb

The configuration of Spring Boot 2.0 onwards has been changed: the unit Mb has been changed to MB
spring.servlet.multipart.max-file-size = 100MB
spring.servlet.multipart.max-request-size = 150MB

[Solved] Java.lang.IllegalStateException: Type handler was null on parameter mapping for property ‘__frch_it

2018-08-28 17:13:21 ERROR com.sprucetec.osc.task.ScanBalanceTask scanBalanceInnerNew:114 – ScanBalance Failed!
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException:
### Error querying database.  Cause: java.lang.IllegalStateException: Type handler was null on parameter mapping for property ‘__frch_item_0’.  It was either not specified and/or could not be found for the javaType/jdbcType combination specified.
### Cause: java.lang.IllegalStateException: Type handler was null on parameter mapping for property ‘__frch_item_0’.  It was either not specified and/or could not be found for the javaType/jdbcType combination specified.
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:75)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:371)
at com.sun.proxy.$Proxy20.selectList(Unknown Source)
at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:198)
at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:119)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:63)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:52)
at com.sun.proxy.$Proxy32.getBillBalanceAndMoney(Unknown Source)
at com.sprucetec.osc.manager.impl.OscCustomerBillManagerImpl.getBillBalanceAndMoney(OscCustomerBillManagerImpl.java:1440)
at com.sprucetec.osc.manager.impl.OscCustomerBillManagerImpl$$FastClassBySpringCGLIB$$e9ab471c.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:649)
at com.sprucetec.osc.manager.impl.OscCustomerBillManagerImpl$$EnhancerBySpringCGLIB$$392028c4.getBillBalanceAndMoney(<generated>)
at com.sprucetec.osc.task.ScanBalanceTask.scanBalanceInnerNew(ScanBalanceTask.java:92)
at com.sprucetec.osc.task.ScanBalanceTask$2.run(ScanBalanceTask.java:71)
at com.sprucetec.osc.base.redis.RedisLock.wrap(RedisLock.java:199)
at com.sprucetec.osc.task.ScanBalanceTask.scanBalanceByHand(ScanBalanceTask.java:68)
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 org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:266)
at java.util.concurrent.FutureTask.run(FutureTask.java)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.ibatis.exceptions.PersistenceException:
### Error querying database.  Cause: java.lang.IllegalStateException: Type handler was null on parameter mapping for property ‘__frch_item_0’.  It was either not specified and/or could not be found for the javaType/jdbcType combination specified.
### Cause: java.lang.IllegalStateException: Type handler was null on parameter mapping for property ‘__frch_item_0’.  It was either not specified and/or could not be found for the javaType/jdbcType combination specified.
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:26)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:111)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:102)
at sun.reflect.GeneratedMethodAccessor221.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:358)
… 30 more
Caused by: java.lang.IllegalStateException: Type handler was null on parameter mapping for property ‘__frch_item_0’.  It was either not specified and/or could not be found for the javaType/jdbcType combination specified.
at org.apache.ibatis.mapping.ParameterMapping$Builder.validate(ParameterMapping.java:117)
at org.apache.ibatis.mapping.ParameterMapping$Builder.build(ParameterMapping.java:104)
at org.apache.ibatis.builder.SqlSourceBuilder$ParameterMappingTokenHandler.buildParameterMapping(SqlSourceBuilder.java:122)
at org.apache.ibatis.builder.SqlSourceBuilder$ParameterMappingTokenHandler.handleToken(SqlSourceBuilder.java:66)
at org.apache.ibatis.parsing.GenericTokenParser.parse(GenericTokenParser.java:53)
at org.apache.ibatis.builder.SqlSourceBuilder.parse(SqlSourceBuilder.java:45)
at org.apache.ibatis.scripting.xmltags.DynamicSqlSource.getBoundSql(DynamicSqlSource.java:43)
at org.apache.ibatis.mapping.MappedStatement.getBoundSql(MappedStatement.java:278)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:75)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:108)
… 35 more

The item here should be an object and should hold the properties of that object

How to Open Files by Dragging and Dropping in C#

Set the Form property allowDrop = True;
In the Form event C # tutorial

private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            string localFilePath = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();//Full path of the file
            GetExtension(localFilePath);//file suffix name
            if (extension == ".cbd")
            {
         //todo you code
            }
        }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
           
            string localFilePath = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
            string extension = System.IO.Path.GetExtension(localFilePath);
            if (string.Compare(extension, ".cds", true) == 0)
            {
                e.Effect = DragDropEffects.Move;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

How to Solve ERROR: Java 1.7 or later is required to run Apache Drill

problem

Apache’s drill executes the startup command drill-embedded

Error: ERROR: Java 1.7 or later is required to run Apache Drill.

By java -versioncommand to view the version information is as follows:

java version "1.8.0_144"
Java(TM) SE Runtime Environment (build 1.8.0_144-b01)
Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed mode)

Solution

Open the bin directory of drill drill-config.shmodify the behavior of 396:

"$JAVA" -version 2>&1 | grep "version" | egrep -e "1/.4|1/.5|1/.6" > /dev/null

?the reason

Dril problem lies in the drill-config.shscript is a positive match jdk version, no decimal ‘.’ Escape.

reference

ERROR: Java 1.7 or later is required to run Apache Drill.

[Javac compilation exception] javac compilation prompts that the package in jdk cannot be found error: package jdk.internal.org.objectweb.asm does not exist and error: cannot find symbol

1. Steps to reproduce

1) Write the java class to be compiled

package f_asm_and_javassist;

import jdk. internal .org.objectweb.asm.* ;

import java.io. * ;

import static jdk. internal .org.objectweb.asm.Opcodes.ASM5;

/* *
 * @Author zhangboqing
 * @Date 2020/3/26
 */ 
public  class AsmDemo {

    // Methods and fields to access the class 
    public  static  void main(String[] args) {
         byte [] bytes = getBytes(); // Byte array of the MyMain.class file 
        ClassReader cr = new ClassReader(bytes);
        ClassWriter cw = new ClassWriter( 0 );
        ClassVisitor cv = new ClassVisitor(ASM5, cw) {
            @Override
            public FieldVisitor visitField( int access, String name, String desc, String signature, Object value) {
                System. out .println( " field: " + name);
                 return super.visitField(access, name, desc, signature, value);
            }

            @Override
            public MethodVisitor visitMethod( int access, String name, String desc, String signature, String[] exceptions) {
                System. out .println( " method: " + name);
                 return super.visitMethod(access, name, desc, signature, exceptions);
            }
        };
        cr.accept(cv, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG);
    }

    private  static  byte [] getBytes() {

        StringBuilder sb = new StringBuilder();
         try (FileInputStream fileInputStream = new FileInputStream( new File( " MyMain.class " ));
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream)) {

            byte [] buffer = new  byte [ 1024 * 8 ];
             while (bufferedInputStream.available()> 0 ) {

                int length = bufferedInputStream.read(buffer);
                sb.append( new String(buffer, 0 ,length) );
            }


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return sb.toString().getBytes();
    }
}

2) Use javac to compile in the current directory

 javac -d. AsmDemo.java

Prompt the following error:

➜ f_asm_and_javassist git:(master) ✗ javac- d. AsmDemo.java
AsmDemo.java: 3 : error: package jdk. internal .org.objectweb.asm does not exist
import jdk. internal .org.objectweb.asm.* ;
 ^ 
AsmDemo.java: 7 : error: package jdk. internal .org.objectweb.asm does not exist
import static jdk. internal .org.objectweb.asm.Opcodes.ASM5;
                                             ^ 
AsmDemo.java: 7 : error: static import only from classes and interfaces
import static jdk. internal .org.objectweb.asm.Opcodes.ASM5;
 ^ 
AsmDemo.java: 18 : error: cannot find symbol
        ClassReader cr = new ClassReader(bytes);
         ^ 
  symbol:    class ClassReader
  location: class AsmDemo
AsmDemo.java: 18 : error: cannot find symbol
        ClassReader cr = new ClassReader(bytes);
                              ^ 
  symbol:    class ClassReader
  location: class AsmDemo
AsmDemo.java: 19 : error: cannot find symbol
        ClassWriter cw = new ClassWriter( 0 );
         ^ 
  symbol:    class ClassWriter
  location: class AsmDemo
AsmDemo.java: 19 : error: cannot find symbol
        ClassWriter cw = new ClassWriter( 0 );
                              ^ 
  symbol:    class ClassWriter
  location: class AsmDemo
AsmDemo.java: 20 : error: cannot find symbol
        ClassVisitor cv = new ClassVisitor(ASM5, cw) {
         ^ 
  symbol:    class ClassVisitor
  location: class AsmDemo
AsmDemo.java: 20 : error: cannot find symbol
        ClassVisitor cv = new ClassVisitor(ASM5, cw) {
                               ^ 
  symbol:    class ClassVisitor
  location: class AsmDemo
AsmDemo.java: 20 : error: cannot find symbol
        ClassVisitor cv = new ClassVisitor(ASM5, cw) {
                                            ^
  symbol: variable ASM5
  location: class AsmDemo
AsmDemo.java: 33 : error: cannot find symbol
        cr.accept(cv, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG);
                       ^
  symbol: variable ClassReader
  location: class AsmDemo
AsmDemo.java: 33 : error: cannot find symbol
        cr.accept(cv, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG);
                                               ^
  symbol: variable ClassReader
  location: class AsmDemo
 12 errors

 

2. the solution

This is the limitation of javac. By default, javac will not read classes from rt.jar. It is read from a symbol file that contains only standard APIs and some internal APIs (such as com.sun., com.oracle. and sun. *).

To disable this mechanism, you can use javac -XDignore.symbol.file=true 

With maven, you can use:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <configuration>
    <compilerArgument>-XDignore.symbol.file</compilerArgument>
  </configuration>
</plugin>

The above problem can be successfully executed with the following command:

javac -XDignore.symbol.file=true -d. AsmDemo.java

For the class to be package name, you need to use -d., which means that the package path is automatically generated in the current directory