Commit ce55671f authored by 张永's avatar 张永
parents 6f644eb1 2a73609a
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.egolm</groupId>
<artifactId>common</artifactId>
<version>0.0.1-RELEASE</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.3.RELEASE</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-full</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.5.0-b01</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk16</artifactId>
<version>1.46</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.egolm</groupId>
<artifactId>common</artifactId>
<version>0.0.1-RELEASE</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.3.RELEASE</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-full</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.5.0-b01</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk16</artifactId>
<version>1.46</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
......@@ -14,7 +14,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
......@@ -363,18 +362,23 @@ public class FileUtil {
public static byte[] streamToBytes(InputStream instream) {
byte[] bytes = null;
ByteArrayOutputStream baos = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream(102400);
baos = new ByteArrayOutputStream(102400);
byte[] b = new byte[102400];
int n;
while ((n = instream.read(b)) != -1) {
baos.write(b, 0, n);
}
instream.close();
baos.close();
bytes = baos.toByteArray();
} catch (Exception e) {
throw new FileUtilException("将输入流转换为字节数组异常", e);
} finally {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return bytes;
}
......@@ -549,30 +553,6 @@ public class FileUtil {
}
/**
*
* @Title: inputStreamToFile
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param: @param ins
* @param: @param file
* @return: void
* @throws
*/
public static void inputStreamToFile(InputStream ins,File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Object fileToObject(File file) {
FileInputStream fis = null;
ObjectInputStream ois = null;
......
package com.egolm.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPSClient;
/**
* FTP工具类
* @author 曲欣亮
* @since 2015-04-01
*
*/
public class FtpUtil {
private static final String fx = ".FTPDOWNLOAD$QUXL@DNE#COM#CN";
public final FTPClient ftpClient;
private final String ip;
private final int port;
private final String username;
private final String password;
public static final ExecutorService pool = Executors.newFixedThreadPool(3);
public static FtpUtil newInstance(String ip, int port, String username, String password, boolean ftps) throws SocketException, IOException {
return new FtpUtil(ip, port, username, password, ftps);
}
public void disconnect() throws IOException {
ftpClient.disconnect();
}
private FtpUtil(String ip, int port, String username, String password, boolean ftps) throws SocketException, IOException {
this.ip = ip;
this.port = port;
this.username = username;
this.password = password;
if(ftps) {
this.ftpClient = new FTPSClient();
} else {
this.ftpClient = new FTPClient();
}
this.ftpClient.connect(ip, port);
this.ftpClient.login(username, password);
this.ftpClient.setControlEncoding("UTF-8");
this.ftpClient.setFileType(FTP.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE);
this.ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
this.ftpClient.enterLocalPassiveMode();
}
public void downFolder(final String localRootPath, final String remoteRootPath, boolean async, String backupRootPath) throws IOException {
File localFolder = new File(localRootPath);
if(!localFolder.exists()) {
localFolder.mkdirs();
}
FTPFile[] listFiles = ftpClient.listFiles(remoteRootPath);
for(int i = listFiles.length - 1; i >= 0; i--) {
downFolder(listFiles[i], localRootPath, remoteRootPath, async, backupRootPath);
}
}
private void downFolder(final FTPFile entry, final String localRootPath, final String remoteRootPath, boolean async, String backupRootPath) throws IOException {
String entryName = entry.getName();
String localPath = localRootPath + File.separator + entryName;
String remotePath = remoteRootPath + "/" + entryName;
String backupPath = backupRootPath == null ? null : (backupRootPath + "/" + entryName);
if(entry.isDirectory()) {
File file = new File(localPath);
if(!file.exists()) {
file.mkdirs();
}
FTPFile[] listFiles = ftpClient.listFiles(remotePath);
for(int i = listFiles.length - 1; i >= 0; i--) {
downFolder(listFiles[i], localPath, remotePath, async, backupPath);
}
} else {
downFile(remotePath, localPath, async, backupPath);
}
}
public void downFile(final String remoteFullName, final String localFullName, boolean async, final String backupFullName) throws FileNotFoundException, IOException {
final File localFile = new File(localFullName);
if(!localFile.exists() || localFile.isDirectory()) {
if(async) {
Thread thread = new Thread() {
public void run() {
System.out.println("FTPDownload>>Async>>FTP://" + username + "@" + ip + ":" + port + remoteFullName + ">>" + localFullName);
String tempFileName = localFullName + fx;
File file = new File(tempFileName);
OutputStream os = null;
FtpUtil ftp = null;
try {
os = new FileOutputStream(file);
ftp = FtpUtil.newInstance(ip, port, username, password, false);
ftp.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.ftpClient.retrieveFile(remoteFullName, os);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
os.close();
if(StringUtil.isNotEmpty(backupFullName)) {
String[] names = backupFullName.substring(1).split("/");
String p_name = "";
for(int i = 0; i < names.length - 1; i++) {
p_name = p_name + "/" + names[i];
try {
ftp.ftpClient.makeDirectory(p_name);
} catch (Exception e) {
System.out.println(e);
}
}
}
ftp.ftpClient.rename(remoteFullName, backupFullName);
ftp.ftpClient.disconnect();
FileUtil.fileMove(file, localFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
pool.execute(thread);
} else {
System.out.println("FTPDownload>>Sync>>" + remoteFullName + ">>" + localFullName);
String tempFileName = localFullName + fx;
File file = new File(tempFileName);
ftpClient.retrieveFile(remoteFullName, new FileOutputStream(file));
if(StringUtil.isNotEmpty(backupFullName)) {
ftpClient.rename(remoteFullName, backupFullName);
}
FileUtil.fileMove(file, new File(localFullName));
}
} else {
System.out.println("File exists already: " + localFullName);
}
}
public void downFile(final String remoteFullName, final OutputStream os) throws FileNotFoundException, IOException {
try {
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.retrieveFile(remoteFullName, os);
} finally {
os.close();
ftpClient.disconnect();
}
}
public void uploadFile(InputStream is, String remoteFullPath) throws IOException {
String[] names = remoteFullPath.substring(1).split("/");
String p_name = "";
for (int i = 0; i < names.length - 1; i++) {
p_name = p_name + "/" + names[i];
try {
ftpClient.makeDirectory(p_name);
} catch (Exception e) {
System.out.println(e);
}
}
ftpClient.storeFile(remoteFullPath, is);
}
public void uploadFolder(String localFileName, String remoteFullPath) throws IOException {
File localFile = new File(localFileName);
if(localFile.isFile()) {
InputStream is = new FileInputStream(localFile);
ftpClient.storeFile(remoteFullPath, is);
is.close();
} else {
String[] names = remoteFullPath.substring(1).split("/");
String p_name = "";
for(int i = 0; i < names.length; i++) {
p_name = p_name + "/" + names[i];
try {ftpClient.makeDirectory(p_name);} catch (Exception e) {}
}
ftpClient.changeWorkingDirectory(remoteFullPath);
File[] fs = localFile.listFiles();
if(fs != null) {
for(File childFile : fs) {
String childFileFullName = localFile.getAbsolutePath() + File.separator + childFile.getName();
String remoteChildFullPath = remoteFullPath + "/" + childFile.getName();
uploadFolder(childFileFullName, remoteChildFullPath);
}
}
}
}
public static void main(String[] args) throws Exception {
FtpUtil ftp = FtpUtil.newInstance("10.10.0.67", 21, "egomedia", "egomedia", false);
//ftp.uploadFolder("D:\\logs\\FH_log", "/");
//ftp.uploadFile(new FileInputStream("D:\\logs\\FH_log\\PurePro_"), "/a");
ftp.downFile("/456/RSAUtil.java", new FileOutputStream(new File("d:/a.java")));
}
}
package com.egolm.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPSClient;
/**
* FTP工具类
* @author 曲欣亮
* @since 2015-04-01
*
*/
public class FtpUtil {
private static final String fx = ".FTPDOWNLOAD$QUXL@DNE#COM#CN";
public final FTPClient ftpClient;
private final String ip;
private final int port;
private final String username;
private final String password;
public static final ExecutorService pool = Executors.newFixedThreadPool(3);
public static FtpUtil newInstance(String ip, int port, String username, String password, boolean ftps) throws SocketException, IOException {
return new FtpUtil(ip, port, username, password, ftps);
}
public void disconnect() throws IOException {
ftpClient.disconnect();
}
private FtpUtil(String ip, int port, String username, String password, boolean ftps) throws SocketException, IOException {
this.ip = ip;
this.port = port;
this.username = username;
this.password = password;
if(ftps) {
this.ftpClient = new FTPSClient();
} else {
this.ftpClient = new FTPClient();
}
this.ftpClient.connect(ip, port);
this.ftpClient.login(username, password);
this.ftpClient.setControlEncoding("UTF-8");
this.ftpClient.setFileType(FTP.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE);
this.ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
this.ftpClient.enterLocalPassiveMode();
}
public void downFolder(final String localRootPath, final String remoteRootPath, boolean async, String backupRootPath) throws IOException {
File localFolder = new File(localRootPath);
if(!localFolder.exists()) {
localFolder.mkdirs();
}
FTPFile[] listFiles = ftpClient.listFiles(remoteRootPath);
for(int i = listFiles.length - 1; i >= 0; i--) {
downFolder(listFiles[i], localRootPath, remoteRootPath, async, backupRootPath);
}
}
private void downFolder(final FTPFile entry, final String localRootPath, final String remoteRootPath, boolean async, String backupRootPath) throws IOException {
String entryName = entry.getName();
String localPath = localRootPath + File.separator + entryName;
String remotePath = remoteRootPath + "/" + entryName;
String backupPath = backupRootPath == null ? null : (backupRootPath + "/" + entryName);
if(entry.isDirectory()) {
File file = new File(localPath);
if(!file.exists()) {
file.mkdirs();
}
FTPFile[] listFiles = ftpClient.listFiles(remotePath);
for(int i = listFiles.length - 1; i >= 0; i--) {
downFolder(listFiles[i], localPath, remotePath, async, backupPath);
}
} else {
downFile(remotePath, localPath, async, backupPath);
}
}
public void downFile(final String remoteFullName, final String localFullName, boolean async, final String backupFullName) throws FileNotFoundException, IOException {
final File localFile = new File(localFullName);
if(!localFile.exists() || localFile.isDirectory()) {
if(async) {
Thread thread = new Thread() {
public void run() {
System.out.println("FTPDownload>>Async>>FTP://" + username + "@" + ip + ":" + port + remoteFullName + ">>" + localFullName);
String tempFileName = localFullName + fx;
File file = new File(tempFileName);
OutputStream os = null;
FtpUtil ftp = null;
try {
os = new FileOutputStream(file);
ftp = FtpUtil.newInstance(ip, port, username, password, false);
ftp.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.ftpClient.retrieveFile(remoteFullName, os);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
os.close();
if(StringUtil.isNotEmpty(backupFullName)) {
String[] names = backupFullName.substring(1).split("/");
String p_name = "";
for(int i = 0; i < names.length - 1; i++) {
p_name = p_name + "/" + names[i];
try {
ftp.ftpClient.makeDirectory(p_name);
} catch (Exception e) {
System.out.println(e);
}
}
}
ftp.ftpClient.rename(remoteFullName, backupFullName);
ftp.ftpClient.disconnect();
FileUtil.fileMove(file, localFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
pool.execute(thread);
} else {
System.out.println("FTPDownload>>Sync>>" + remoteFullName + ">>" + localFullName);
String tempFileName = localFullName + fx;
File file = new File(tempFileName);
ftpClient.retrieveFile(remoteFullName, new FileOutputStream(file));
if(StringUtil.isNotEmpty(backupFullName)) {
ftpClient.rename(remoteFullName, backupFullName);
}
FileUtil.fileMove(file, new File(localFullName));
}
} else {
System.out.println("File exists already: " + localFullName);
}
}
public void downFile(final String remoteFullName, final OutputStream os) throws FileNotFoundException, IOException {
try {
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.retrieveFile(remoteFullName, os);
} finally {
os.close();
ftpClient.disconnect();
}
}
public void uploadFile(InputStream is, String remoteFullPath) throws IOException {
String[] names = remoteFullPath.substring(1).split("/");
String p_name = "";
for (int i = 0; i < names.length - 1; i++) {
p_name = p_name + "/" + names[i];
try {
ftpClient.makeDirectory(p_name);
} catch (Exception e) {
System.out.println(e);
}
}
ftpClient.storeFile(remoteFullPath, is);
}
public void uploadFolder(String localFileName, String remoteFullPath) throws IOException {
File localFile = new File(localFileName);
if(localFile.isFile()) {
InputStream is = new FileInputStream(localFile);
ftpClient.storeFile(remoteFullPath, is);
is.close();
} else {
String[] names = remoteFullPath.substring(1).split("/");
String p_name = "";
for(int i = 0; i < names.length; i++) {
p_name = p_name + "/" + names[i];
try {ftpClient.makeDirectory(p_name);} catch (Exception e) {}
}
ftpClient.changeWorkingDirectory(remoteFullPath);
File[] fs = localFile.listFiles();
if(fs != null) {
for(File childFile : fs) {
String childFileFullName = localFile.getAbsolutePath() + File.separator + childFile.getName();
String remoteChildFullPath = remoteFullPath + "/" + childFile.getName();
uploadFolder(childFileFullName, remoteChildFullPath);
}
}
}
}
public static void main(String[] args) throws Exception {
FtpUtil ftp = FtpUtil.newInstance("10.10.0.67", 21, "egomedia", "egomedia", false);
//ftp.uploadFolder("D:\\logs\\FH_log", "/");
//ftp.uploadFile(new FileInputStream("D:\\logs\\FH_log\\PurePro_"), "/a");
ftp.downFile("/456/RSAUtil.java", new FileOutputStream(new File("d:/a.java")));
}
}
......@@ -13,6 +13,7 @@ import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
......@@ -104,8 +105,8 @@ public class HttpUtil {
System.out.println(requestUrl);
connection = createConnection(requestUrl, proxy);
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//connection.setRequestProperty("Accept-Charset", charset);
//connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (header != null) {
for (String key : header.keySet()) {
connection.setRequestProperty(key, header.get(key));
......@@ -177,6 +178,7 @@ public class HttpUtil {
try {
bytes = FileUtil.streamToBytes(connection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
bytes = FileUtil.streamToBytes(connection.getErrorStream());
}
Map<String, List<String>> responseHeaders = connection.getHeaderFields();
......@@ -258,8 +260,7 @@ public class HttpUtil {
for (Object key : parameters.keySet()) {
Object val = parameters.get(key);
String sKey = String.valueOf(key);
Object[] sVals = (val == null ? null
: (val instanceof Object[] ? (Object[]) val : new Object[] { val }));
Object[] sVals = (val == null ? null : (val instanceof Object[] ? (Object[]) val : (val instanceof Collection<?> ? ((Collection<?>)val).toArray() : new Object[] { val })));
if (sVals != null && sVals.length > 0) {
for (Object sVal : sVals) {
if(StringUtil.isNotEmpty(sVal)) {
......
......@@ -1001,7 +1001,8 @@ public class StringUtil {
public static String[] searchNumber(String string) {
List<String> numbers = new ArrayList<String>();
Pattern pattern = Pattern.compile("[\\d]+(\\.?[\\d]+)?");
String regexText = "\\d+(\\.\\d+)?";
Pattern pattern = Pattern.compile(regexText);
Matcher matcher = pattern.matcher(string);
while(matcher.find()) {
numbers.add(matcher.group(0));
......
package com.egolm.common.jdbc;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.CallableStatementCallback;
import org.springframework.jdbc.core.CallableStatementCreator;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import com.egolm.common.DateUtil;
import com.egolm.common.ReflexUtil;
import com.egolm.common.StringUtil;
import com.egolm.common.Util;
import com.egolm.common.jdbc.dialect.Dialect;
import com.egolm.common.jdbc.dialect.bean.Desc;
import com.egolm.common.jdbc.dialect.bean.Sql;
import com.egolm.common.jdbc.exception.MustBeOneRowException;
import com.egolm.common.jdbc.exception.QueryArgsException;
public class JdbcTemplate extends org.springframework.jdbc.core.JdbcTemplate {
protected Dialect dialect;
protected int sql_level = 2;
public JdbcTemplate() {
super();
}
public JdbcTemplate(DataSource dataSource, boolean lazyInit) {
super(dataSource, lazyInit);
}
public JdbcTemplate(DataSource dataSource) {
super(dataSource);
}
public int executeUpdate(String sql, Object... args) {
showSql(sql, args);
return super.update(sql, args);
}
public Map<String, Object> queryForMap(String sql, Object... args) {
showSql(sql, args);
return super.queryForMap(sql, args);
}
public List<Map<String, Object>> queryForList(String sql, Object... args) {
showSql(sql, args);
return super.queryForList(sql, args);
}
public int queryForInt(String sql, Object... args) {
showSql(sql, args);
return super.queryForObject(sql, Integer.class, args);
}
public long queryForLong(String sql, Object... args) {
showSql(sql, args);
return super.queryForObject(sql, Long.class, args);
}
public String queryForString(String sql, Object... args) {
showSql(sql, args);
return super.queryForObject(sql, String.class, args);
}
public Double queryForDouble(String sql, Object... args) {
showSql(sql, args);
return super.queryForObject(sql, Double.class, args);
}
public Date queryForDate(String sql, Object... args) {
showSql(sql, args);
return super.queryForObject(sql, Date.class, args);
}
public Boolean queryForBoolean(String sql, Object... args) {
showSql(sql, args);
return super.queryForObject(sql, Boolean.class, args);
}
public <T> T queryForObject(String sql, Class<T> type, Object... args) {
showSql(sql, args);
return super.queryForObject(sql, type, args);
}
public <T> List<T> queryForObjects(String sql, Class<T> type, Object... args) {
List<Map<String, Object>> list = queryForList(sql, args);
List<T> objs = new ArrayList<T>();
for (Map<String, Object> map : list) {
for (String key : map.keySet()) {
objs.add(Util.objTo(map.get(key), type));
}
}
return objs;
}
public int[] batchUpdate(String sql, List<Object[]> args) {
showSql(sql, args.toArray());
return super.batchUpdate(sql, args);
}
public int saveOrUpdate(Object obj) {
Desc desc = dialect.getDesc(obj.getClass());
String[] byFields = desc.getFieldPkNames();
Map<String, Object> pkFieldMap = dialect.getFieldValue(obj, byFields);
if(dialect.hasPkValue(obj) && pkFieldMap != null && pkFieldMap.size() > 0) {
List<Map<String, Object>> objMaps = queryForListByColumn(desc.getName(), pkFieldMap);
if(objMaps != null) {
if(objMaps.size() == 1) {
return this.update(obj);
} else if(objMaps.size() > 1) {
throw new MustBeOneRowException();
} else {
return this.save(obj);
}
} else {
return this.save(obj);
}
} else {
return this.save(obj);
}
}
public Map<String, Object> queryForMapByColumn(String tableName, Map<String, Object> byColumns) {
Sql iSql = dialect.argsQuery(tableName, byColumns);
return this.queryForMap(iSql.getSql(), iSql.getArgs());
}
public List<Map<String, Object>> queryForListByColumn(String tableName, Map<String, Object> byColumns) {
Sql iSql = dialect.argsQuery(tableName, byColumns);
return this.queryForList(iSql.getSql(), iSql.getArgs());
}
public Map<String, Object> queryForMapByField(Object obj, String... byFields) {
Desc desc = dialect.getDesc(obj.getClass());
Sql iSql = dialect.argsQuery(desc.getName(), dialect.getColumnValueByField(obj, byFields));
return this.queryForMap(iSql.getSql(), iSql.getArgs());
}
public List<Map<String, Object>> queryForListByField(Object obj, String... byFields) {
Desc desc = dialect.getDesc(obj.getClass());
Sql iSql = dialect.argsQuery(desc.getName(), dialect.getColumnValueByField(obj, byFields));
return this.queryForList(iSql.getSql(), iSql.getArgs());
}
public Map<String, Object> queryForMapByObject(Object obj) {
Desc desc = dialect.getDesc(obj.getClass());
Sql iSql = dialect.argsQuery(desc.getName(), dialect.getColumnValueByField(obj, desc.getFieldPkNames()));
return queryForMap(iSql.getSql(), iSql.getArgs());
}
public <T> T queryById(Class<T> type, Object... vals) {
Desc desc = dialect.getDesc(type);
String[] fieldPkNames = desc.getFieldPkNames();
if(vals == null || vals.length == 0 || vals.length != fieldPkNames.length) {
throw new QueryArgsException();
} else {
Map<String, Object> map = new HashMap<String, Object>();
for(int i = 0; i < vals.length; i++) {
map.put(fieldPkNames[i], vals[i]);
}
Sql iSql = dialect.argsQuery(desc.getName(), map);
return queryForBean(iSql.getSql(), type, iSql.getArgs());
}
}
public <T> T queryByObject(T obj) {
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>)obj.getClass();
Desc desc = dialect.getDesc(clazz);
Sql iSql = dialect.argsQuery(desc.getName(), dialect.getColumnValueByField(obj, desc.getFieldPkNames()));
return queryForBean(iSql.getSql(), clazz, iSql.getArgs());
}
public int merge(Object... objs) {
int count = 0;
for(Object obj : objs) {
Desc iSql = dialect.getDesc(obj.getClass());
count += mergeByField(obj, iSql.getFieldPkNames());
}
return count;
}
public int mergeByField(Object obj, String... byFields) {
Desc iSql = dialect.getDesc(obj.getClass());
Map<String, Object> pkFieldMap = dialect.getFieldValue(obj, byFields);
if(dialect.hasPkValue(obj) && pkFieldMap != null && pkFieldMap.size() > 0) {
List<Map<String, Object>> objMaps = this.queryForListByColumn(iSql.getName(), pkFieldMap);
if(objMaps != null) {
if(objMaps.size() == 1) {
Map<String, Object> map = new HashMap<String, Object>();
Field[] fields = obj.getClass().getDeclaredFields();
for(Field field : fields) {
int mod = field.getModifiers();
if(!Modifier.isStatic(mod) && !Modifier.isFinal(mod)) {
Object fieldValue = ReflexUtil.getFieldValue(field, obj);
if(fieldValue != null) {
map.put(field.getName(), fieldValue);
}
}
}
return this.updateByColumn(iSql.getName(), iSql.getColumnPkNames(), map);
} else if(objMaps.size() > 1) {
throw new MustBeOneRowException();
} else {
return this.save(obj);
}
} else {
return this.save(obj);
}
} else {
return this.save(obj);
}
}
public int save(Object... objs) {
int save_count = 0;
for (Object obj : objs) {
final Sql iSql = dialect.argsInsert(obj);
Desc desc = dialect.getDesc(obj.getClass());
showSql(iSql.getSql(), iSql.getArgs());
KeyHolder keyHolder = new GeneratedKeyHolder();
save_count += super.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(iSql.getSql(), Statement.RETURN_GENERATED_KEYS);
Object[] args = iSql.getArgs();
for(int i = 0; i <args.length; i++) {
Object argObj = args[i];
if(argObj instanceof java.util.Date) {
java.util.Date argDate = (java.util.Date)argObj;
ps.setObject(i+1, new java.sql.Timestamp(argDate.getTime()));
} else if(argObj.getClass().isEnum()) {
ps.setObject(i+1, args[i].toString());
} else {
ps.setObject(i+1, args[i]);
}
}
return ps;
}
}, keyHolder);
String[] pks = desc.getFieldPkNames();
if(pks != null && pks.length > 0) {
if(ReflexUtil.readField(pks[0], obj) == null) {
Object key = keyHolder.getKey();
try {
ReflexUtil.writeField(pks[0], obj, key);
} catch (ClassCastException e) {
throw new RuntimeException("设置自增主键:field=" + pks[0] + ",value=" + key + ",class=" + key.getClass() + "错误");
}
}
}
}
return save_count;
}
public int save(String tableName, Map<String, Object> objMap) {
Sql desc = dialect.argsInsert(tableName, objMap);
int save_count = this.executeUpdate(desc.getSql(), desc.getArgs());
return save_count;
}
public int delete(Object... objs) {
int delete_count = 0;
for (Object obj : objs) {
Sql desc = dialect.argsDelete(obj);
delete_count += this.executeUpdate(desc.getSql(), desc.getArgs());
}
return delete_count;
}
public int batchDelete(Object... objs) {
Sql desc = dialect.batchDelete(objs);
int[] counts = this.batchUpdate(desc.getSql(), desc.getBachArgs());
int countSum = 0;
for(int count : counts) {
countSum += count;
}
return countSum;
}
public int batchDelete(List<Object> objs) {
return this.batchDelete(objs.toArray());
}
public int deleteByField(Object obj, String... byFields) {
Desc desc = dialect.getDesc(obj.getClass());
Map<String, Object> columnsMap = dialect.getColumnValueByField(obj, byFields);
return this.delete(desc.getName(), columnsMap);
}
public int delete(String tableName, String columnName, Object columnValue) {
Sql desc = dialect.argsDelete(tableName, columnName, columnValue);
return this.executeUpdate(desc.getSql(), desc.getArgs());
}
public int delete(String tableName, Map<String, Object> objMap) {
Sql desc = dialect.argsDelete(tableName, objMap);
return this.executeUpdate(desc.getSql(), desc.getArgs());
}
public int update(Object... objs) {
int update_count = 0;
for (Object obj : objs) {
Sql desc = dialect.argsUpdate(obj);
update_count += this.executeUpdate(desc.getSql(), desc.getArgs());
}
return update_count;
}
public int updateByColumn(String tableName, String[] columnNames, Map<String, Object> objMap) {
Sql desc = dialect.argsUpdate(tableName, columnNames, objMap);
return this.executeUpdate(desc.getSql(), desc.getArgs());
}
public int updateByField(Object obj, String... byFields) {
Desc desc = dialect.getDesc(obj.getClass());
String[] columns = desc.getColumnsByFidlds(byFields);
return this.updateByColumn(desc.getName(), columns, Util.toMap(obj));
}
public Map<String, Object> slimit(String sql, Page page, Object... args) {
Map<String, Object> map = new HashMap<String, Object>();
List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
if(page == null) {
datas= queryForList(sql, args);
} else {
String sql_limit = dialect.limit(sql, page);
String sql_count = dialect.count(sql);
Long count = queryForLong(sql_count, args);
page.setTotal(count);
if(count > 0) {
datas = this.queryForList(sql_limit, args);
}
}
map.put("page", page);
map.put("datas", datas);
return map;
}
public List<Map<String, Object>> limit(String sql, Page page, Object... args) {
if(page == null) {
return queryForList(sql, args);
} else {
String sql_limit = dialect.limit(sql, page);
String sql_count = dialect.count(sql);
Long count = queryForLong(sql_count, args);
page.setTotal(count);
if(count > 0) {
return this.queryForList(sql_limit, args);
} else {
return new ArrayList<Map<String, Object>>();
}
}
}
public List<Map<String, Object>> limitAll(String sql, Page page, Object... args) {
List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
long index = 1;
List<Map<String, Object>> pageDatas = null;
do{
page.setIndex(index++);
pageDatas = limit(sql, page, args);
datas.addAll(pageDatas);
} while(pageDatas != null && pageDatas.size() > 0 && datas.size() < page.getTotal());
return datas;
}
public <T> T queryForBean(String sql, Class<T> type, Object... args) {
return JUtil.mapTo(this.queryForMap(sql, args), type);
}
public <T> T queryForBeanByField(T obj, String... byFields) {
@SuppressWarnings("unchecked")
Class<T> type = (Class<T>) obj.getClass();
Desc desc = dialect.getDesc(type);
Sql iSql = dialect.argsQuery(desc.getName(), dialect.getColumnValueByField(obj, byFields));
return this.queryForBean(iSql.getSql(), type, iSql.getArgs());
}
public <T> T queryForBeanByField(Class<T> type, Map<String, Object> byFields) {
Map<String, Object> byColumns = dialect.fieldsToColumns(type, byFields);
Desc desc = dialect.getDesc(type);
Sql iSql = dialect.argsQuery(desc.getName(), byColumns);
return this.queryForBean(iSql.getSql(), type, iSql.getArgs());
}
public <T> List<T> queryForBeansByField(Class<T> type, Map<String, Object> byFields) {
Map<String, Object> byColumns = dialect.fieldsToColumns(type, byFields);
Desc desc = dialect.getDesc(type);
Sql iSql = dialect.argsQuery(desc.getName(), byColumns);
return this.queryForBeans(iSql.getSql(), type, iSql.getArgs());
}
public <T> List<T> queryForBeansByField(T obj, String[] byFields) {
@SuppressWarnings("unchecked")
Class<T> type = (Class<T>) obj.getClass();
Desc desc = dialect.getDesc(type);
Sql iSql = dialect.argsQuery(desc.getName(), dialect.getColumnValueByField(obj, byFields));
return this.queryForBeans(iSql.getSql(), type, iSql.getArgs());
}
public <T> List<T> queryForBeans(String sql, Class<T> type, Object... args) {
return JUtil.listTo(this.queryForList(sql, args), type);
}
public int executeUpdate(String sql) {
return this.executeUpdate(sql, new Object[] {});
}
public int[] batchUpdate(String sql, Object[][] args) {
List<Object[]> vals = new ArrayList<Object[]>();
for (Object[] arg : args) {
vals.add(arg);
}
return this.batchUpdate(sql, vals);
}
public int[] batchSave(Object... objs) {
if(objs != null && objs.length > 0) {
Sql i = dialect.batchInsert(objs);
return this.batchUpdate(i.getSql(), i.getBachArgs());
}
return new int[]{0};
}
public int[] batchSave(List<?> objs) {
if(objs != null && objs.size() > 0) {
return this.batchSave(objs.toArray());
}
return new int[]{0};
}
public int batchSave(String tableName, List<Map<String, Object>> objs) {
if(objs.size() > 0) {
Sql sql = dialect.batchInsert(tableName, objs);
this.batchUpdate(sql.getSql(), sql.getBachArgs());
return 0;
} else {
return 0;
}
}
public int update(String sql) {
return this.executeUpdate(sql, new Object[] {});
}
public int update(String sql, Object... args) {
return this.executeUpdate(sql, args);
}
public Map<String, Object> queryForMap(String sql) {
return this.queryForMap(sql, new Object[] {});
}
public List<Map<String, Object>> queryForList(String sql) {
return this.queryForList(sql, new Object[] {});
}
public Integer queryForInt(String sql) {
return this.queryForObject(sql, int.class, new Object[] {});
}
public Long queryForLong(String sql) {
return this.queryForObject(sql, long.class, new Object[] {});
}
public <T> T queryForObject(String sql, Class<T> type) {
return this.queryForObject(sql, type, new Object[] {});
}
public ResultMutil executeMutil(final String sql, final Object... args) {
showSql(sql, args);
Map<Integer, OutParameter> out = new HashMap<Integer, OutParameter>();
return super.execute(new CallableStatementCreator() {
public CallableStatement createCallableStatement(final Connection con) throws SQLException {
final CallableStatement cs = con.prepareCall(sql);
for(int i = 0; i < args.length; i++) {
Integer index = i + 1;
Object arg = args[i];
if(arg != null && arg instanceof OutParameter) {
out.put(index, (OutParameter)arg);
} else {
cs.setObject(index, arg);
}
}
return cs;
}
}, new CallableStatementCallback<ResultMutil>() {
public ResultMutil doInCallableStatement(final CallableStatement cs) throws SQLException, DataAccessException {
List<List<Map<String, Object>>> datas = new ArrayList<List<Map<String, Object>>>();
List<Integer> counts = new ArrayList<Integer>();
cs.execute();
while(true) {
Integer count = cs.getUpdateCount();
ResultSet resultSet = cs.getResultSet();
if(count == -1 && resultSet == null) {
break;
} else {
if(resultSet != null) {
datas.add(JUtil.resultSetToList(resultSet));
} else {
counts.add(count);
}
cs.getMoreResults();
}
}
if(out.size() > 0) {
for(Integer key : out.keySet()) {
out.get(key).setValue(cs.getObject(key));
}
}
return new ResultMutil(datas, counts);
}
});
}
public List<Object> exec(final String sql, final Object... args) {
showSql(sql, args);
return super.execute(new CallableStatementCreator() {
public CallableStatement createCallableStatement(final Connection con) throws SQLException {
final CallableStatement cs = con.prepareCall(sql);
for(int i = 0; i < args.length; i++) {
cs.setObject(i+1, args[i]);
}
return cs;
}
}, new CallableStatementCallback<List<Object>>() {
public List<Object> doInCallableStatement(final CallableStatement cs) throws SQLException, DataAccessException {
List<Object> datas = new ArrayList<Object>();
cs.execute();
while(true) {
Integer count = cs.getUpdateCount();
ResultSet resultSet = cs.getResultSet();
if(count == -1 && resultSet == null) {
break;
} else {
if(resultSet != null) {
datas.add(JUtil.resultSetToList(resultSet));
} else {
datas.add(count);
}
cs.getMoreResults();
}
}
return datas;
}
});
}
public static class OutParameter {
private final int type;
private Object value;
public OutParameter(int type) {
this.type = type;
}
public int getType() {
return type;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
public synchronized String getNumber(String... args) {
String sKey = null;
String format = null;
String formatD = null;
String formatNo = null;
if(args != null) {
for(int i = 0; i < args.length; i++) {
sKey = i == 0 ? args[i] : sKey;
format = i == 1 ? args[i] : format;
formatD = i == 2 ? args[i] : formatD;
formatNo = i == 3 ? args[i] : formatNo;
}
}
sKey = StringUtil.isBlank(sKey) ? "DEFAULT" : sKey;
format = StringUtil.isBlank(format) ? "NO_00000000000000000" : format;
formatD = StringUtil.isBlank(formatD) ? "yyyyMMdd" : formatD;
formatNo = StringUtil.isBlank(formatNo) ? "000000" : formatNo;
return StringUtil.formatLength(DateUtil.format(new Date(), "yyyyMMddHHmmssSSS"), format);
}
public Dialect getDialect() {
return this.dialect;
}
public void setDialect(Dialect dialect) {
this.dialect = dialect;
}
public int getSql_level() {
return sql_level;
}
public void setSql_level(int sql_level) {
this.sql_level = sql_level;
}
public void setLogger(Object logger) {
}
protected void showSql(String sql, Object[] args) {
if (sql_level == 1) {
logger.debug(sql);
} else if (sql_level > 1) {
logger.debug(sql + " " + StringUtil.toJson(args));
}
}
}
package com.egolm.common.jdbc;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.CallableStatementCallback;
import org.springframework.jdbc.core.CallableStatementCreator;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import com.egolm.common.DateUtil;
import com.egolm.common.GsonUtil;
import com.egolm.common.ReflexUtil;
import com.egolm.common.StringUtil;
import com.egolm.common.Util;
import com.egolm.common.jdbc.dialect.Dialect;
import com.egolm.common.jdbc.dialect.bean.Desc;
import com.egolm.common.jdbc.dialect.bean.Sql;
import com.egolm.common.jdbc.exception.MustBeOneRowException;
import com.egolm.common.jdbc.exception.QueryArgsException;
public class JdbcTemplate extends org.springframework.jdbc.core.JdbcTemplate {
protected Dialect dialect;
protected int sql_level = 2;
public JdbcTemplate() {
super();
}
public JdbcTemplate(DataSource dataSource, boolean lazyInit) {
super(dataSource, lazyInit);
}
public JdbcTemplate(DataSource dataSource) {
super(dataSource);
}
public int executeUpdate(String sql, Object... args) {
showSql(sql, args);
return super.update(sql, args);
}
public Map<String, Object> queryForMap(String sql, Object... args) {
showSql(sql, args);
return super.queryForMap(sql, args);
}
public List<Map<String, Object>> queryForList(String sql, Object... args) {
showSql(sql, args);
return super.queryForList(sql, args);
}
public int queryForInt(String sql, Object... args) {
showSql(sql, args);
return super.queryForObject(sql, Integer.class, args);
}
public long queryForLong(String sql, Object... args) {
showSql(sql, args);
return super.queryForObject(sql, Long.class, args);
}
public String queryForString(String sql, Object... args) {
showSql(sql, args);
return super.queryForObject(sql, String.class, args);
}
public Double queryForDouble(String sql, Object... args) {
showSql(sql, args);
return super.queryForObject(sql, Double.class, args);
}
public Date queryForDate(String sql, Object... args) {
showSql(sql, args);
return super.queryForObject(sql, Date.class, args);
}
public Boolean queryForBoolean(String sql, Object... args) {
showSql(sql, args);
return super.queryForObject(sql, Boolean.class, args);
}
public <T> T queryForObject(String sql, Class<T> type, Object... args) {
showSql(sql, args);
return super.queryForObject(sql, type, args);
}
public <T> List<T> queryForObjects(String sql, Class<T> type, Object... args) {
List<Map<String, Object>> list = queryForList(sql, args);
List<T> objs = new ArrayList<T>();
for (Map<String, Object> map : list) {
for (String key : map.keySet()) {
objs.add(Util.objTo(map.get(key), type));
}
}
return objs;
}
public int[] batchUpdate(String sql, List<Object[]> args) {
showSql(sql, args.toArray());
return super.batchUpdate(sql, args);
}
public int saveOrUpdate(Object obj) {
Desc desc = dialect.getDesc(obj.getClass());
String[] byFields = desc.getFieldPkNames();
Map<String, Object> pkFieldMap = dialect.getFieldValue(obj, byFields);
if(dialect.hasPkValue(obj) && pkFieldMap != null && pkFieldMap.size() > 0) {
List<Map<String, Object>> objMaps = queryForListByColumn(desc.getName(), pkFieldMap);
if(objMaps != null) {
if(objMaps.size() == 1) {
return this.update(obj);
} else if(objMaps.size() > 1) {
throw new MustBeOneRowException();
} else {
return this.save(obj);
}
} else {
return this.save(obj);
}
} else {
return this.save(obj);
}
}
public Map<String, Object> queryForMapByColumn(String tableName, Map<String, Object> byColumns) {
Sql iSql = dialect.argsQuery(tableName, byColumns);
return this.queryForMap(iSql.getSql(), iSql.getArgs());
}
public List<Map<String, Object>> queryForListByColumn(String tableName, Map<String, Object> byColumns) {
Sql iSql = dialect.argsQuery(tableName, byColumns);
return this.queryForList(iSql.getSql(), iSql.getArgs());
}
public Map<String, Object> queryForMapByField(Object obj, String... byFields) {
Desc desc = dialect.getDesc(obj.getClass());
Sql iSql = dialect.argsQuery(desc.getName(), dialect.getColumnValueByField(obj, byFields));
return this.queryForMap(iSql.getSql(), iSql.getArgs());
}
public List<Map<String, Object>> queryForListByField(Object obj, String... byFields) {
Desc desc = dialect.getDesc(obj.getClass());
Sql iSql = dialect.argsQuery(desc.getName(), dialect.getColumnValueByField(obj, byFields));
return this.queryForList(iSql.getSql(), iSql.getArgs());
}
public Map<String, Object> queryForMapByObject(Object obj) {
Desc desc = dialect.getDesc(obj.getClass());
Sql iSql = dialect.argsQuery(desc.getName(), dialect.getColumnValueByField(obj, desc.getFieldPkNames()));
return queryForMap(iSql.getSql(), iSql.getArgs());
}
public <T> T queryById(Class<T> type, Object... vals) {
Desc desc = dialect.getDesc(type);
String[] fieldPkNames = desc.getFieldPkNames();
if(vals == null || vals.length == 0 || vals.length != fieldPkNames.length) {
throw new QueryArgsException();
} else {
Map<String, Object> map = new HashMap<String, Object>();
for(int i = 0; i < vals.length; i++) {
map.put(fieldPkNames[i], vals[i]);
}
Sql iSql = dialect.argsQuery(desc.getName(), map);
return queryForBean(iSql.getSql(), type, iSql.getArgs());
}
}
public <T> T queryByObject(T obj) {
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>)obj.getClass();
Desc desc = dialect.getDesc(clazz);
Sql iSql = dialect.argsQuery(desc.getName(), dialect.getColumnValueByField(obj, desc.getFieldPkNames()));
return queryForBean(iSql.getSql(), clazz, iSql.getArgs());
}
public int merge(Object... objs) {
int count = 0;
for(Object obj : objs) {
Desc iSql = dialect.getDesc(obj.getClass());
count += mergeByField(obj, iSql.getFieldPkNames());
}
return count;
}
public int mergeByField(Object obj, String... byFields) {
Desc iSql = dialect.getDesc(obj.getClass());
Map<String, Object> pkFieldMap = dialect.getFieldValue(obj, byFields);
if(dialect.hasPkValue(obj) && pkFieldMap != null && pkFieldMap.size() > 0) {
List<Map<String, Object>> objMaps = this.queryForListByColumn(iSql.getName(), pkFieldMap);
if(objMaps != null) {
if(objMaps.size() == 1) {
Map<String, Object> map = new HashMap<String, Object>();
Field[] fields = obj.getClass().getDeclaredFields();
for(Field field : fields) {
int mod = field.getModifiers();
if(!Modifier.isStatic(mod) && !Modifier.isFinal(mod)) {
Object fieldValue = ReflexUtil.getFieldValue(field, obj);
if(fieldValue != null) {
map.put(field.getName(), fieldValue);
}
}
}
return this.updateByColumn(iSql.getName(), iSql.getColumnPkNames(), map);
} else if(objMaps.size() > 1) {
throw new MustBeOneRowException();
} else {
return this.save(obj);
}
} else {
return this.save(obj);
}
} else {
return this.save(obj);
}
}
public int save(Object... objs) {
int save_count = 0;
for (Object obj : objs) {
final Sql iSql = dialect.argsInsert(obj);
Desc desc = dialect.getDesc(obj.getClass());
showSql(iSql.getSql(), iSql.getArgs());
KeyHolder keyHolder = new GeneratedKeyHolder();
save_count += super.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(iSql.getSql(), Statement.RETURN_GENERATED_KEYS);
Object[] args = iSql.getArgs();
for(int i = 0; i <args.length; i++) {
Object argObj = args[i];
if(argObj instanceof java.util.Date) {
java.util.Date argDate = (java.util.Date)argObj;
ps.setObject(i+1, new java.sql.Timestamp(argDate.getTime()));
} else if(argObj.getClass().isEnum()) {
ps.setObject(i+1, args[i].toString());
} else {
ps.setObject(i+1, args[i]);
}
}
return ps;
}
}, keyHolder);
String[] pks = desc.getFieldPkNames();
if(pks != null && pks.length > 0) {
if(ReflexUtil.readField(pks[0], obj) == null) {
Object key = keyHolder.getKey();
try {
ReflexUtil.writeField(pks[0], obj, key);
} catch (ClassCastException e) {
throw new RuntimeException("设置自增主键:field=" + pks[0] + ",value=" + key + ",class=" + key.getClass() + "错误");
}
}
}
}
return save_count;
}
public int save(String tableName, Map<String, Object> objMap) {
Sql desc = dialect.argsInsert(tableName, objMap);
int save_count = this.executeUpdate(desc.getSql(), desc.getArgs());
return save_count;
}
public int delete(Object... objs) {
int delete_count = 0;
for (Object obj : objs) {
Sql desc = dialect.argsDelete(obj);
delete_count += this.executeUpdate(desc.getSql(), desc.getArgs());
}
return delete_count;
}
public int batchDelete(Object... objs) {
Sql desc = dialect.batchDelete(objs);
int[] counts = this.batchUpdate(desc.getSql(), desc.getBachArgs());
int countSum = 0;
for(int count : counts) {
countSum += count;
}
return countSum;
}
public int batchDelete(List<Object> objs) {
return this.batchDelete(objs.toArray());
}
public int deleteByField(Object obj, String... byFields) {
Desc desc = dialect.getDesc(obj.getClass());
Map<String, Object> columnsMap = dialect.getColumnValueByField(obj, byFields);
return this.delete(desc.getName(), columnsMap);
}
public int delete(String tableName, String columnName, Object columnValue) {
Sql desc = dialect.argsDelete(tableName, columnName, columnValue);
return this.executeUpdate(desc.getSql(), desc.getArgs());
}
public int delete(String tableName, Map<String, Object> objMap) {
Sql desc = dialect.argsDelete(tableName, objMap);
return this.executeUpdate(desc.getSql(), desc.getArgs());
}
public int update(Object... objs) {
int update_count = 0;
for (Object obj : objs) {
Sql desc = dialect.argsUpdate(obj);
update_count += this.executeUpdate(desc.getSql(), desc.getArgs());
}
return update_count;
}
public int updateByColumn(String tableName, String[] columnNames, Map<String, Object> objMap) {
Sql desc = dialect.argsUpdate(tableName, columnNames, objMap);
return this.executeUpdate(desc.getSql(), desc.getArgs());
}
public int updateByField(Object obj, String... byFields) {
Desc desc = dialect.getDesc(obj.getClass());
String[] columns = desc.getColumnsByFidlds(byFields);
return this.updateByColumn(desc.getName(), columns, Util.toMap(obj));
}
public Map<String, Object> slimit(String sql, Page page, Object... args) {
Map<String, Object> map = new HashMap<String, Object>();
List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
if(page == null) {
datas= queryForList(sql, args);
} else {
String sql_limit = dialect.limit(sql, page);
String sql_count = dialect.count(sql);
Long count = queryForLong(sql_count, args);
page.setTotal(count);
if(count > 0) {
datas = this.queryForList(sql_limit, args);
}
}
map.put("page", page);
map.put("datas", datas);
return map;
}
public List<Map<String, Object>> limit(String sql, Page page, Object... args) {
if(page == null) {
return queryForList(sql, args);
} else {
String sql_limit = dialect.limit(sql, page);
String sql_count = dialect.count(sql);
Long count = queryForLong(sql_count, args);
page.setTotal(count);
if(count > 0) {
return this.queryForList(sql_limit, args);
} else {
return new ArrayList<Map<String, Object>>();
}
}
}
public List<Map<String, Object>> limitAll(String sql, Page page, Object... args) {
List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
long index = 1;
List<Map<String, Object>> pageDatas = null;
do{
page.setIndex(index++);
pageDatas = limit(sql, page, args);
datas.addAll(pageDatas);
} while(pageDatas != null && pageDatas.size() > 0 && datas.size() < page.getTotal());
return datas;
}
public <T> T queryForBean(String sql, Class<T> type, Object... args) {
return JUtil.mapTo(this.queryForMap(sql, args), type);
}
public <T> T queryForBeanByField(T obj, String... byFields) {
@SuppressWarnings("unchecked")
Class<T> type = (Class<T>) obj.getClass();
Desc desc = dialect.getDesc(type);
Sql iSql = dialect.argsQuery(desc.getName(), dialect.getColumnValueByField(obj, byFields));
return this.queryForBean(iSql.getSql(), type, iSql.getArgs());
}
public <T> T queryForBeanByField(Class<T> type, Map<String, Object> byFields) {
Map<String, Object> byColumns = dialect.fieldsToColumns(type, byFields);
Desc desc = dialect.getDesc(type);
Sql iSql = dialect.argsQuery(desc.getName(), byColumns);
return this.queryForBean(iSql.getSql(), type, iSql.getArgs());
}
public <T> List<T> queryForBeansByField(Class<T> type, Map<String, Object> byFields) {
Map<String, Object> byColumns = dialect.fieldsToColumns(type, byFields);
Desc desc = dialect.getDesc(type);
Sql iSql = dialect.argsQuery(desc.getName(), byColumns);
return this.queryForBeans(iSql.getSql(), type, iSql.getArgs());
}
public <T> List<T> queryForBeansByField(T obj, String[] byFields) {
@SuppressWarnings("unchecked")
Class<T> type = (Class<T>) obj.getClass();
Desc desc = dialect.getDesc(type);
Sql iSql = dialect.argsQuery(desc.getName(), dialect.getColumnValueByField(obj, byFields));
return this.queryForBeans(iSql.getSql(), type, iSql.getArgs());
}
public <T> List<T> queryForBeans(String sql, Class<T> type, Object... args) {
return JUtil.listTo(this.queryForList(sql, args), type);
}
public int executeUpdate(String sql) {
return this.executeUpdate(sql, new Object[] {});
}
public int[] batchUpdate(String sql, Object[][] args) {
List<Object[]> vals = new ArrayList<Object[]>();
for (Object[] arg : args) {
vals.add(arg);
}
return this.batchUpdate(sql, vals);
}
public int[] batchSave(Object... objs) {
if(objs != null && objs.length > 0) {
Sql i = dialect.batchInsert(objs);
return this.batchUpdate(i.getSql(), i.getBachArgs());
}
return new int[]{0};
}
public int[] batchSave(List<?> objs) {
if(objs != null && objs.size() > 0) {
return this.batchSave(objs.toArray());
}
return new int[]{0};
}
public int batchSave(String tableName, List<Map<String, Object>> objs) {
if(objs.size() > 0) {
Sql sql = dialect.batchInsert(tableName, objs);
this.batchUpdate(sql.getSql(), sql.getBachArgs());
return 0;
} else {
return 0;
}
}
public int update(String sql) {
return this.executeUpdate(sql, new Object[] {});
}
public int update(String sql, Object... args) {
return this.executeUpdate(sql, args);
}
public Map<String, Object> queryForMap(String sql) {
return this.queryForMap(sql, new Object[] {});
}
public List<Map<String, Object>> queryForList(String sql) {
return this.queryForList(sql, new Object[] {});
}
public Integer queryForInt(String sql) {
return this.queryForObject(sql, int.class, new Object[] {});
}
public Long queryForLong(String sql) {
return this.queryForObject(sql, long.class, new Object[] {});
}
public <T> T queryForObject(String sql, Class<T> type) {
return this.queryForObject(sql, type, new Object[] {});
}
public ResultMutil executeMutil(final String sql, final Object... args) {
showSql(sql, args);
return super.execute(new CallableStatementCreator() {
public CallableStatement createCallableStatement(final Connection con) throws SQLException {
final CallableStatement cs = con.prepareCall(sql);
for(int i = 0; i < args.length; i++) {
Integer index = i + 1;
Object arg = args[i];
cs.setObject(index, arg);
}
return cs;
}
}, new CallableStatementCallback<ResultMutil>() {
public ResultMutil doInCallableStatement(final CallableStatement cs) throws SQLException, DataAccessException {
List<List<Map<String, Object>>> datas = new ArrayList<List<Map<String, Object>>>();
List<Integer> counts = new ArrayList<Integer>();
cs.execute();
while(true) {
Integer count = cs.getUpdateCount();
ResultSet resultSet = cs.getResultSet();
if(count == -1 && resultSet == null) {
break;
} else {
if(resultSet != null) {
datas.add(JUtil.resultSetToList(resultSet));
} else {
counts.add(count);
}
cs.getMoreResults();
}
}
return new ResultMutil(datas, counts);
}
});
}
public List<Object> exec(final String sql, final Object... args) {
showSql(sql, args);
Map<Integer, OutParameter> out = new HashMap<Integer, OutParameter>();
return super.execute(new CallableStatementCreator() {
public CallableStatement createCallableStatement(final Connection con) throws SQLException {
final CallableStatement cs = con.prepareCall(sql);
for(int i = 0; i < args.length; i++) {
Integer index = i + 1;
Object arg = args[i];
if(arg != null && arg instanceof OutParameter) {
OutParameter outArg = (OutParameter)arg;
outArg.setValue(null);
cs.registerOutParameter(index, outArg.getSqlType());
out.put(index, outArg);
} else {
cs.setObject(index, arg);
}
}
return cs;
}
}, new CallableStatementCallback<List<Object>>() {
public List<Object> doInCallableStatement(final CallableStatement cs) throws SQLException, DataAccessException {
List<Object> datas = new ArrayList<Object>();
cs.execute();
while(true) {
Integer count = cs.getUpdateCount();
ResultSet resultSet = cs.getResultSet();
if(count == -1 && resultSet == null) {
break;
} else {
if(resultSet != null) {
datas.add(JUtil.resultSetToList(resultSet));
} else {
datas.add(count);
}
cs.getMoreResults();
}
}
if(out.size() > 0) {
for(Integer key : out.keySet()) {
Object value = cs.getObject(key);
out.get(key).setValue(value);
logger.debug("Parameter out: index=" + key + ", value=" + value);
}
}
return datas;
}
});
}
public static class OutParameter {
private final int sqlType;
private Object value;
public OutParameter(int sqlType) {
this.sqlType = sqlType;
}
public int getSqlType() {
return sqlType;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public <T> T getValue(Class<T> requireType) {
return Util.objTo(this.getValue(), requireType);
}
public String getString() {
return this.getValue(String.class);
}
public Date getDate() {
return this.getValue(Date.class);
}
public Number getNumber() {
return (Number)value;
}
public Long getLong() {
return this.getValue(Long.class);
}
public Integer getInteger() {
return this.getValue(Integer.class);
}
public BigDecimal getBigDecimal() {
return this.getValue(BigDecimal.class);
}
public BigInteger getBigInteger() {
return this.getValue(BigInteger.class);
}
public Double getDouble() {
return this.getValue(Double.class);
}
public Float getFloat() {
return this.getValue(Float.class);
}
public Short getShort() {
return this.getValue(Short.class);
}
public Byte getByte() {
return this.getValue(Byte.class);
}
public Boolean getBoolean() {
return this.getValue(Boolean.class);
}
}
public synchronized String getNumber(String... args) {
String sKey = null;
String format = null;
String formatD = null;
String formatNo = null;
if(args != null) {
for(int i = 0; i < args.length; i++) {
sKey = i == 0 ? args[i] : sKey;
format = i == 1 ? args[i] : format;
formatD = i == 2 ? args[i] : formatD;
formatNo = i == 3 ? args[i] : formatNo;
}
}
sKey = StringUtil.isBlank(sKey) ? "DEFAULT" : sKey;
format = StringUtil.isBlank(format) ? "NO_00000000000000000" : format;
formatD = StringUtil.isBlank(formatD) ? "yyyyMMdd" : formatD;
formatNo = StringUtil.isBlank(formatNo) ? "000000" : formatNo;
return StringUtil.formatLength(DateUtil.format(new Date(), "yyyyMMddHHmmssSSS"), format);
}
public Dialect getDialect() {
return this.dialect;
}
public void setDialect(Dialect dialect) {
this.dialect = dialect;
}
public int getSql_level() {
return sql_level;
}
public void setSql_level(int sql_level) {
this.sql_level = sql_level;
}
public void setLogger(Object logger) {
}
protected void showSql(String sql, Object[] args) {
if (sql_level == 1) {
logger.debug(sql);
} else if (sql_level > 1) {
logger.debug(sql + " " + GsonUtil.toJson(args));
}
}
}
package com.egolm.common.jdbc.dialect;
import java.io.File;
import java.io.IOException;
import java.util.List;
import com.egolm.common.FileUtil;
import com.egolm.common.StringUtil;
/**
*
* @Description 生成Bean的工具类
* @author 曲欣亮
* @date 2016年4月22日
* @since 2016年4月22日
*/
public class ReverseUtil {
public static void main(String[] args) {
String regex = "^[a-z][A-Z].*$";
System.out.println("nQd".matches(regex));
}
/**
* 功能:生成实体类主体代码
*
* @param columnNames
* @param colTypes
* @return
* @throws IOException
*/
public static void parseEntity(String pkg_name, String author, String root, String name, String comment, List<String> paramyKeys, List<String> columnNames, List<String> colTypes, List<String> colComments) throws IOException {
StringBuffer sb = new StringBuffer();
sb.append("package " + pkg_name + ";" + "\n\n");
sb.append("import javax.persistence.Entity;" + "\n\n");
sb.append("import javax.persistence.Column;" + "\n\n");
if(paramyKeys.size() > 0) {
sb.append("import javax.persistence.Id;" + "\n\n");
}
boolean is_date = false;
boolean is_decimal = false;
for(String columnType : colTypes) {
if ((columnType.equalsIgnoreCase("datetime") || columnType.equalsIgnoreCase("date")) && !is_date) {
sb.append("import java.util.Date;" + "\n\n");
is_date = true;
} else if ((columnType.contains("decimal") || columnType.contains("numeric")) && !is_decimal) {
sb.append("import java.math.BigDecimal;" + "\n\n");
is_decimal = true;
}
}
// sb.append("/**" + "\n");
// sb.append(" * @author " + author + "\n");
// sb.append(" * @since " + DateUtil.format(new Date(), DateUtil.FMT_DATE) + "\n");
// sb.append(" * @version v-1.0" + "\n");
// sb.append(" */" + "\n");
sb.append("@Entity(name=\"" + name + "\")" + "\n");
sb.append("public class " + StringUtil.upperFirst(name) + " implements java.io.Serializable {" + "\n\n" + "\tprivate static final long serialVersionUID = 1L;" + "\n\n");
processAllAttrs(paramyKeys, columnNames, colTypes, colComments, sb);
// processAllConstructor(StringUtil.upperFirst(name), comment, columnNames, colTypes, colComments, sb);
processAllMethod(columnNames, colTypes, colComments, sb);
sb.append("}" + "\n");
String outputPath = root + File.separator + pkg_name.replace(".", File.separator) + File.separator + StringUtil.upperFirst(name) + ".java";
File file = new File(outputPath).getParentFile();
if (!file.exists()) {
file.mkdirs();
}
FileUtil.stringToFile(outputPath, sb.toString());
System.out.println("Create: " + outputPath);
}
/**
* 功能:生成所有属性
*
* @param sbuffer
*/
public static void processAllAttrs(List<String> paramyKeys, List<String> columnNames, List<String> colTypes, List<String> columnComments, StringBuffer sbuffer) {
for (int i = 0; i < columnNames.size(); i++) {
String columnName = columnNames.get(i);
if(StringUtil.contains(paramyKeys.toArray(new String[paramyKeys.size()]), columnName)) {
sbuffer.append("\t@Id" + "\n");
}
sbuffer.append("\t@Column(columnDefinition=\"" + colTypes.get(i) + (StringUtil.isNotBlank(columnComments.get(i)) ? (" COMMENT '" + columnComments.get(i).replaceAll("\\s+", " ") + "'") : "") + "\")\n");
sbuffer.append("\tprivate " + sqlType2JavaType(colTypes.get(i)) + " " + columnName + ";" + "\n\n");
}
sbuffer.append("\n");
}
/**
* 功能:生成构造方法
* @param sb
*/
public static void processAllConstructor(String name, String comment, List<String> colnames, List<String> colTypes, List<String> colComments, StringBuffer sb) {
sb.append("\t/**" + "\n");
sb.append("\t * " + "无参数构造方法" + "\n");
sb.append("\t */" + "\n");
sb.append("\tpublic " + name + " () {" + "\n" + "\t\tsuper();" + "\n" + "\t}" + "\n\n");
sb.append("\t/**" + "\n");
sb.append("\t * " + "全参数构造方法" + "\n");
for (int i = 0; i < colnames.size(); i++) {
sb.append("\t * @param " + colnames.get(i) + " " + (StringUtil.isNotBlank(colComments.get(i)) ? colComments.get(i) : "") + "\n");
}
sb.append("\t */" + "\n");
sb.append("\tpublic " + name + "(");
for (int i = 0; i < colnames.size(); i++) {
sb.append(sqlType2JavaType(colTypes.get(i)) + " " + colnames.get(i));
if(i < colnames.size() - 1) {
sb.append(", ");
}
}
sb.append(") {" + "\n");
for (int i = 0; i < colnames.size(); i++) {
sb.append("\t\tthis." + colnames.get(i) + " = " + colnames.get(i) + ";" + "\n");
}
sb.append("\t}" + "\n\n");
}
/**
* 功能:生成所有方法
* @param sb
*/
public static void processAllMethod(List<String> colnames, List<String> colTypes, List<String> colComments, StringBuffer sb) {
String regex = "^[a-z][A-Z].*$";
for (int i = 0; i < colnames.size(); i++) {
String columnName = colnames.get(i);
String name = (columnName.matches(regex) ? columnName : StringUtil.upperFirst(columnName));
sb.append("\tpublic void set" + name + "(" + sqlType2JavaType(colTypes.get(i)) + " " + colnames.get(i) + ") {" + "\n");
sb.append("\t\tthis." + colnames.get(i) + " = " + colnames.get(i) + ";" + "\n");
sb.append("\t}" + "\n\n");
sb.append("\tpublic " + sqlType2JavaType(colTypes.get(i)) + " get" + name + "() {" + "\n");
sb.append("\t\treturn " + colnames.get(i) + ";" + "\n");
sb.append("\t}" + "\n\n");
}
}
/**
* 功能:获得列的数据类型
* @param sqlType
* @return
*/
public static String sqlType2JavaType(String sqlType) {
if(sqlType.startsWith("bit")){
return "Boolean";
} else if(sqlType.startsWith("int") || sqlType.startsWith("integer") || sqlType.startsWith("tinyint") || sqlType.startsWith("smallint")){
return "Integer";
} else if(sqlType.startsWith("bigint")){
return "Long";
} else if(sqlType.startsWith("float")){
return "Float";
} else if(sqlType.startsWith("decimal") || sqlType.startsWith("numeric")) {
return "BigDecimal";
} else if(sqlType.startsWith("double") || sqlType.startsWith("real") || sqlType.startsWith("money") || sqlType.startsWith("smallmoney")){
return "Double";
} else if(sqlType.startsWith("varchar") || sqlType.startsWith("char") || sqlType.startsWith("nvarchar") || sqlType.startsWith("nchar") || sqlType.startsWith("text") || sqlType.startsWith("longtext")){
return "String";
} else if(sqlType.startsWith("datetime") || sqlType.startsWith("date") || sqlType.startsWith("timestamp")){
return "Date";
} else if(sqlType.startsWith("image")){
return "Byte[]";
} else {
return "";
}
// throw new RuntimeException("Unknown Type: " + sqlType);
}
}
package com.egolm.common.jdbc.dialect;
import java.io.File;
import java.io.IOException;
import java.util.List;
import com.egolm.common.FileUtil;
import com.egolm.common.StringUtil;
/**
*
* @Description 生成Bean的工具类
* @author 曲欣亮
* @date 2016年4月22日
* @since 2016年4月22日
*/
public class ReverseUtil {
public static void main(String[] args) {
String regex = "^[a-z][A-Z].*$";
System.out.println("nQd".matches(regex));
}
/**
* 功能:生成实体类主体代码
*
* @param columnNames
* @param colTypes
* @return
* @throws IOException
*/
public static void parseEntity(String pkg_name, String author, String root, String name, String comment, List<String> paramyKeys, List<String> columnNames, List<String> colTypes, List<String> colComments) throws IOException {
StringBuffer sb = new StringBuffer();
sb.append("package " + pkg_name + ";" + "\n\n");
sb.append("import javax.persistence.Entity;" + "\n\n");
sb.append("import javax.persistence.Column;" + "\n\n");
if(paramyKeys.size() > 0) {
sb.append("import javax.persistence.Id;" + "\n\n");
}
boolean is_date = false;
boolean is_decimal = false;
for(String columnType : colTypes) {
if ((columnType.equalsIgnoreCase("datetime") || columnType.equalsIgnoreCase("date")) && !is_date) {
sb.append("import java.util.Date;" + "\n\n");
is_date = true;
} else if ((columnType.contains("decimal") || columnType.contains("numeric")) && !is_decimal) {
sb.append("import java.math.BigDecimal;" + "\n\n");
is_decimal = true;
}
}
// sb.append("/**" + "\n");
// sb.append(" * @author " + author + "\n");
// sb.append(" * @since " + DateUtil.format(new Date(), DateUtil.FMT_DATE) + "\n");
// sb.append(" * @version v-1.0" + "\n");
// sb.append(" */" + "\n");
sb.append("@Entity(name=\"" + name + "\")" + "\n");
sb.append("public class " + StringUtil.upperFirst(name) + " implements java.io.Serializable {" + "\n\n" + "\tprivate static final long serialVersionUID = 1L;" + "\n\n");
processAllAttrs(paramyKeys, columnNames, colTypes, colComments, sb);
// processAllConstructor(StringUtil.upperFirst(name), comment, columnNames, colTypes, colComments, sb);
processAllMethod(columnNames, colTypes, colComments, sb);
sb.append("}" + "\n");
String outputPath = root + File.separator + pkg_name.replace(".", File.separator) + File.separator + StringUtil.upperFirst(name) + ".java";
File file = new File(outputPath).getParentFile();
if (!file.exists()) {
file.mkdirs();
}
FileUtil.stringToFile(outputPath, sb.toString());
System.out.println("Create: " + outputPath);
}
/**
* 功能:生成所有属性
*
* @param sbuffer
*/
public static void processAllAttrs(List<String> paramyKeys, List<String> columnNames, List<String> colTypes, List<String> columnComments, StringBuffer sbuffer) {
for (int i = 0; i < columnNames.size(); i++) {
String columnName = columnNames.get(i);
if(StringUtil.contains(paramyKeys.toArray(new String[paramyKeys.size()]), columnName)) {
sbuffer.append("\t@Id" + "\n");
}
sbuffer.append("\t@Column(columnDefinition=\"" + colTypes.get(i) + (StringUtil.isNotBlank(columnComments.get(i)) ? (" COMMENT '" + columnComments.get(i).replaceAll("\\s+", " ") + "'") : "") + "\")\n");
sbuffer.append("\tprivate " + sqlType2JavaType(colTypes.get(i)) + " " + columnName + ";" + "\n\n");
}
sbuffer.append("\n");
}
/**
* 功能:生成构造方法
* @param sb
*/
public static void processAllConstructor(String name, String comment, List<String> colnames, List<String> colTypes, List<String> colComments, StringBuffer sb) {
sb.append("\t/**" + "\n");
sb.append("\t * " + "无参数构造方法" + "\n");
sb.append("\t */" + "\n");
sb.append("\tpublic " + name + " () {" + "\n" + "\t\tsuper();" + "\n" + "\t}" + "\n\n");
sb.append("\t/**" + "\n");
sb.append("\t * " + "全参数构造方法" + "\n");
for (int i = 0; i < colnames.size(); i++) {
sb.append("\t * @param " + colnames.get(i) + " " + (StringUtil.isNotBlank(colComments.get(i)) ? colComments.get(i) : "") + "\n");
}
sb.append("\t */" + "\n");
sb.append("\tpublic " + name + "(");
for (int i = 0; i < colnames.size(); i++) {
sb.append(sqlType2JavaType(colTypes.get(i)) + " " + colnames.get(i));
if(i < colnames.size() - 1) {
sb.append(", ");
}
}
sb.append(") {" + "\n");
for (int i = 0; i < colnames.size(); i++) {
sb.append("\t\tthis." + colnames.get(i) + " = " + colnames.get(i) + ";" + "\n");
}
sb.append("\t}" + "\n\n");
}
/**
* 功能:生成所有方法
* @param sb
*/
public static void processAllMethod(List<String> colnames, List<String> colTypes, List<String> colComments, StringBuffer sb) {
String regex = "^[a-z][A-Z].*$";
for (int i = 0; i < colnames.size(); i++) {
String columnName = colnames.get(i);
String name = (columnName.matches(regex) ? columnName : StringUtil.upperFirst(columnName));
sb.append("\tpublic void set" + name + "(" + sqlType2JavaType(colTypes.get(i)) + " " + colnames.get(i) + ") {" + "\n");
sb.append("\t\tthis." + colnames.get(i) + " = " + colnames.get(i) + ";" + "\n");
sb.append("\t}" + "\n\n");
sb.append("\tpublic " + sqlType2JavaType(colTypes.get(i)) + " get" + name + "() {" + "\n");
sb.append("\t\treturn " + colnames.get(i) + ";" + "\n");
sb.append("\t}" + "\n\n");
}
}
/**
* 功能:获得列的数据类型
* @param sqlType
* @return
*/
public static String sqlType2JavaType(String sqlType) {
if(sqlType.startsWith("bit")){
return "Boolean";
} else if(sqlType.startsWith("int") || sqlType.startsWith("integer") || sqlType.startsWith("tinyint") || sqlType.startsWith("smallint")){
return "Integer";
} else if(sqlType.startsWith("bigint")){
return "Long";
} else if(sqlType.startsWith("float")){
return "Float";
} else if(sqlType.startsWith("decimal") || sqlType.startsWith("numeric")) {
return "BigDecimal";
} else if(sqlType.startsWith("double") || sqlType.startsWith("real") || sqlType.startsWith("money") || sqlType.startsWith("smallmoney")){
return "Double";
} else if(sqlType.startsWith("varchar") || sqlType.startsWith("char") || sqlType.startsWith("nvarchar") || sqlType.startsWith("nchar") || sqlType.startsWith("text") || sqlType.startsWith("longtext") || sqlType.startsWith("mediumtext")){
return "String";
} else if(sqlType.startsWith("datetime") || sqlType.startsWith("date") || sqlType.startsWith("timestamp")){
return "Date";
} else if(sqlType.startsWith("image")){
return "Byte[]";
} else {
return "";
}
// throw new RuntimeException("Unknown Type: " + sqlType);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment