Category Archives: JAVA

How to Use filechannel to copy files

Filechannel is the content in javanio. Javanio (newio) is actually an IO multiplexing model. I won’t elaborate on this. If you want to know something about it, you can baidu.
This paper mainly uses buffer and channel in Java NiO to copy files.
The following is the code for copying the file:

package ch03;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
@Slf4j
public class FileCopy {
    private FileInputStream inputStream = null;
    private FileOutputStream outputStream = null;
    private FileChannel inChannel = null;
    private FileChannel outChannel = null;
    private double startTime;
    public void Copy(String src, String dest){
        startTime = System.currentTimeMillis();
        CopyFile(src,dest);
        log.info("the total time is " + (System.currentTimeMillis() - startTime) + "ms" );
    }

    private void CopyFile(String src,String dest){
        try {
            inputStream = new FileInputStream(new File(src));
            outputStream = new FileOutputStream(new File(dest));
            inChannel = inputStream.getChannel();
            outChannel = outputStream.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int readLength = -1;
            while (-1 != (readLength = inChannel.read(buffer))){
                buffer.flip();//Switching from read mode to write mode
                int outLength = 0;
                while (0 != (outLength = outChannel.write(buffer))){
                log.info("写入了 --->"+ outLength +"KB" );
                }
                buffer.clear();
            }
            outChannel.force(true);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
                outputStream.close();
                inChannel.close();
                outChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Springboot uses Oracle database to report property ‘sqlsessionfactory’ or ‘sqlsessiontemplate’ are required

The first time I used springboot to do a project, this mistake is very simple, but it took me more than two hours to solve it.!!

1. According to the Convention, write a test class to test whether the connection to the database is successful


import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;

@SpringBootTest
class SpringbootThymeleaf001ApplicationTests {

	//Test database connection
	@Autowired
	DataSource dataSource;
	@Test
	void contextLoads() throws Exception{
		System.out.println("The database connection obtained is :"+dataSource.getConnection());
	}

}

The connection was tested at the beginning and the connection was successful. Then, when I started the project, there was an error, so I turned back and tested the connection again, and even reported an error!! Nothing changed in the middle!
2. Solutions

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

Replace the above dependency with the following dependency, successfully solved!

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>1.2.0</version>
</dependency>

Flutter: How to Fix Android module can’t recognize flutter SDK source code

1. During the development of the flutter plug-in, when opening the Android project of the plug-in and preparing to write the native code, we found that all kinds of reports were red, the code could not jump, and the experience was very bad

The main reason is that the Android project does not rely on the flutter library and uses the local.properties In flutter.sdk Path to load

sdk.dir=C :/Users/11/AppData/Local/Android/ Sdkflutter.sdk=C :\src\flutter\flutter_ windows_ 1.22.6-stable\flutter

Finally, we’re on Android/ build.gradle File, write read flutter.sdk Finally, use compileonly files to rely on the local flutter library.

//Get the local.properties configuration file
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}
//Get the sdk path of flutter
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    compileOnly files("$flutterRoot/bin/cache/artifacts/engine/android-arm/flutter.jar")
    compileOnly 'androidx.annotation:annotation:1.1.0'
}

The new sync gradle is effective.

Resources is configured in the build of Maven project to prevent the failure of resource export

Since the convention in Maven is larger than the configuration we may run into the problem that the configuration file we write cannot be exported or valid.

<!--    Configure resources in build to prevent our resource export from failing-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

[How to Fix]Spring 3.0 could not find acceptable representation

When using Spring 3.0.5 MVC development, JSON interface data development, using JSONObject.fromobObject (Object) to return JSON data. Problems with “org. Springframework. Web. HttpMediaTypeNotAcceptableException: Could not find acceptable representation” error.

Solution 1:
The @responseBody method’s return type is changed from JSONObject to Object.
Modify SpringMVC-servlet.xml to add MessageConverters

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<!-- Object->json -->
<property name="messageConverters"> 
<list> 
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /> 
</list> 
</property> 
</bean>

JacksonJar package support is required: jackson-core-lgpl-1.2.1.jar and jackson-core-lgpl-1.2.1.jar.

Solution 2:
The @responseBody method returns a String instead of a JSONObject, and returns JSONObject.fromobObject (Object).toString();
At this time, if there is Chinese, there will be garbled code, the solution is as follows:

 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
	    <!-- Object->json -->
	    <!-- <property name="messageConverters">  
		    <list>  
		         <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />  
		    </list>   
	    </property> -->
	    <!-- default is ISO you should set utf-8 -->
	    <property name="messageConverters">  
        <list>  
            <bean  
                class="org.springframework.http.converter.StringHttpMessageConverter">  
                <property name="supportedMediaTypes">  
                    <list>  
                        <bean class="org.springframework.http.MediaType">  
                            <constructor-arg index="0" value="text" />  
                            <constructor-arg index="1" value="plain" />  
                            <constructor-arg index="2" value="UTF-8" />  
                        </bean>  
                    </list>  
                </property>  
            </bean>  
        </list>  
    </property>  
    </bean>

Solution 3:
The return type is JSONObject. Write your own Converter.

package javacommon.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.Charset;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

public class JaksonConverter extends AbstractHttpMessageConverter<Object> {
	public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
	
	public JaksonConverter() {
		super(new MediaType("application", "json", DEFAULT_CHARSET));
	}
	
	@Override
	protected boolean supports(Class<?> clazz) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected Object readInternal(Class<?extends Object> clazz,
			HttpInputMessage inputMessage) throws IOException,
			HttpMessageNotReadableException {
		logger.info(clazz.getSimpleName());
		InputStream inputStream=inputMessage.getBody();
		StringBuilder stringBuilder = new StringBuilder();
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
		String line = null; 
		while((line = bufferedReader.readLine()) != null){
			stringBuilder.append(line);
		}
		logger.info(stringBuilder.toString());
		return stringBuilder;
	}

	@Override
	protected void writeInternal(Object t, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {
		logger.info(t.getClass().getSimpleName());
		
		// HashMap
		// JSONObject
		logger.info(t.toString());
		OutputStream os=outputMessage.getBody();
		 
		os.write(t.toString().getBytes("utf-8")); 
		os.flush();
		
	}

}

Replace the Converter in Scenario 1 with a written one.

Maven project running servlet jump JSP error: HTTP status 500 – unable to compile class for JSP

Runtime environment: JDK1.8 + Tomcat 6.0. x (maven comes with)

1. Error details

exception:
org.apache.jasper. JasperException: Unable to compile class for JSP:
An error occurred at line: 1 in the generated java file
The type java.io. ObjectInputStream cannot be resolved. It is indirectly referenced from required .class files…


Look at the console error again

2. the cause of the problem:
maven use skeleton to create web projects, the default tomcat is 6.0, tomcat version is too low or jdk version is high.
3. problem solving:
Method 1: Use a high version of tomcat. Method 2: Use a lower version of jdk. I was using jdk1.8, the results reported an error. After replacing jdk1.7, it ran successfully without errors.

Run successfully:

Java: How to Find the Minimum Value from a Random Array by Bubble Sort Method

public class HelloWorld{
  public static void main(String[] args){
	  int[] a = new int[5];
      a[0] = (int) (Math.random() * 100);
      a[1] = (int) (Math.random() * 100);
      a[2] = (int) (Math.random() * 100);
      a[3] = (int) (Math.random() * 100);
      a[4] = (int) (Math.random() * 100);
       
      System.out.println("The individual random numbers in the array are :");
      for (int i = 0; i < a.length; i++)
          System.out.println(a[i]);
       
      System.out.println("bubble sorting method: (compare two by two, put the bigger one behind)");
      for (int j = 0; j < a.length; j++) {
          for (int i = 0; i < a.length-j-1; i++) {
              if(a[i]>a[i+1]){  
                  int temp = a[i];
                  a[i] = a[i+1];
                  a[i+1] = temp;
              }
          }
      }
      System.out.println("the minimum number is"+a[0]);
  }
}

Exception information: jsonmappingexception: out of start_ ARRAY token

JsonMappingException: out of START_ARRAY token
How to Fix this error
Json

[
  {
    "id": 4,
    "dmNum": "111102",
    "number": "683272",
    "parentNum": "0",
    "type": "1",
    "name": "dashen",
    "code": "213134",
    "mDefault": "37",
    "description": "please ask",
    "isDel": "0",
    "opFlag": "A",
    "createdBy": "creator",
    "createdTime": "2020-10-15T05:20:17.000+0000",
    "updatedBy": "deleter",
    "updatedTime": "2020-10-15T05:28:18.000+0000",
    "children": null,
    "parentName": null
  },
  {
    "id": 5,
    "dmNum": "111102",
    "number": "68327201",
    "parentNum": "683272",
    "type": "0",
    "name": "temperature data",
    "code": "213135",
    "mDefault": "95",
    "description": "I dont know",
    "isDel": "0",
    "opFlag": "A",
    "createdBy": "creator",
    "createdTime": "2020-10-15T05:20:18.000+0000",
    "updatedBy": "deleter",
    "updatedTime": "2020-10-15T05:27:33.000+0000",
    "children": null,
    "parentName": null
  }
]

Create ObjectMapper

    public static ObjectMapper mapper = new ObjectMapper();

    static {
        // Convert to formatted json
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        // If there are new fields in the json that do not exist in the entity class, no error will be reported
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // Modify date format
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

Java code:

String s1 = httpAPIService
                    .doGet("http://192.168.0.25:8888/modeloutput/selectOutputByModelId?mid=" + mid);
            ModelOutput[] modelOutput =  mapper.readValue(s1, ModelOutput[].class);//Output Table Object
            for (ModelOutput output : modelOutput) {
                //Assignment: metadata number
                deviceOutput.setMetaNum(output.getNumber());
                //Assignment; data encoding
                deviceOutput.setCode(output.getOutputCode());
                deviceOutputMapper.save(deviceOutput);
                System.out.println(deviceOutput);
            }

The outermost layer of this string of JSON data is [], which represents an array of objects, because the Jackson Object Mapper is converting the returned JSON fragment into an object.
Convert to an array object

ModelOutput[] modelOutput =  mapper.readValue(s1, ModelOutput[].class);

Iterate through the data in the array. Convert to a Java object.
idea shortcut key: iter

for (ModelOutput output : modelOutput) {
                //Assignment: metadata number
                deviceOutput.setMetaNum(output.getNumber());
                //Assignment; data encoding
                deviceOutput.setCode(output.getOutputCode());
                deviceOutputMapper.save(deviceOutput);
                System.out.println(deviceOutput);
            }

Done!

Build a mybatis and it will appear session.selectOne Method error

Error:

org.apache.ibatis.exceptions.PersistenceException:
### Error querying database.   Cause: java.lang. IllegalArgumentException: Mapped Statements collection does not contain value for com.helloword.mapper.UserMapper.xml
### Cause: java.lang. IllegalArgumentException: Mapped Statements collection does not contain value for com.helloword.mapper.UserMapper.xml
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:150)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:77)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:71)
at test.Test.main(Test.java:43)
Caused by: java.lang. IllegalArgumentException: Mapped Statements collection does not contain value for com.helloword.mapper.UserMapper.xml
at org.apache.ibatis.session.Configuration$StrictMap.get(Configuration.java:888)
at org.apache.ibatis.session.Configuration.getMappedStatement(Configuration.java:721)
at org.apache.ibatis.session.Configuration.getMappedStatement(Configuration.java:714)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:147)
… 4 more

Solution.

See the error message, guess that it may be because there is a problem with the configuration file, first see if the <mapper> configuration in mybatis-config.xml is correct, see if there is no problem with the <mapper> configuration see if the path of namespace in UserMapper.xml is correct, check if there is no problem with UerMapper. xml is in the package of com.helloword.mapper, but this package is empty. Move the mapping file of UserMapper.xml to the package of entity class, and modify the configuration in one and two. After testing, the above error is still reported.

New error message

org.apache.ibatis.exceptions.PersistenceException:
### Error building SqlSession.
### The error may exist in com/helloworld/model/UserMapper.xml
### Cause: org.apache.ibatis.builder. BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io. IOException: Could not find resource com/helloworld/model/UserMapper.xml
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:52)
at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:36)
at test.Test.<clinit>(Test.java:30)
Caused by: org.apache.ibatis.builder. BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io. IOException: Could not find resource com/helloworld/model/UserMapper.xml
at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:121)
at org.apache.ibatis.builder.xml.XMLConfigBuilder.parse(XMLConfigBuilder.java:99)
at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:50)
… 2 more
Caused by: java.io. IOException: Could not find resource com/helloworld/model/UserMapper.xml
at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:114)
at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:100)
at org.apache.ibatis.builder.xml.XMLConfigBuilder.mapperElement(XMLConfigBuilder.java:371)
at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:119)
… 4 more
Exception in thread “main” java.lang.NullPointerException
at test.Test.main(Test.java:41)

The error was: Problem creating SqlSession and reported a null pointer error for the main method. Solution: I was careless and wrote a wrong letter in the <mapper> configuration path of mybatis configuration file

MDK keil template annotation template

When you write a program, you tend to follow certain norms. Good code style can improve the readability of the code, easy to maintain and upgrade. Here are some comment templates that mimic the code style of the STM32 official HAL library source code.
1. Add user comment template to MDK

2. Use some code comment templates
Void bsp_dac1_Init(void) {void bsp_dac1_Init(void) {void bsp_dac1_Init(void) {void bsp_dac1_Init(void);

 /** @defgroup BSP_DAC_Driver
   * @brief xxx driver modules
   * @{
   */ 
     void bsp_dac1_Init(void);
 /** 
   * @}
   */

void bsp_dac2_Init(void) is added to the BSP_DAC_Driver group.

   /** @addtogroup BSP_DAC_Driver 
     * @{
     */
       void bsp_dac2_Init(void);
   /** 
     * @}
     */

2.3 use formal code comments mode can enhance code can read a gender, use the following statement can be more comprehensive description.
@brief
te
@p>
@retval>>@retval
@brief
@brief
@note
@param
@retval
@retval

/**
  * @brief  Stop ADC data switch
  * @note   NONE
  * @param  NONE
  * @retval NONE
  */
void bsp_adc1_stop(void)
{
  ///
}

3, summarize
MDK’s Template function makes it easy to add a user’s code comment Template, improve the quality of the code, and facilitate subsequent maintenance and upgrade.

Springdatajpa @query with like @param

Direct to the code

//Using :name this way must be added, cut @Param is org.springframework.data.repository.query.Param package below the note
    @Query(nativeQuery = true, value = "select a.id,a.name,a.code,a.age,b.age as sub_age from dog a inner join dog b  on a.age = b.age where a.name like concat('%',:name ,'%')")
    List<Dog> findAllByAgeAfter2(@Param("name") String name);

    //The use of ?1 does not require the addition of @Param, and the addition of @Param does not affect
    @Query(nativeQuery = true, value = "select a.id,a.name,a.code,a.age,b.age as sub_age from dog a inner join dog b  on a.age = b.age where a.name like  CONCAT('%',?1,'%')")
    List<Dog> findAllByAgeAfter(String name);

The test is as follows:

I hope I can help you, thank you!

Java back end receives localdatetime type parameter

//QTO layer

    @ApiModelProperty("Billing start time")
    @JsonFormat(shape = JsonFormat.Shape.STRING,pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private LocalDateTime billStartTime;
    
    @ApiModelProperty("Billing end time")
    @JsonFormat(shape = JsonFormat.Shape.STRING,pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private LocalDateTime billEndTime;

@requestBody
@apiOperation (” list”)
stMapping (“/list”)
p>c responseData< PageData< TradeSettlementVO.ListVO> > list(@RequestBody TradeSettlementQTO.PcQTO qto){
return ResponseData.data(ipcMarketSettlementRpc.settlementPageData(qto));
}