Commit 0aab7837 authored by 周健威's avatar 周健威

添加gtdata

parent 817fa0f3
......@@ -39,6 +39,12 @@
<poi.version>3.15</poi.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<optional>true</optional>
<version>2.8.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
......
package com.upyuns.platform.rs.gtdata;
import org.apache.commons.lang3.Validate;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
/**
*
* Description:支持SHA-1/MD5消息摘要的工具类(返回ByteSource,可进一步被编码为Hex, Base64或UrlSafeBase64)
*
* @author JhYao 2014年10月20日
*
* @version v1.0
*
*/
public class Digests {
private static final String SHA1 = "SHA-1";
private static final String MD5 = "MD5";
private static SecureRandom random = new SecureRandom();
/**
* 对输入字符串进行sha1散列.
*/
public static byte[] sha1(byte[] input) {
return digest(input, SHA1, null, 1);
}
public static byte[] sha1(byte[] input, byte[] salt) {
return digest(input, SHA1, salt, 1);
}
public static byte[] sha1(byte[] input, byte[] salt, int iterations) {
return digest(input, SHA1, salt, iterations);
}
/**
* 对字符串进行散列, 支持md5与sha1算法.
*/
private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {
try {
MessageDigest digest = MessageDigest.getInstance(algorithm);
if (salt != null) {
digest.update(salt);
}
byte[] result = digest.digest(input);
for (int i = 1; i < iterations; i++) {
digest.reset();
result = digest.digest(result);
}
return result;
} catch (GeneralSecurityException e) {
throw Exceptions.unchecked(e);
}
}
/**
* 对字符串进行散列, 支持md5与sha1算法.
*/
private static byte[] digest(byte[] input, String algorithm) {
try {
MessageDigest digest = MessageDigest.getInstance(algorithm);
byte[] result = digest.digest(input);
return result;
} catch (GeneralSecurityException e) {
throw Exceptions.unchecked(e);
}
}
/**
* 生成随机的Byte[]作为salt.
*
* @param numBytes byte数组的大小
*/
public static byte[] generateSalt(int numBytes) {
Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes);
byte[] bytes = new byte[numBytes];
random.nextBytes(bytes);
return bytes;
}
/**
* 对字符串进行md5散列.
*/
public static byte[] md5(InputStream input) throws IOException {
return digest(input, MD5);
}
/**
* 对文件进行md5散列.
*/
public static byte[] md5(byte[] input) throws IOException {
return digest(input, MD5);
}
/**
* 对文件进行sha1散列.
*/
public static byte[] sha1(InputStream input) throws IOException {
return digest(input, SHA1);
}
private static byte[] digest(InputStream input, String algorithm) throws IOException {
try {
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
int bufferLength = 8 * 1024;
byte[] buffer = new byte[bufferLength];
int read = input.read(buffer, 0, bufferLength);
while (read > -1) {
messageDigest.update(buffer, 0, read);
read = input.read(buffer, 0, bufferLength);
}
return messageDigest.digest();
} catch (GeneralSecurityException e) {
throw Exceptions.unchecked(e);
}
}
}
package com.upyuns.platform.rs.gtdata;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringEscapeUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
*
* Description:封装各种格式的编码解码工具类(1.Commons-Codec的 hex/base64 编码;2.自制的base62 编码;3.Commons-Lang的xml/html
* escape;4.JDK提供的URLEncoder)
*
* @author JhYao 2014年10月20日
*
* @version v1.0
*
*/
public class Encodes {
private static final String DEFAULT_URL_ENCODING = "UTF-8";
private static final char[] BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
/**
* Hex编码.
*/
public static String encodeHex(byte[] input) {
return Hex.encodeHexString(input);
}
/**
* Hex解码.
*/
public static byte[] decodeHex(String input) {
try {
return Hex.decodeHex(input.toCharArray());
} catch (DecoderException e) {
throw Exceptions.unchecked(e);
}
}
/**
* Base64编码.
*/
public static String encodeBase64(byte[] input) {
return Base64.encodeBase64String(input);
}
/**
* Base64编码, URL安全(将Base64中的URL非法字符'+'和'/'转为'-'和'_', 见RFC3548).
*/
public static String encodeUrlSafeBase64(byte[] input) {
return Base64.encodeBase64URLSafeString(input);
}
/**
* Base64解码.
*/
public static byte[] decodeBase64(String input) {
return Base64.decodeBase64(input);
}
/**
* Base62编码。
*/
public static String encodeBase62(byte[] input) {
char[] chars = new char[input.length];
for (int i = 0; i < input.length; i++) {
chars[i] = BASE62[(input[i] & 0xFF) % BASE62.length];
}
return new String(chars);
}
/**
* Html 转码.
*/
public static String escapeHtml(String html) {
return StringEscapeUtils.escapeHtml4(html);
}
/**
* Html 解码.
*/
public static String unescapeHtml(String htmlEscaped) {
return StringEscapeUtils.unescapeHtml4(htmlEscaped);
}
/**
* Xml 转码.
*/
public static String escapeXml(String xml) {
return StringEscapeUtils.escapeXml(xml);
}
/**
* Xml 解码.
*/
public static String unescapeXml(String xmlEscaped) {
return StringEscapeUtils.unescapeXml(xmlEscaped);
}
/**
* URL 编码, Encode默认为UTF-8.
*/
public static String urlEncode(String part) {
try {
return URLEncoder.encode(part, DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
throw Exceptions.unchecked(e);
}
}
/**
* URL 解码, Encode默认为UTF-8.
*/
public static String urlDecode(String part) {
try {
return URLDecoder.decode(part, DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
throw Exceptions.unchecked(e);
}
}
}
package com.upyuns.platform.rs.gtdata;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
*
* Description:关于异常的工具类(参考了guava的Throwables)
*
* @author JhYao 2014年10月20日
*
* @version v1.0
*
*/
public class Exceptions {
/**
* 将CheckedException转换为UncheckedException.
*/
public static RuntimeException unchecked(Throwable ex) {
if (ex instanceof RuntimeException) {
return (RuntimeException) ex;
} else {
return new RuntimeException(ex);
}
}
/**
* 将ErrorStack转化为String.
*/
public static String getStackTraceAsString(Throwable ex) {
StringWriter stringWriter = new StringWriter();
ex.printStackTrace(new PrintWriter(stringWriter));
return stringWriter.toString();
}
/**
* 获取组合本异常信息与底层异常信息的异常描述, 适用于本异常为统一包装异常类,底层异常才是根本原因的情况。
*/
public static String getErrorMessageWithNestedException(Throwable ex) {
Throwable nestedException = ex.getCause();
return new StringBuilder().append(ex.getMessage()).append(" nested exception is ")
.append(nestedException.getClass().getName()).append(":").append(nestedException.getMessage())
.toString();
}
/**
* 获取异常的Root Cause.
*/
public static Throwable getRootCause(Throwable ex) {
Throwable cause;
while ((cause = ex.getCause()) != null) {
ex = cause;
}
return ex;
}
/**
* 判断异常是否由某些底层的异常引起.
*/
public static boolean isCausedBy(Exception ex, Class<? extends Exception>... causeExceptionClasses) {
Throwable cause = ex;
while (cause != null) {
for (Class<? extends Exception> causeClass : causeExceptionClasses) {
if (causeClass.isInstance(cause)) {
return true;
}
}
cause = cause.getCause();
}
return false;
}
}
package com.upyuns.platform.rs.gtdata;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
/**
*
* Description:java在linux环境下执行linux命令
*
* @author JhYao 2015年1月12日
*
* @version v1.0
*
*/
public class ExecLinuxCmd {
/**
*
* Description:java在linux环境下执行linux命令
*
* @param cmd
* @return 返回命令返回值
*
*/
public static String exec(String cmd) {
try {
String[] cmdA = { "/bin/sh", "-c", cmd };
Process process = Runtime.getRuntime().exec(cmdA);
LineNumberReader br = new LineNumberReader(new InputStreamReader(process.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
// System.out.println(line);
sb.append(line).append("\n");
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
/**
*
* Copyright zkyg
*/
package com.upyuns.platform.rs.gtdata;
import lombok.Data;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
*
* Description:GTDATA接口客户端(详情请查看gtdata相关的api文档)
*
* @author JhYao 2014年11月11日
*
* @version v1.0
*
*/
@Service("gtDataRestClient")
@Conditional(GtdataCondition.class)
@Scope("singleton")
public class GtDataRestClient {
private static Logger logger = LoggerFactory
.getLogger(GtDataRestClient.class);
@Autowired
private RestTemplate restTemplate;
//
// @Value("#{gtdataProperty[baseUrl]}")
// protected String baseUrl;
//
// @Value("#{gtdataProperty[gtDataUrl]}")
// protected String gtDataUrl;
//
// @Value("#{gtdataProperty[gtDataUsername]}")
// protected String gtDataUsername;
//
// @Value("#{gtdataProperty[gtDataPassword]}")
// protected String gtDataPassword;
@Value("${gtdata.baseUrl}")
protected String baseUrl;
@Value("${gtdata.gtDataUrl}")
protected String gtDataUrl;
@Value("${gtdata.gtDataUsername}")
protected String gtDataUsername;
@Value("${gtdata.gtDataPassword}")
protected String gtDataPassword;
private String defaultToken;
private String defaultSign;
private String defaultTime;
private static JsonMapper jsonMapper = JsonMapper.buildNormalMapper();
private ScheduledExecutorService scheduler;
@PostConstruct
public void init() {
try {
login();// 第一次更新认证信息,在初始化时执行
} catch (GtDataRestException e) {
logger.warn("GtData login error. try again...", e);
logout(defaultToken);
login(); // 异常时,再试一次更新认证信息
}
int cpuCoreNumber = Runtime.getRuntime().availableProcessors();// cpu内核数
scheduler = Executors.newScheduledThreadPool(cpuCoreNumber);
Runnable task = new Runnable() {
@Override
public void run() {
try {
updateAuth(); // 更新认证信息
} catch (GtDataRestException e) {
logger.warn("GtData getSign error. try relogin...", e);
logout(defaultToken);
login(); // 异常时,重新登陆
}
}
};
Thread thread = new Thread(task);
thread.setDaemon(true);
scheduler.scheduleAtFixedRate(thread, 5L, 5L, TimeUnit.MINUTES);// 每5分钟执行一次
}
@PreDestroy
public void dostory() {
scheduler.shutdown();
}
public boolean isSign() {
return defaultSign == null ? false : true;
}
/**
*
* Description:取token
*
* @return
*
*/
public Map<String, Object> getToken() {
return getToken(gtDataUsername);
}
/**
*
* Description:取token
*
* @param username
* @return
*
*/
public Map<String, Object> getToken(String username) {
String resourceUrl = MessageFormat.format("{0}?op=GETTOKEN&user={1}",
baseUrl, username);
return restGet(resourceUrl);
}
/**
*
* Description:登录
*
* @param token
* @param time
* @return
*
*/
public Map<String, Object> login(String token, String time) {
return login(gtDataUsername, gtDataPassword, token, time);
}
/**
*
* Description:登录
*
* @param username
* @param password
* @param token
* @param time
* @return
*
*/
public Map<String, Object> login(String username, String password,
String token, String time) {
String resourceUrl = "";
try {
resourceUrl = MessageFormat.format(
"{0}?op=LOGIN&user={1}&pass={2}&token={3}&time={4}",
baseUrl, username,
Encodes.encodeHex(Digests.md5((Encodes.encodeHex(Digests
.md5(password.getBytes())) + token).getBytes())),
token, time);
} catch (IOException e) {
logger.error("password to md5 error.", e);
}
return restGet(resourceUrl);
}
/**
*
* Description:获取sign
*
* @param sign
* @param time
* @return
*
*/
public Map<String, Object> getSign(String sign, String time) {
String resourceUrl = MessageFormat.format(
"{0}?op=GETSIGN&sign={1}&time={2}", baseUrl, sign, time);
return restGet(resourceUrl);
}
/**
*
* Description:登出
*
* @param token
* @return
*
*/
public Map<String, Object> logout(String token) {
String resourceUrl = MessageFormat.format("{0}?op=LOGOUT&token={1}",
baseUrl, token);
return restGet(resourceUrl);
}
/**
*
* Description:组用户注册普通用户
*
* @param username
* 普通用户名
* @param password
* MD5(密码)
* @param totalSize
* 普通用户空间的总大小(bytes)
* @return
*
*/
public Map<String, Object> register(String username, String password,
String totalSize) {
return register(username, password, totalSize, defaultSign, defaultTime);
}
/**
*
* Description:组用户注册普通用户
*
* @param username
* 普通用户名
* @param password
* MD5(密码)
* @param totalSize
* 普通用户空间的总大小(bytes)
* @param sign
* @param time
* @return
*
*/
public Map<String, Object> register(String username, String password,
String totalSize, String sign, String time) {
String resourceUrl = MessageFormat.format(
"{0}?op=GREG&user={1}&pass={2}&total={3}&sign={4}&time={5}",
baseUrl, username, password, totalSize, sign, time);
return restGet(resourceUrl);
}
/**
*
* Description:删除普通用户
*
* @param username
* 普通用户名
* @return
*
*/
public Map<String, Object> deleteUser(String username) {
return deleteUser(username, defaultSign, defaultTime);
}
/**
*
* Description:删除普通用户
*
* @param username
* 普通用户名
* @param sign
* @param time
* @return
*
*/
public Map<String, Object> deleteUser(String username, String sign,
String time) {
String resourceUrl = MessageFormat.format(
"{0}?op=GDELUSER&user={1}&sign={2}&time={3}", baseUrl,
username, sign, time);
return restGet(resourceUrl);
}
/**
*
* Description:组用户修改自己的密码
*
* @param newPassword
* MD5(新密码)
* @return
*
*/
public Map<String, Object> changePassword(String newPassword) {
return changePassword(newPassword, defaultSign, defaultTime);
}
/**
*
* Description:组用户修改自己的密码
*
* @param newPassword
* MD5(新密码)
* @param sign
* @param time
* @return
*
*/
public Map<String, Object> changePassword(String newPassword, String sign,
String time) {
String resourceUrl = MessageFormat.format(
"{0}?op=CHANGEPWD&newpass={1}&sign={2}&time={3}", baseUrl,
newPassword, sign, time);
return restGet(resourceUrl);
}
/**
*
* Description:组用户修改普通用户的密码
*
* @param username
* 普通用户名
* @param newPassword
* MD5(新密码)
* @return
*
*/
public Map<String, Object> changeUserPassword(String username,
String newPassword) {
return changeUserPassword(username, newPassword, defaultSign,
defaultTime);
}
/**
*
* Description:组用户修改普通用户的密码
*
* @param username
* 普通用户名
* @param newPassword
* MD5(新密码)
* @param sign
* @param time
* @return
*
*/
public Map<String, Object> changeUserPassword(String username,
String newPassword, String sign, String time) {
String resourceUrl = MessageFormat.format(
"{0}?op=GCHANGEPWD&user={1}&newpass={2}&sign={3}&time={4}",
baseUrl, username, newPassword, sign, time);
return restGet(resourceUrl);
}
/**
*
* Description:组用户修改普通用户容量
*
* @param username
* 普通用户名
* @param newSize
* 修改后的空间的总大小(bytes)
* @return
*
*/
public Map<String, Object> changeUserSize(String username, long newSize) {
return changeUserSize(username, newSize, defaultSign, defaultTime);
}
/**
*
* Description:组用户修改普通用户容量
*
* @param username
* 普通用户名
* @param newSize
* 修改后的空间的总大小(bytes)
* @param sign
* @param time
* @return
*
*/
public Map<String, Object> changeUserSize(String username, long newSize,
String sign, String time) {
String resourceUrl = MessageFormat.format(
"{0}?op=GCHANGESIZE&user={1}&newsize={2}&sign={3}&time={4}",
baseUrl, username, newSize + "", sign, time);
return restGet(resourceUrl);
}
/**
* 修改文件目录的权限
*
* @param path
* @param newpermisson
* @return
*/
public Map<String, Object> changePermisson(String path, String newpermisson) {
return changePermisson(path, newpermisson, defaultSign, defaultTime);
}
/**
* 修改文件目录的权限
*
* @param path
* @param newpermisson
* @param sign
* @param time
* @return
*/
public Map<String, Object> changePermisson(String path,
String newpermisson, String sign, String time) {
String resourceUrl = MessageFormat.format(
"{0}{1}?op=CHANGEPERMISSON&newpermisson={2}&sign={3}&time={4}",
gtDataUrl, path, newpermisson, sign, time);
return restGet(resourceUrl);
}
/**
*
* Description:组用户获取普通用户容量等信息
*
* @param username
* 普通用户名
* @return
*
*/
public Map<String, Object> userInfo(String username) {
return userInfo(username, defaultSign, defaultTime);
}
/**
*
* Description:组用户获取普通用户容量等信息
*
* @param username
* 普通用户名
* @param sign
* @param time
* @return
*
*/
public Map<String, Object> userInfo(String username, String sign,
String time) {
String resourceUrl = MessageFormat.format(
"{0}?op=GGETUSERINFO&user={1}&sign={2}&time={3}", baseUrl,
username, sign, time);
return restGet(resourceUrl);
}
/**
*
* Description:根据路径创建文件夹
*
* @param path
* @return
*
*/
public Map<String, Object> mkdirs(String path) {
return mkdirs(path, defaultSign, defaultTime);
}
/**
*
* Description:根据路径创建文件夹
*
* @param path
* @param sign
* @param time
* @return
*
*/
public Map<String, Object> mkdirs(String path, String sign, String time) {
String resourceUrl = MessageFormat.format(
"{0}{1}?op=MKDIRS&sign={2}&time={3}", gtDataUrl, path, sign,
time);
return rest(resourceUrl, HttpMethod.PUT, null);
}
/**
* Description:根据路径递归创建多级文件夹
*
* @param path
*/
public Map<String, Object> mkdir(String path) {
String parentPath = StringUtils.substringBeforeLast(path, "/");
if (logger.isInfoEnabled()) {
logger.info("path:{},parentPath:{},isExist(parentPath):{},", path,parentPath,isExist(parentPath).get("exist"));
}
if ( isExist(parentPath).get("exist").toString().equals("true")) {
return mkdirs(path);
} else {
mkdir(parentPath);
return mkdirs(path);
}
}
/**
*
* Description:文件或文件夹重命名
*
* @param path
* @param newPath
* @return
*
*/
public Map<String, Object> move(String path, String newPath) {
return move(path, newPath, defaultSign, defaultTime);
}
/**
*
* Description:文件或文件夹重命名
*
* @param path
* @param newPath
* @param sign
* @param time
* @return
*
*/
public Map<String, Object> move(String path, String newPath, String sign,
String time) {
String resourceUrl = MessageFormat.format(
"{0}{1}?op=MOVE&destination={2}&sign={3}&time={4}", gtDataUrl,
path, newPath, sign, time);
return rest(resourceUrl, HttpMethod.PUT, null);
}
/**
*
* Description:删除文件或文件夹
*
* @param path
* @return
*
*/
public Map<String, Object> delete(String path) {
return delete(path, true, defaultSign, defaultTime);
}
/**
*
* Description:删除文件或文件夹
*
* @param path
* @param sign
* @param time
* @return
*
*/
public Map<String, Object> delete(String path, boolean recursive,
String sign, String time) {
String resourceUrl = MessageFormat.format(
"{0}{1}?op=DELETE&recursive={2}&sign={3}&time={4}", gtDataUrl,
path, recursive, sign, time);
return rest(resourceUrl, HttpMethod.DELETE, null);
}
/**
*
* Description:复制文件或文件夹到指定路径
*
* @param path
* @param newPath
* @return
*
*/
public Map<String, Object> copy(String path, String newPath) {
return copy(path, newPath, defaultSign, defaultTime);
}
/**
*
* Description:复制文件或文件夹到指定路径
*
* @param path
* @param newPath
* @param sign
* @param time
* @return
*
*/
public Map<String, Object> copy(String path, String newPath, String sign,
String time) {
String resourceUrl = MessageFormat.format(
"{0}{1}?op=COPY&destination={2}&sign={3}&time={4}", gtDataUrl,
path, newPath, sign, time);
return rest(resourceUrl, HttpMethod.PUT, null);
}
/**
* 复制文件或文件夹到指定路径(带权限)
*
* @param path
* @param newPath
* @param newcapflag
* @param newpermisson
* @return
*/
public Map<String, Object> copyWithPermisson(String path, String newPath,
String newcapflag, String newpermisson) {
String resourceUrl = MessageFormat
.format("{0}{1}?op=COPY&destination={2}&sign={3}&time={4}&newcapflag={5}&newpermisson={6}",
gtDataUrl, path, newPath, defaultSign, defaultTime,
newcapflag, newpermisson);
return rest(resourceUrl, HttpMethod.PUT, null);
}
/**
*
* Description:显示指定路径[文件/文件夹(包括子文件)]的属性
*
* @param path
* @return
* 成功({key:HttpStatusCode,value:200},{key:files,value:List<GtdataFile
* >})
*
*/
public Map<String, Object> list(String path) {
return list(path, gtDataUsername, true, defaultSign, defaultTime);
}
/**
*
* Description:显示指定路径[文件/文件夹(包括子文件)]的属性
*
* @param path
* @param username
* @param recursive
* @param sign
* @param time
* @return
* 成功({key:HttpStatusCode,value:200},{key:files,value:List<GtdataFile
* >})
*
*/
public Map<String, Object> list(String path, String username,
boolean recursive, String sign, String time) {
String resourceUrl = MessageFormat.format(
"{0}{1}?op=LIST&user={2}&recursive={3}&sign={4}&time={5}",
gtDataUrl, path, username, recursive, sign, time);
Map<String, Object> responseMap = restGet(resourceUrl);
Map<String, Object> myResponseMap = new HashMap<String, Object>();
if (responseMap != null
&& 200 == (Integer) responseMap.get("HttpStatusCode")) {
List<GtdataFile> gtdataFiles = mapToGtdataFiles(responseMap);
myResponseMap.put("files", gtdataFiles);
myResponseMap.put("HttpStatusCode", 200);// 调用成功
return myResponseMap;
}
return responseMap;
}
/**
*
* Description:(只能在Linux环境使用)根据路径读取文件内容(支持大文件)
*
* @param filePath
* @param path
* @return
*
*/
public Map<String, Object> openLarge(String filePath, String path) {
return openLarge(filePath, path, defaultSign, defaultTime);
}
/**
*
* Description:(只能在Linux环境使用)根据路径读取文件内容(支持大文件)
*
* @param filePath
* 文件保存的路径
* @param path
* @param sign
* @param time
* @return
*
*/
public Map<String, Object> openLarge(String filePath, String path,
String sign, String time) {
String resourceUrl = MessageFormat
.format("{0}{1}?op=OPEN&sign={2}&time={3}", gtDataUrl, path,
sign, time);
try {
// TODO 调curl进行下载,只能在Linux环境使用
String curlString = MessageFormat.format("curl -o {0} {1}",
filePath, "\"" + resourceUrl + "\"");
String jsonResult = ExecLinuxCmd.exec(curlString);
if (jsonResult != null && !"".equals(jsonResult)) {
Map<String, Object> responseMap = jsonMapper.fromJson(
jsonResult, HashMap.class);
return responseMap;
}
Map<String, Object> success = new HashMap<String, Object>();
success.put("HttpStatusCode", 200);// 调用成功
return success;
} catch (Exception e) {
String message = MessageFormat.format(
"call gtdata rest api [{0}] by linux curl throw exception",
resourceUrl);
logger.error(message, e);
Map<String, Object> error = new HashMap<String, Object>();
error.put("HttpStatusCode", 500);// 调用失败
return error;
}
}
/**
*
* Description:根据路径读取文件内容 如果出现内存溢出,请使用openLarge(只能在Linux环境使用)
*
* @see #openLarge(String, String)
*
* @param path
* @return
* 成功({key:HttpStatusCode,value:200},{key:file,value:ByteArrayInputStream
* })
*
*/
public Map<String, Object> open(String path) {
return open(path, defaultSign, defaultTime);
}
/**
*
* Description:根据路径读取文件内容(小文件,1G以内的) 如果出现内存溢出,请使用openLarge(只能在Linux环境使用)
*
* @see #openLarge(String, String, String, String)
*
* @param path
* @param sign
* @param time
* @return 成功({key:HttpStatusCode,value:200},{key:file,value:byte[]})
*
*/
public Map<String, Object> open(String path, String sign, String time) {
String resourceUrl = MessageFormat
.format("{0}{1}?op=OPEN&sign={2}&time={3}", gtDataUrl, path,
sign, time);
try {
ResponseEntity<byte[]> responseEntity = rest(resourceUrl,
HttpMethod.GET, null, byte[].class);
Map<String, Object> success = new HashMap<String, Object>();
success.put("HttpStatusCode", 200);// 调用成功
if (responseEntity.getBody() != null
&& 0 < responseEntity.getBody().length) {
success.put("file", responseEntity.getBody());
}
return success;
} catch (HttpStatusCodeException e) {
String message = MessageFormat
.format("call gtdata rest api [{0}] throw exception: http status code {1}, response body {2}",
resourceUrl, e.getStatusCode().value(),
e.getResponseBodyAsString());
logger.error(message, e);
Map<String, Object> error = new HashMap<String, Object>();
error.put("HttpStatusCode", e.getStatusCode().value());// 调用失败
if (e.getResponseBodyAsString() != null
&& !"".equals(e.getResponseBodyAsString())) {
Map<String, Object> exceptionMap = jsonMapper.fromJson(
e.getResponseBodyAsString(), HashMap.class);
if (exceptionMap != null && !exceptionMap.isEmpty()) {
error.putAll(exceptionMap);
}
}
return error;
}
}
/**
* 通过httpclient下载数据,并输入到outputstream中
*
* @param path
* @param output
* @return
*/
public Map<String, Object> openByHttpClient(String path, OutputStream output) {
return openByHttpClient(path, output, defaultSign, defaultTime);
}
public Map<String, Object> openByHttpClient(String path,
OutputStream output, String sign, String time) {
String resourceUrl = MessageFormat
.format("{0}{1}?op=OPEN&sign={2}&time={3}", gtDataUrl, path,
sign, time);
Map<String, Object> result = new HashMap<String, Object>();
try {
result = HttpUtils.GetFile(resourceUrl, output);
if ((Integer) result.get("HttpStatusCode") != HttpStatus.SC_OK) {
String message = MessageFormat
.format("call gtdata rest api [{0}] throw exception: http status code {1}, response body {2}",
resourceUrl, result.get("HttpStatusCode"),
result);
logger.error(message);
}
return result;
} catch (IOException e) {
String message = MessageFormat.format(
"call gtdata rest api [{0}] throw IOException: {1}",
resourceUrl, e.getMessage());
logger.error(message, e);
result.put("HttpStatusCode", 500);
} finally {
IOUtils.closeQuietly(output);
}
return result;
}
/**
*
* Description:单独上传文件的MD5值
*
* @param filePath
* @param path
* @param sign
* @param time
* @return
*
*/
public Map<String, Object> md5(String filePath, String path, String sign,
String time, String md5) {// xsx modified
String resourceUrlMd5 = MessageFormat.format(
"{0}{1}?op=MD5&value={2}&sign={3}&time={4}", gtDataUrl, path,
md5, sign, time);
return rest(resourceUrlMd5, HttpMethod.PUT, null);
}
/**
*
* Description:(只能在Linux环境使用)根据路径创建并写入文件(包含上传文件的MD5、覆盖旧文件)
*
* @param filePath
* @param path
* @return
*
*/
public Map<String, Object> createLarge(String filePath, String path) {
return createLarge(filePath, path, defaultSign, defaultTime);
}
/**
*
* Description:(只能在Linux环境使用)根据路径创建并写入文件(包含上传文件的MD5、覆盖旧文件)
*
* @param filePath
* @param path
* @param sign
* @param time
* @return
*
*/
public Map<String, Object> createLarge(String filePath, String path,
String sign, String time) {
return createLarge(filePath, path, sign, time, true);// 覆盖旧文件
}
/**
*
* Description:(只能在Linux环境使用)根据路径创建并写入文件(包含上传文件的MD5)
*
* @param filePath
* @param path
* @param sign
* @param time
* @param overwrite
* @return
*
*/
public Map<String, Object> createLarge(String filePath, String path,
String sign, String time, boolean overwrite) {
String md5 = "";
try {
md5 = fileToMd5(filePath);
} catch (Exception e) {
Map<String, Object> error = new HashMap<String, Object>();
error.put("HttpStatusCode", 0);// 上传文件不存在
return error;
}
Map<String, Object> responseMap = md5(filePath, path, sign, time, md5);
if (responseMap != null
&& (200 == (Integer) responseMap.get("HttpStatusCode") || 404 != (Integer) responseMap
.get("HttpStatusCode"))) {
return responseMap;// 已存在该文件,无需上传(秒传) 或 异常
}
String resourceUrl = MessageFormat.format(
"{0}{1}?op=CREATE&md5={2}&sign={3}&time={4}&overwrite={5}",
gtDataUrl, path, md5, sign, time, overwrite);
try {
// TODO 调curl进行上传,只能在Linux环境使用
String curlString = MessageFormat.format("curl -T {0} -X PUT {1}",
filePath, "\"" + resourceUrl + "\"");
String jsonResult = ExecLinuxCmd.exec(curlString);
Map<String, Object> responseMap2 = jsonMapper.fromJson(jsonResult,
HashMap.class);
return responseMap2;
} catch (Exception e) {
String message = MessageFormat.format(
"call gtdata rest api [{0}] by linux curl throw exception",
resourceUrl);
logger.error(message, e);
Map<String, Object> error = new HashMap<String, Object>();
error.put("HttpStatusCode", 500);// 调用失败
return error;
}
}
/**
*
* Description:(小文件,1G以内的)根据路径创建并写入文件(包含上传文件的MD5)
* 如果出现内存溢出,请使用createLarge(只能在Linux环境使用)
*
* @see #createLarge(String, String)
*
* @param filePath
* @param path
* @return
*
*/
public Map<String, Object> create(String filePath, String path) {
return create(filePath, path, defaultSign, defaultTime);
}
/**
*
* Description:(小文件,1G以内的)根据路径创建并写入文件(包含上传文件的MD5)
* 如果出现内存溢出,请使用createLarge(只能在Linux环境使用)
*
* @see #createLarge(String, String, String, String)
*
* @param filePath
* @param path
* @param sign
* @param time
* @return
*
*/
public Map<String, Object> create(String filePath, String path,
String sign, String time) {
return create(filePath, path, sign, time, true);// 覆盖旧文件
}
/**
*
* Description:(小文件,1G以内的)根据路径创建并写入文件(包含上传文件的MD5)
* 如果出现内存溢出,请使用createLarge(只能在Linux环境使用)
*
* @see #createLarge(String, String, String, String, boolean)
*
* @param filePath
* @param path
* @param sign
* @param time
* @param overwrite
* @return
*
*/
public Map<String, Object> create(String filePath, String path,
String sign, String time, boolean overwrite) {
String md5 = "";
try {
md5 = fileToMd5(filePath);
} catch (Exception e) {
Map<String, Object> error = new HashMap<String, Object>();
error.put("HttpStatusCode", 0);// 上传文件不存在
return error;
}
Map<String, Object> responseMap = md5(filePath, path, sign, time, md5);
if (responseMap != null
&& (200 == (Integer) responseMap.get("HttpStatusCode") || 404 != (Integer) responseMap
.get("HttpStatusCode"))) {
return responseMap;// 已存在该文件,无需上传(秒传) 或 异常
}
String resourceUrl = MessageFormat.format(
"{0}{1}?op=CREATE&md5={2}&sign={3}&time={4}&overwrite={5}",
gtDataUrl, path, md5, sign, time, overwrite);
try {
HttpEntity<byte[]> httpEntity = new HttpEntity(
IOUtils.toByteArray(new FileInputStream(filePath)));
Map<String, Object> responseMap2 = rest(resourceUrl,
HttpMethod.PUT, httpEntity);
return responseMap2;
} catch (Exception e) {
String message = MessageFormat.format(
"call gtdata rest api [{0}] by linux curl throw exception",
resourceUrl);
logger.error(message, e);
Map<String, Object> error = new HashMap<String, Object>();
error.put("HttpStatusCode", 500);// 调用失败
return error;
}
}
public Map<String, Object> createByHttpCilent(String filePath, String path) {
return createByHttpCilent(filePath, path, defaultSign, defaultTime,
true);
}
public Map<String, Object> createByHttpCilent(String filePath, String path,
String sign, String time, boolean overwrite) {
String md5 = "";
try {
md5 = fileToMd5(filePath);
} catch (Exception e) {
Map<String, Object> error = new HashMap<String, Object>();
error.put("HttpStatusCode", 0);// 上传文件不存在
return error;
}
Map<String, Object> responseMap = md5(filePath, path, sign, time, md5);
if (responseMap != null
&& (200 == (Integer) responseMap.get("HttpStatusCode") || 404 != (Integer) responseMap
.get("HttpStatusCode"))) {
return responseMap;// 已存在该文件,无需上传(秒传) 或 异常
}
String resourceUrl = MessageFormat.format(
"{0}{1}?op=CREATE&md5={2}&sign={3}&time={4}&overwrite={5}",
gtDataUrl, path, md5, sign, time, overwrite);
try {
Map<String, Object> responseMap2 = HttpUtils.putFile(resourceUrl,
new File(filePath));
return responseMap2;
} catch (Exception e) {
String message = MessageFormat.format(
"call gtdata rest api [{0}] by linux curl throw exception",
resourceUrl);
logger.error(message, e);
Map<String, Object> error = new HashMap<String, Object>();
error.put("HttpStatusCode", 500);// 调用失败
return error;
}
}
/**
*
* Description:统计路径下的文件总大小(包含子目录的文件)
*
* @param path
* @return 成功({key:HttpStatusCode,value:200},{key:totalSize,value:总大小字节})
*
*/
public Map<String, Object> countFileSize(String path) {
return countFileSize(path, gtDataUsername, true, defaultSign,
defaultTime);
}
/**
*
* Description:统计路径下的文件总大小
*
* @param path
* @param username
* @param recursive
* @param sign
* @param time
* @return 成功({key:HttpStatusCode,value:200},{key:totalSize,value:总大小字节})
*
*/
public Map<String, Object> countFileSize(String path, String username,
boolean recursive, String sign, String time) {
Map<String, Object> responseMap = list(path, username, recursive, sign,
time);
if (responseMap != null && responseMap.containsKey("files")) {
List<GtdataFile> gtdataFiles = (List<GtdataFile>) responseMap
.get("files");
Map<String, Object> success = new HashMap<String, Object>();
success.put("HttpStatusCode", 200);// 调用成功
success.put("totalSize", countFileSize(gtdataFiles));
return success;
}
return responseMap;
}
/**
*
* Description:判断文件或文件夹是否存在
*
* @param path
* @return 存在(key:exist,value:true),不存在(key:exist,value:true)
*
*/
public Map<String, Object> isExist(String path) {
return isExist(path, gtDataUsername, defaultSign, defaultTime);
}
/**
*
* Description:判断文件或文件夹是否存在
*
* @param path
* @param username
* @param sign
* @param time
* @return 存在(key:exist,value:true),不存在(key:exist,value:true)
*
*/
public Map<String, Object> isExist(String path, String username,
String sign, String time) {
Map<String, Object> responseMap = list(path, username, false, sign,
time);
if (responseMap != null
&& 200 == (Integer) responseMap.get("HttpStatusCode")) {
responseMap = new HashMap<String, Object>();
responseMap.put("HttpStatusCode", 200);
responseMap.put("exist", true);
return responseMap;
}
if (responseMap != null
&& 404 == (Integer) responseMap.get("HttpStatusCode")) {
responseMap = new HashMap<String, Object>();
responseMap.put("HttpStatusCode", 404);
responseMap.put("exist", false);
return responseMap;
}
return responseMap;
}
/**
*
* Description:计算文件总大小
*
* @param gtdataFiles
* @return
*
*/
protected long countFileSize(List<GtdataFile> gtdataFiles) {
long total = 0;
for (GtdataFile gtdataFile : gtdataFiles) {
if (!"-1".equals(gtdataFile.getSize())) {
total += Long.valueOf(gtdataFile.getSize());
}
if (gtdataFile.getChild() != null
&& !gtdataFile.getChild().isEmpty()) {
total += countFileSize(gtdataFile.getChild());
}
}
return total;
}
/**
* @Description rest方式请求封装(resourceUrl不带sign和time)
* @param resourceUrl
* @param httpMethod
* @return
*/
public Map<String, Object> restWithoutSignAndTime(String resourceUrl, HttpMethod httpMethod){
resourceUrl =gtDataUrl+resourceUrl+ MessageFormat.format("&sign={0}&time={1}",defaultSign, defaultTime);
return rest(resourceUrl,httpMethod,null);
}
/**
*
* Description:rest方式Get请求封装
*
* @param resourceUrl
* @return
*
*/
public Map<String, Object> restGet(String resourceUrl) {
return rest(resourceUrl, HttpMethod.GET, null);
}
/**
*
* Description:rest方式请求封装
*
* @param resourceUrl
* @param httpMethod
* @param httpEntity
* @return
*
*/
protected <T> Map<String, Object> rest(String resourceUrl,
HttpMethod httpMethod, HttpEntity<T> httpEntity) {
try {
ResponseEntity<HashMap> responseEntity = rest(resourceUrl,
httpMethod, httpEntity, HashMap.class);
Map<String, Object> success = new HashMap<String, Object>();
success.put("HttpStatusCode", responseEntity.getStatusCode()
.value());// 调用成功
if (responseEntity.getBody() != null
&& !responseEntity.getBody().isEmpty()) {
success.putAll(responseEntity.getBody());
}
return success;
} catch (HttpStatusCodeException e) {
String message = MessageFormat
.format("call gtdata rest api [{0}] throw exception: http status code {1}, response body {2}",
resourceUrl, e.getStatusCode().value(),
e.getResponseBodyAsString());
logger.debug(message, e);
Map<String, Object> error = new HashMap<String, Object>();
error.put("HttpStatusCode", e.getStatusCode().value());// 调用失败
if (e.getResponseBodyAsString() != null
&& !"".equals(e.getResponseBodyAsString())) {
Map<String, Object> exceptionMap = jsonMapper.fromJson(
e.getResponseBodyAsString(), HashMap.class);
if (exceptionMap != null && !exceptionMap.isEmpty()) {
error.putAll(exceptionMap);
}
}
if (HttpStatus.SC_FORBIDDEN == e.getStatusCode().value()) {
logger.warn("FORBIDDEN 403, relogin...", e);
logout(defaultToken);
login(); // 403时,再试一次更新认证信息
}
return error;
}
}
/**
*
* Description:rest方式请求封装
*
* @param resourceUrl
* @param httpMethod
* @param httpEntity
* @param elementClass
* @return
*
*/
protected <T, E> ResponseEntity<E> rest(String resourceUrl,
HttpMethod httpMethod, HttpEntity<T> httpEntity,
Class<E> elementClass) {
UriComponents uriComponents = UriComponentsBuilder.fromUriString(
resourceUrl).build();
ResponseEntity<E> responseEntity = restTemplate.exchange(
uriComponents.toUri(), httpMethod, httpEntity, elementClass);
return responseEntity;
}
/**
*
* Description:计算文件的md5值
*
* @param filePath
* @return
* @throws IOException
*
*/
protected String fileToMd5(String filePath) throws IOException {
File file = new File(filePath);
return Encodes.encodeHex(Digests.md5(new FileInputStream(file)));
}
/**
* Description:Map转ShareFile
*
* @param responseMap
* @return
*/
protected List<ShareFile> mapToShareFiles(Map<String, Object> responseMap,
String keyValue) {
List<ShareFile> shareFiles = new ArrayList<ShareFile>();
if (responseMap.containsKey(keyValue)) {
for (Map fileMap : (List<Map>) responseMap.get(keyValue)) {
ShareFile shareFile = new ShareFile();
if (keyValue.equals("friends")) { // 获取所有好友只有name属性
shareFile.setName((String) fileMap.get("name"));
} else if (keyValue.equals("groups")) { // 列取用户所属所有组:(包含有id
// 与name属性)
shareFile.setId((String) fileMap.get("id"));
shareFile.setName((String) fileMap.get("name"));
} else if (keyValue.equals("groupshare")
|| keyValue.equals("friendshare")) { // 查看组分享 OR 查看好友分享
shareFile.setId((String) fileMap.get("id"));
shareFile.setName((String) fileMap.get("name"));
shareFile.setUser((String) fileMap.get("user"));
shareFile.setSharetime((String) fileMap.get("sharetime"));
shareFile.setSize((String) fileMap.get("size"));
} else if (keyValue.equals("myshare")) { // 查看我的分享
shareFile.setId((String) fileMap.get("id"));
shareFile.setName((String) fileMap.get("name"));
shareFile.setPath((String) fileMap.get("path"));
shareFile.setSharetime((String) fileMap.get("sharetime"));
shareFile.setIsdir((String) fileMap.get("isdir"));
}
shareFiles.add(shareFile);
}
}
return shareFiles;
}
/**
*
* Description:Map转GtdataFile 用于查询猎取分享目录
*
* @param responseMap
* @return
*
*/
protected List<ShareFile> mapToShareFilesToQueryList(
Map<String, Object> responseMap) {
List<ShareFile> shareFiles = new ArrayList<ShareFile>();
if (responseMap.containsKey("files")) { // 当前属于文件夹
/*
* ShareFile shareFile= new ShareFile();
* shareFile.setId((String)responseMap.get("id"));
* shareFile.setUser((String)responseMap.get("user"));
* shareFile.setPath((String)responseMap.get("path"));
* shareFile.setSharetime((String)responseMap.get("sharetime"));
* shareFile.setSize((String)responseMap.get("size"));
*/
for (Map fileMap : (List<Map>) responseMap.get("files")) {
ShareFile shareFile0 = new ShareFile();
shareFile0.setId((String) fileMap.get("id"));
shareFile0.setUser((String) fileMap.get("user"));
shareFile0.setPath((String) fileMap.get("path"));
shareFile0.setSharetime((String) fileMap.get("sharetime"));
shareFile0.setSize((String) fileMap.get("size"));
List<ShareFile> child = null;
if (fileMap.containsKey("files")) {
child = mapToShareFilesToQueryList(fileMap);// 递归
}
shareFile0.setChild(child);
shareFiles.add(shareFile0);
}
} else { // 当前目录属于文件
ShareFile shareFile = new ShareFile();
shareFile.setId((String) responseMap.get("id"));
shareFile.setUser((String) responseMap.get("user"));
shareFile.setPath((String) responseMap.get("path"));
shareFile.setSharetime((String) responseMap.get("sharetime"));
shareFile.setSize((String) responseMap.get("size"));
shareFiles.add(shareFile);
}
return shareFiles;
}
protected List<GtdataFile> mapToGtdataFiles(Map<String, Object> responseMap) {
List<GtdataFile> gtdataFiles = new ArrayList<GtdataFile>();
if (responseMap.containsKey("files")) {
for (Map fileMap : (List<Map>) responseMap.get("files")) {
GtdataFile gtdataFile = new GtdataFile();
gtdataFile.setPath((String) fileMap.get("path"));
gtdataFile.setSize((String) fileMap.get("size"));
gtdataFile.setTime(new DateTime(Long.parseLong(fileMap
.get("time") + "000")).toString("yyyy-MM-dd HH:mm:ss"));
gtdataFile.setFilename(StringUtils.substringAfterLast(
gtdataFile.getPath(), "/"));
List<GtdataFile> child = null;
if (fileMap.containsKey("files")) {
child = mapToGtdataFiles(fileMap);// 递归
}
gtdataFile.setChild(child);
gtdataFiles.add(gtdataFile);
}
} else {
GtdataFile gtdataFile = new GtdataFile();
gtdataFile.setPath((String) responseMap.get("path"));
gtdataFile.setSize((String) responseMap.get("size"));
gtdataFile.setTime(new DateTime(Long.parseLong(responseMap
.get("time") + "000")).toString("yyyy-MM-dd HH:mm:ss"));
gtdataFile.setFilename(StringUtils.substringAfterLast(
gtdataFile.getPath(), "/"));
gtdataFiles.add(gtdataFile);
}
return gtdataFiles;
}
/**
*
* Description: 登陆并更新认证信息
*
*/
protected void login() throws GtDataRestException {
Map<String, Object> tokenMap = getToken();
defaultToken = (String) tokenMap.get("token");
defaultTime = (String) tokenMap.get("time");
if (200 != (Integer) tokenMap.get("HttpStatusCode")) {
throw new GtDataRestException((String) tokenMap.get("errorCode"));
}
Map<String, Object> loginMap = login(defaultToken, defaultTime);
defaultTime = (String) loginMap.get("time");
defaultSign = (String) loginMap.get("sign");
if (200 != (Integer) loginMap.get("HttpStatusCode")) {
throw new GtDataRestException((String) loginMap.get("errorCode"));
}
}
/**
*
* Description: 更新认证信息
*
*/
protected void updateAuth() throws GtDataRestException {
Map<String, Object> signMap = getSign(defaultSign, defaultTime);
defaultTime = (String) signMap.get("time");
defaultSign = (String) signMap.get("sign");
if (200 != (Integer) signMap.get("HttpStatusCode")) {
throw new GtDataRestException((String) signMap.get("errorCode"));
}
}
/**
* Description:创建逻辑组
*
* @param groupName
* 逻辑组名称
* @return
*
*/
public Map<String, Object> createLogicGroup(String groupName) {
String resourceUrl = MessageFormat.format(
"{0}?op=CREATELOGICGROUP&sign={1}&time={2}&groupname={3}",
gtDataUrl, defaultSign, defaultTime, groupName);
Map<String, Object> responseMap = restGet(resourceUrl);
Map<String, Object> myResponseMap = new HashMap<String, Object>();
if (responseMap != null
&& 200 == (Integer) responseMap.get("HttpStatusCode")) {
myResponseMap.put("HttpStatusCode", 200);// 调用成功
myResponseMap.putAll(responseMap);
return myResponseMap;
}
return responseMap;
}
/**
* Description:增加逻辑组成员
*
* @param groupId
* 逻辑组ID
* @param userName
* 成员名称
* @return
*/
public Map<String, Object> addToLogicGroup(String groupId, String userName) {
String resourceUrl = MessageFormat
.format("{0}?op=ADDTOLOGICGROUP&sign={1}&time={2}&groupid={3}&user={4}",
gtDataUrl, defaultSign, defaultTime, groupId, userName);
Map<String, Object> responseMap = restGet(resourceUrl);
Map<String, Object> myResponseMap = new HashMap<String, Object>();
if (responseMap != null
&& 200 == (Integer) responseMap.get("HttpStatusCode")) {
myResponseMap.put("HttpStatusCode", 200);// 调用成功
myResponseMap.putAll(responseMap);
return myResponseMap;
}
return responseMap;
}
/**
* Description:删除逻辑组成员
*
* @param groupId
* 用户所属的组id
* @param userName
* 要删除的用户名
* @return
*/
public Map<String, Object> delFromLogicGroup(String groupId, String userName) {
String resourceUrl = MessageFormat
.format("{0}?op=DELFROMLOGICGROUP&sign={1}&time={2}&groupid={3}&user={4}",
gtDataUrl, defaultSign, defaultTime, groupId, userName);
Map<String, Object> responseMap = restGet(resourceUrl);
Map<String, Object> myResponseMap = new HashMap<String, Object>();
if (responseMap != null
&& 200 == (Integer) responseMap.get("HttpStatusCode")) {
myResponseMap.put("HttpStatusCode", 200);// 调用成功
myResponseMap.putAll(responseMap);
return myResponseMap;
}
return responseMap;
}
/**
* Description:添加好友
*
* @param userName
* 好友用户名
* @return
*/
public Map<String, Object> addFriend(String userName) {
String resourceUrl = MessageFormat.format(
"{0}?op=ADDFRIEND&sign={1}&time={2}&user={3}", gtDataUrl,
defaultSign, defaultTime, userName);
Map<String, Object> responseMap = restGet(resourceUrl);
Map<String, Object> myResponseMap = new HashMap<String, Object>();
if (responseMap != null
&& 200 == (Integer) responseMap.get("HttpStatusCode")) {
myResponseMap.put("HttpStatusCode", 200);// 调用成功
myResponseMap.putAll(responseMap);
return myResponseMap;
}
return responseMap;
}
/**
* Description:删除好友
*
* @param userName
* 好友用户名
* @return
*/
public Map<String, Object> delFriend(String userName) {
String resourceUrl = MessageFormat.format(
"{0}?op=DELFRIEND&sign={1}&time={2}&user={3}", gtDataUrl,
defaultSign, defaultTime, userName);
Map<String, Object> responseMap = restGet(resourceUrl);
Map<String, Object> myResponseMap = new HashMap<String, Object>();
if (responseMap != null
&& 200 == (Integer) responseMap.get("HttpStatusCode")) {
myResponseMap.put("HttpStatusCode", 200);// 调用成功
myResponseMap.putAll(responseMap);
return myResponseMap;
}
return responseMap;
}
/**
* Description:修改逻辑组权限及管理员标志位
*
* @param groupId
* 要修改权限的逻辑组id
* @param userName
* 要修改权限的用户
* @param newpermisson
* 新权限
* @return
*/
public Map<String, Object> modLogicGroupPermisson(String groupId,
String userName, String newpermisson) {
String resourceUrl = MessageFormat
.format("{0}?op=MODLOGICGROUPPERMISSON&sign={1}&time={2}&groupid={3}&user={4}&newpermisson={5}",
gtDataUrl, defaultSign, defaultTime, groupId, userName,
newpermisson);
Map<String, Object> responseMap = restGet(resourceUrl);
Map<String, Object> myResponseMap = new HashMap<String, Object>();
if (responseMap != null
&& 200 == (Integer) responseMap.get("HttpStatusCode")) {
myResponseMap.put("HttpStatusCode", 200);// 调用成功
myResponseMap.putAll(responseMap);
return myResponseMap;
}
return responseMap;
}
/**
* Description:修改是否接受分享标志位(逻辑组)
*
* @param groupId
* 要修改的逻辑组id
* @param shareFlag
* 1------接受分享, 0------不接受分享
* @return
*/
public Map<String, Object> modLogicGroupShareFlag(String groupId,
String shareFlag) {
String resourceUrl = MessageFormat
.format("{0}?op=MODLOGICGROUPSHAREFLAG&sign={1}&time={2}&groupid={3}&shareflag={4}",
gtDataUrl, defaultSign, defaultTime, groupId, shareFlag);
Map<String, Object> responseMap = restGet(resourceUrl);
Map<String, Object> myResponseMap = new HashMap<String, Object>();
if (responseMap != null
&& 200 == (Integer) responseMap.get("HttpStatusCode")) {
myResponseMap.put("HttpStatusCode", 200);// 调用成功
myResponseMap.putAll(responseMap);
return myResponseMap;
}
return responseMap;
}
/**
* Description:修改是否接受分享标志位(好友)
*
* @param userName
* 要修改的好友用户
* @param shareFlag
* 1------接受分享, 0------不接受分享
* @return
*/
public Map<String, Object> modFriendShareFlag(String userName,
String shareFlag) {
String resourceUrl = MessageFormat
.format("{0}?op==MODFRIENDSHAREFLAG&sign={1}&time={2}&user={3}&shareflag={4}",
gtDataUrl, defaultSign, defaultTime, userName,
shareFlag);
Map<String, Object> responseMap = restGet(resourceUrl);
Map<String, Object> myResponseMap = new HashMap<String, Object>();
if (responseMap != null
&& 200 == (Integer) responseMap.get("HttpStatusCode")) {
myResponseMap.put("HttpStatusCode", 200);// 调用成功
myResponseMap.putAll(responseMap);
return myResponseMap;
}
return responseMap;
}
/**
* Description:分享至公共云(组分享)
*
* @param path
* @param groupId
* @return
*/
public Map<String, Object> groupShare(String path, String groupId) {
String resourceUrl = MessageFormat.format(
"{0}{1}?op=GROUPSHARE&sign={2}&time={3}&groupid={4}",
gtDataUrl, path, defaultSign, defaultTime, groupId);
Map<String, Object> responseMap = restGet(resourceUrl);
Map<String, Object> myResponseMap = new HashMap<String, Object>();
if (responseMap != null
&& 200 == (Integer) responseMap.get("HttpStatusCode")) {
myResponseMap.put("HttpStatusCode", 200);// 调用成功
myResponseMap.putAll(responseMap);
return myResponseMap;
}
return responseMap;
}
/**
*
* Description:好友分享
*
* @param userName
* 分享给哪个好友的好友名称
* @return
*
*/
public Map<String, Object> friendShare(String userName) {
String resourceUrl = MessageFormat.format(
"{0}{1}?op=FRIENDSHARE&sign={2}&time={3}&user={4}", gtDataUrl,
defaultSign, defaultTime, userName);
Map<String, Object> responseMap = restGet(resourceUrl);
return responseMap;
}
/**
* Description:取消分享
*
* @param groupId
* @return
*
*/
public Map<String, Object> cancelShare(String path, String groupId,
String sharetime) {
String resourceUrl = MessageFormat
.format("{0}{1}?op=CANCELSHARE&sign={2}&time={3}&groupid={4}&sharetime={5}",
gtDataUrl, path, defaultSign, defaultTime, groupId,
sharetime);
Map<String, Object> responseMap = restGet(resourceUrl);
Map<String, Object> myResponseMap = new HashMap<String, Object>();
if (responseMap != null
&& 200 == (Integer) responseMap.get("HttpStatusCode")) {
myResponseMap.put("HttpStatusCode", 200);// 调用成功
myResponseMap.putAll(responseMap);
return myResponseMap;
}
return responseMap;
}
/**
* Description:删除分享
*
* @param groupId
* 分享属于哪个组
* @param username
* 谁分享的
* @param item
* 分享的项目名
* @param sharetime
* 分享时间
* @return
*/
public Map<String, Object> deleteShare(String groupId, String username,
String item, String sharetime) {
String resourceUrl = MessageFormat
.format("{0}?op=DELETESHARE&sign={1}&time={2}&groupid={3}&user={4}&item={5}&sharetime={6}",
gtDataUrl, defaultSign, defaultTime, groupId, username,
item, sharetime);
Map<String, Object> responseMap = restGet(resourceUrl);
Map<String, Object> myResponseMap = new HashMap<String, Object>();
if (responseMap != null
&& 200 == (Integer) responseMap.get("HttpStatusCode")) {
myResponseMap.put("HttpStatusCode", 200);// 调用成功
return myResponseMap;
}
return responseMap;
}
/**
* Description:保存至我的网盘
*
* @param destination
* 目的路径
* @param groupId
* 分享属于哪个组
* @param userName
* 谁分享的
* @param item
* 分享的项目名
* @param sharetime
* 分享时间
* @return
*/
public Map<String, Object> saveToMyDisk(String destination, String groupId,
String userName, String item, String sharetime) {
String resourceUrl = MessageFormat
.format("{0}?op=SAVETOMYDISK&destination={1}&sign={2}&time={3}&groupid={4}&user={5}&item={6}&sharetime={7}",
gtDataUrl, destination, defaultSign, defaultTime,
groupId, userName, item, sharetime);
Map<String, Object> responseMap = restGet(resourceUrl);
Map<String, Object> myResponseMap = new HashMap<String, Object>();
if (responseMap != null
&& 200 == (Integer) responseMap.get("HttpStatusCode")) {
myResponseMap.put("HttpStatusCode", 200);// 调用成功
return myResponseMap;
}
return responseMap;
}
/**
* Description:列取用户所有好友
*
* @return
*/
public Map<String, Object> listAllFriends() {
String resourceUrl = MessageFormat.format(
"{0}?op=LISTALLFRIENDS&sign={1}&time={2}", gtDataUrl,
defaultSign, defaultTime);
Map<String, Object> responseMap = restGet(resourceUrl);
Map<String, Object> myResponseMap = new HashMap<String, Object>();
if (responseMap != null
&& 200 == (Integer) responseMap.get("HttpStatusCode")) {
List<ShareFile> shareFiles = mapToShareFiles(responseMap, "friends");
myResponseMap.put("files", shareFiles);
myResponseMap.put("HttpStatusCode", 200);// 调用成功
return myResponseMap;
}
return responseMap;
}
/**
* Description:列取用户所属所有组
*
* @return
*/
public Map<String, Object> listAllGroups() {
String resourceUrl = MessageFormat.format(
"{0}?op=LISTALLGROUPS&sign={1}&time={2}", gtDataUrl,
defaultSign, defaultTime);
Map<String, Object> responseMap = restGet(resourceUrl);
Map<String, Object> myResponseMap = new HashMap<String, Object>();
if (responseMap != null
&& 200 == (Integer) responseMap.get("HttpStatusCode")) {
List<ShareFile> shareFiles = mapToShareFiles(responseMap, "groups");
myResponseMap.put("files", shareFiles);
myResponseMap.put("HttpStatusCode", 200);// 调用成功
return myResponseMap;
}
return responseMap;
}
/**
* Description:查看组分享
*
* @return
*/
public Map<String, Object> queryGroupShare(String groupId) {
String resourceUrl = MessageFormat.format(
"{0}?op=QUERYGROUPSHARE&sign={1}&time={2}&groupid={3}",
gtDataUrl, defaultSign, defaultTime, groupId);
Map<String, Object> responseMap = restGet(resourceUrl);
Map<String, Object> myResponseMap = new HashMap<String, Object>();
if (responseMap != null
&& 200 == (Integer) responseMap.get("HttpStatusCode")) {
List<ShareFile> shareFiles = mapToShareFiles(responseMap,
"groupshare");
myResponseMap.put("files", shareFiles);
myResponseMap.put("HttpStatusCode", 200);// 调用成功
return myResponseMap;
}
return responseMap;
}
/**
* Description:查看好友分享
*
* @return
*/
public Map<String, Object> queryFriendShare() {
String resourceUrl = MessageFormat.format(
"{0}?op=QUERYFRIENDSHARE &sign={1}&time={2}", gtDataUrl,
defaultSign, defaultTime);
Map<String, Object> responseMap = restGet(resourceUrl);
Map<String, Object> myResponseMap = new HashMap<String, Object>();
if (responseMap != null
&& 200 == (Integer) responseMap.get("HttpStatusCode")) {
List<ShareFile> shareFiles = mapToShareFiles(responseMap,
"friendshare");
myResponseMap.put("files", shareFiles);
myResponseMap.put("HttpStatusCode", 200);// 调用成功
return myResponseMap;
}
return responseMap;
}
/**
* Description:查看我的分享
*
* @return
*/
public Map<String, Object> queryMyShare() {
String resourceUrl = MessageFormat.format(
"{0}?op=QUERYMYSHARE&sign={1}&time={2}", gtDataUrl,
defaultSign, defaultTime);
Map<String, Object> responseMap = restGet(resourceUrl);
Map<String, Object> myResponseMap = new HashMap<String, Object>();
if (responseMap != null
&& 200 == (Integer) responseMap.get("HttpStatusCode")) {
List<ShareFile> shareFiles = mapToShareFiles(responseMap, "myshare");
myResponseMap.put("files", shareFiles);
myResponseMap.put("HttpStatusCode", 200);// 调用成功
return myResponseMap;
}
return responseMap;
}
/**
* Description:列取分享目录
*
* @param path
* @param groupId
* 组id
* @param userName
* 用户名
* @param sharetime
* 分享shijian
* @param recursive
* 是否递归列取子目录的内容
* @return
*/
public Map<String, Object> listShareDir(String path, String groupId,
String userName, String sharetime, String recursive) {
String resourceUrl = MessageFormat
.format("{0}{1}?op=LISTSHAREDIR&sign={2}&time={3}&groupid={4}&user={5}&sharetime={6}&recursive={7}",
gtDataUrl, path, defaultSign, defaultTime, groupId,
userName, sharetime, recursive);
Map<String, Object> responseMap = restGet(resourceUrl);
Map<String, Object> myResponseMap = new HashMap<String, Object>();
if (responseMap != null
&& 200 == (Integer) responseMap.get("HttpStatusCode")) {
List<ShareFile> shareFiles = mapToShareFilesToQueryList(responseMap);
myResponseMap.put("files", shareFiles);
myResponseMap.put("HttpStatusCode", 200);// 调用成功
return myResponseMap;
}
return responseMap;
}
}
/**
*
* Copyright zkyg
*/
package com.upyuns.platform.rs.gtdata;
/**
*
* Description:GtDataRest的Exception
*
* @author JhYao 2014年11月11日
*
* @version v1.0
*
*/
public class GtDataRestException extends RuntimeException {
private static final long serialVersionUID = 265637423335344668L;
public GtDataRestException() {
super();
}
public GtDataRestException(String message) {
super(message);
}
public GtDataRestException(Throwable cause) {
super(cause);
}
public GtDataRestException(String message, Throwable cause) {
super(message, cause);
}
}
\ No newline at end of file
package com.upyuns.platform.rs.gtdata;
import org.apache.commons.lang3.StringUtils;
import java.io.UnsupportedEncodingException;
/**
* 用于多gt-data路径转化的相关工具
* @author wugq
*
*/
public class GtPathUtil {
private final String[] paths;
private String displayPath;
/**
* 对外隐藏默认构造函数
*/
private GtPathUtil(){
paths = null;
}
public GtPathUtil(String path){
while(path.endsWith("/") && path.length()>1){
path = path.substring(0, path.length()-1);
}
paths = StringUtils.splitByWholeSeparator(path, "/");
}
public GtPathUtil(String path,String filename){
path = path +"/"+filename;
while(path.endsWith("/") && path.length()>1){
path = path.substring(0, path.length()-1);
}
paths = StringUtils.splitByWholeSeparator(path, "/");
}
public String getFileName(){
String name = paths[paths.length-1];
return name;
}
public String getPath() {
if(displayPath == null){
displayPath = "/" + StringUtils.join(paths, "/");
}
return displayPath;
}
public String getParentPath() {
String path = "";
if (paths.length <= 1)
path = "/";
else{
path = getPath();
path = path.substring(0, path.lastIndexOf("/"));
}
return path;
}
/**
* @param args
* @throws UnsupportedEncodingException
*/
public static void main(String[] args){
// TODO Auto-generated method stub
for(String str : StringUtils.splitByWholeSeparator("//sdasda///dsadas///aaaa", "/")){
if(str.isEmpty()){
System.out.println("error");
}
// System.out.println(str);
}
System.out.println(new GtPathUtil("//sdasda///dsadas//aaaa//dddd///").getFileName());
System.out.println(new GtPathUtil("//sdasda///dsadas//aaaa//dddd///").getParentPath());
System.out.println(new GtPathUtil("//sdasda///dsadas//aaaa//dddd///").getPath());
}
}
package com.upyuns.platform.rs.gtdata;
import cn.hutool.core.util.StrUtil;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class GtdataCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
Environment environment = conditionContext.getEnvironment();
String sign = environment.getProperty("gtdata.use");
if(StrUtil.isNotBlank(sign) && "true".equals(sign)){
return true;
}
return false;
}
}
\ No newline at end of file
/**
*
* Copyright zkyg
*/
package com.upyuns.platform.rs.gtdata;
import java.io.Serializable;
import java.util.List;
/**
* Description:个人中心我的空间,gtdata的文件属性
*
* @author ljw 2014-6-19
*
* @version v1.0
*
*/
public class GtdataFile implements Serializable {
private static final long serialVersionUID = -1068754518809085144L;
private String path;// 文件路径
private String size;// 文件大小,大小是-1就是文件夹
private String time;// 修改日期
private String filename;// 文件名字
private List<GtdataFile> child;
public List<GtdataFile> getChild() {
return child;
}
public void setChild(List<GtdataFile> child) {
this.child = child;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
}
package com.upyuns.platform.rs.gtdata;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpUtils {
private static JsonMapper jsonMapper = JsonMapper.buildNormalMapper();
public static Map<String, Object> doGet(String URLString)
throws IOException {
CloseableHttpResponse response = null;
HttpGet httpGet = new HttpGet(URLString);
Map<String, Object> ret = new HashMap<String, Object>();
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
ret.put("HttpStatusCode", response.getStatusLine().getStatusCode());
if (entity != null) {
ret.put("response", IOUtils.toString(entity.getContent()));
}
} finally {
IOUtils.closeQuietly((InputStream) response);
httpGet.abort();
}
return ret;
}
public static Map<String, Object> doPost(String URLString)
throws IOException {
CloseableHttpResponse response = null;
HttpPost httpPost = new HttpPost(URLString);
Map<String, Object> ret = new HashMap<String, Object>();
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
ret.put("HttpStatusCode", response.getStatusLine().getStatusCode());
if (entity != null) {
ret.put("response", IOUtils.toString(entity.getContent()));
}
} finally {
IOUtils.closeQuietly((InputStream) response);
httpPost.abort();
}
return ret;
}
/**
* Description:HTTP的PUT请求
*
* @author WuWenSheng 2016.06.02
* @param url
* @param params
* @return
* @throws IOException
*/
public static Map<String, Object> doPut(String url,
List<NameValuePair> params) throws IOException {
CloseableHttpResponse response = null;
HttpPut httpPut = new HttpPut(url);
httpPut.setEntity(new UrlEncodedFormEntity(params));
Map<String, Object> ret = new HashMap<String, Object>();
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
response = httpclient.execute(httpPut);
HttpEntity entity = response.getEntity();
ret.put("HttpStatusCode", response.getStatusLine().getStatusCode());
if (entity != null) {
ret.put("response", IOUtils.toString(entity.getContent()));
}
} finally {
IOUtils.closeQuietly((InputStream) response);
httpPut.abort();
}
return ret;
}
/**
* Description:HTTP的PUT请求(单属性,不传key)
*
* @author WuWenSheng 2016.06.02
* @param url
* @return
* @throws IOException
*/
public static Map<String, Object> doPut(String url, String param)
throws IOException {
CloseableHttpResponse response = null;
HttpPut httpPut = new HttpPut(url);
httpPut.setEntity(new StringEntity(param));
Map<String, Object> ret = new HashMap<String, Object>();
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
response = httpclient.execute(httpPut);
HttpEntity entity = response.getEntity();
ret.put("HttpStatusCode", response.getStatusLine().getStatusCode());
if (entity != null) {
ret.put("response", IOUtils.toString(entity.getContent()));
}
} finally {
IOUtils.closeQuietly((InputStream) response);
httpPut.abort();
}
return ret;
}
public static Map<String, Object> putFile(String URLString, File file)
throws IOException {
CloseableHttpResponse response = null;
Map<String, Object> ret = new HashMap<String, Object>();
InputStream instream = null;
HttpPut httpPut = new HttpPut(URLString);
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
FileEntity reqEntity = new FileEntity(file);
httpPut.setEntity(reqEntity);
response = httpclient.execute(httpPut);
HttpEntity entity = response.getEntity();
ret.put("HttpStatusCode", response.getStatusLine().getStatusCode());
if (entity != null) {
instream = entity.getContent();
ret.putAll(jsonMapper.fromJson(
IOUtils.toString(instream, "utf-8"), Map.class));
}
} finally {
IOUtils.closeQuietly(instream);
IOUtils.closeQuietly((InputStream) response);
httpPut.abort();
}
return ret;
}
public static Map<String, Object> GetFile(String url, OutputStream output)
throws IOException {
CloseableHttpResponse response = null;
InputStream input = null;
Map<String, Object> ret = new HashMap<String, Object>();
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
ret.put("HttpStatusCode", response.getStatusLine()
.getStatusCode());
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
input = entity.getContent();
IOUtils.copyLarge(input, output);
} else {
if (input != null)
ret.putAll(jsonMapper.fromJson(
IOUtils.toString(input, "utf-8"), Map.class));
}
}
} finally {
IOUtils.closeQuietly(input);
IOUtils.closeQuietly(output);
IOUtils.closeQuietly((InputStream) response);
}
return ret;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
package com.upyuns.platform.rs.gtdata;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
/**
*
* Description:简单封装Jackson,实现JSON String<->Java Object的Mapper(封装不同的输出风格, 使用不同的builder函数创建实例)
*
* @author JhYao 2014年10月20日
*
* @version v1.0
*
*/
public class JsonMapper {
private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);
private ObjectMapper mapper;
public JsonMapper() {
this(null);
}
public JsonMapper(Include include) {
mapper = new ObjectMapper();
// 设置输出时包含属性的风格
if (include != null) {
mapper.setSerializationInclusion(include);
}
// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
/**
* 创建输出全部属性到Json字符串的Mapper.
*/
public static JsonMapper buildNormalMapper() {
return new JsonMapper(Include.ALWAYS);
}
/**
* 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用.
*/
public static JsonMapper nonEmptyMapper() {
return new JsonMapper(Include.NON_EMPTY);
}
/**
* 创建只输出初始值被改变的属性到Json字符串的Mapper, 最节约的存储方式,建议在内部接口中使用。
*/
public static JsonMapper nonDefaultMapper() {
return new JsonMapper(Include.NON_DEFAULT);
}
/**
* Object可以是POJO,也可以是Collection或数组。
* 如果对象为Null, 返回"null".
* 如果集合为空集合, 返回"[]".
*/
public String toJson(Object object) {
try {
return mapper.writeValueAsString(object);
} catch (IOException e) {
logger.warn("write to json string error:" + object, e);
return null;
}
}
/**
* 反序列化POJO或简单Collection如List<String>.
*
* 如果JSON字符串为Null或"null"字符串, 返回Null.
* 如果JSON字符串为"[]", 返回空集合.
*
* 如需反序列化复杂Collection如List<MyBean>, 请使用fromJson(String, JavaType)
*
* @see #fromJson(String, JavaType)
*/
public <T> T fromJson(String jsonString, Class<T> clazz) {
if (StringUtils.isEmpty(jsonString)) {
return null;
}
try {
return mapper.readValue(jsonString, clazz);
} catch (IOException e) {
logger.warn("parse json string error:" + jsonString, e);
return null;
}
}
/**
* 反序列化复杂Collection如List<Bean>, 先使用createCollectionType()或contructMapType()构造类型, 然后调用本函数.
*
* @see
*/
public <T> T fromJson(String jsonString, JavaType javaType) {
if (StringUtils.isEmpty(jsonString)) {
return null;
}
try {
return (T) mapper.readValue(jsonString, javaType);
} catch (IOException e) {
logger.warn("parse json string error:" + jsonString, e);
return null;
}
}
/**
* 构造Collection类型.
*/
public JavaType contructCollectionType(Class<? extends Collection> collectionClass, Class<?> elementClass) {
return mapper.getTypeFactory().constructCollectionType(collectionClass, elementClass);
}
/**
* 构造Map类型.
*/
public JavaType contructMapType(Class<? extends Map> mapClass, Class<?> keyClass, Class<?> valueClass) {
return mapper.getTypeFactory().constructMapType(mapClass, keyClass, valueClass);
}
/**
* 当JSON里只含有Bean的部分屬性時,更新一個已存在Bean,只覆蓋該部分的屬性.
*/
public void update(String jsonString, Object object) {
try {
mapper.readerForUpdating(object).readValue(jsonString);
} catch (JsonProcessingException e) {
logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
} catch (IOException e) {
logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
}
}
/**
* 輸出JSONP格式數據.
*/
public String toJsonP(String functionName, Object object) {
return toJson(new JSONPObject(functionName, object));
}
/**
* 設定是否使用Enum的toString函數來讀寫Enum,
* 為False時時使用Enum的name()函數來讀寫Enum, 默認為False.
* 注意本函數一定要在Mapper創建後, 所有的讀寫動作之前調用.
*/
public void enableEnumUseToString() {
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
}
/**
* 支持使用Jaxb的Annotation,使得POJO上的annotation不用与Jackson耦合。
* 默认会先查找jaxb的annotation,如果找不到再找jackson的。
*/
public void enableJaxbAnnotation() {
JaxbAnnotationModule module = new JaxbAnnotationModule();
mapper.registerModule(module);
}
/**
* 取出Mapper做进一步的设置或使用其他序列化API.
*/
public ObjectMapper getMapper() {
return mapper;
}
}
package com.upyuns.platform.rs.gtdata;
import java.io.Serializable;
import java.util.List;
/**
* Description:个人云盘分享文件的属性
* @author zhengmaopan 2015-6-18
* @version v1.0
*/
public class ShareFile implements Serializable {
private static final long serialVersionUID = -1068754518809085144L;
private String id;
private String name; //分享or 组名
private String user; //用户名
private String sharetime; //分享时间
private String size; //文件大小
private String isdir; //是否路径
private String path; //文件路径
private List<ShareFile> child;
public List<ShareFile> getChild() {
return child;
}
public void setChild(List<ShareFile> child) {
this.child = child;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getSharetime() {
return sharetime;
}
public void setSharetime(String sharetime) {
this.sharetime = sharetime;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getIsdir() {
return isdir;
}
public void setIsdir(String isdir) {
this.isdir = isdir;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
package com.upyuns.platform.rs.datacenter.config;
import com.github.wxiaoqi.security.auth.client.interceptor.ServiceAuthRestInterceptor;
import com.github.wxiaoqi.security.auth.client.interceptor.UserAuthRestInterceptor;
import com.github.wxiaoqi.security.common.handler.GlobalExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.Collections;
/**
*
* @author ace
* @date 2017/9/8
*/
@Configuration("datacenterWebConfig")
@Primary
public class WebConfiguration implements WebMvcConfigurer {
@Bean
GlobalExceptionHandler getGlobalExceptionHandler() {
return new GlobalExceptionHandler();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getServiceAuthRestInterceptor()).
addPathPatterns(getIncludePathPatterns()).addPathPatterns("/api/user/validate");
registry.addInterceptor(getUserAuthRestInterceptor()).
addPathPatterns(getIncludePathPatterns());
}
@Bean
ServiceAuthRestInterceptor getServiceAuthRestInterceptor() {
return new ServiceAuthRestInterceptor();
}
@Bean
UserAuthRestInterceptor getUserAuthRestInterceptor() {
return new UserAuthRestInterceptor();
}
/**
* 需要用户和服务认证判断的路径
* @return
*/
private ArrayList<String> getIncludePathPatterns() {
ArrayList<String> list = new ArrayList<>();
String[] urls = {
};
Collections.addAll(list, urls);
return list;
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
......@@ -86,10 +86,6 @@ public class RscpImageDataTotalController extends BaseController<RscpImageDataTo
String startDateTime;
String endDateTime;
String geom;
Double leftLon;
Double rightLon;
Double topLat;
Double bottomLat;
String areaNo;
String provinceNo;
List<satelliteDTO> saSensor;
......
package com.upyuns.platform.rs.website.config;
import com.github.wxiaoqi.security.auth.client.interceptor.ServiceAuthRestInterceptor;
import com.github.wxiaoqi.security.auth.client.interceptor.UserAuthRestInterceptor;
import com.github.wxiaoqi.security.common.handler.GlobalExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.Collections;
/**
*
* @author ace
* @date 2017/9/8
*/
@Configuration("websiteWebConfig")
@Primary
public class WebConfiguration implements WebMvcConfigurer {
@Bean
GlobalExceptionHandler getGlobalExceptionHandler() {
return new GlobalExceptionHandler();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getServiceAuthRestInterceptor()).
addPathPatterns(getIncludePathPatterns()).addPathPatterns("/api/user/validate");
registry.addInterceptor(getUserAuthRestInterceptor()).
addPathPatterns(getIncludePathPatterns());
}
@Bean
ServiceAuthRestInterceptor getServiceAuthRestInterceptor() {
return new ServiceAuthRestInterceptor();
}
@Bean
UserAuthRestInterceptor getUserAuthRestInterceptor() {
return new UserAuthRestInterceptor();
}
/**
* 需要用户和服务认证判断的路径
* @return
*/
private ArrayList<String> getIncludePathPatterns() {
ArrayList<String> list = new ArrayList<>();
String[] urls = {
};
Collections.addAll(list, urls);
return list;
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
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