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