提交 c7d5f895 authored 作者: luojie's avatar luojie

新增上传头像,修改汇率定时查询.导入OSSUtil及其jar包。

上级 e889e19d
......@@ -34,11 +34,71 @@
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>6.5.0</version>
<exclusions>
<exclusion>
<artifactId>google-http-client</artifactId>
<groupId>com.google.http-client</groupId>
</exclusion>
<exclusion>
<artifactId>google-auth-library-credentials</artifactId>
<groupId>com.google.auth</groupId>
</exclusion>
<exclusion>
<artifactId>protobuf-java</artifactId>
<groupId>com.google.protobuf</groupId>
</exclusion>
<exclusion>
<artifactId>opencensus-api</artifactId>
<groupId>io.opencensus</groupId>
</exclusion>
<exclusion>
<artifactId>google-auth-library-oauth2-http</artifactId>
<groupId>com.google.auth</groupId>
</exclusion>
<exclusion>
<artifactId>proto-google-common-protos</artifactId>
<groupId>com.google.api.grpc</groupId>
</exclusion>
<exclusion>
<artifactId>google-http-client-jackson2</artifactId>
<groupId>com.google.http-client</groupId>
</exclusion>
<exclusion>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
</exclusion>
<exclusion>
<artifactId>api-common</artifactId>
<groupId>com.google.api</groupId>
</exclusion>
<exclusion>
<artifactId>google-api-client</artifactId>
<groupId>com.google.api-client</groupId>
</exclusion>
<exclusion>
<artifactId>jsr305</artifactId>
<groupId>com.google.code.findbugs</groupId>
</exclusion>
<exclusion>
<artifactId>grpc-core</artifactId>
<groupId>io.grpc</groupId>
</exclusion>
<exclusion>
<artifactId>opencensus-contrib-http-util</artifactId>
<groupId>io.opencensus</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.yunpian.sdk</groupId>
<artifactId>yunpian-java-sdk</artifactId>
<version>1.2.7</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-elasticsearch -->
......@@ -204,6 +264,12 @@
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
<exclusions>
<exclusion>
<artifactId>commons-lang</artifactId>
<groupId>commons-lang</groupId>
</exclusion>
</exclusions>
</dependency>
<!--net.sf.json-lib-->
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
......@@ -284,6 +350,12 @@
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.10</version>
<exclusions>
<exclusion>
<artifactId>mybatis-spring-boot-starter</artifactId>
<groupId>org.mybatis.spring.boot</groupId>
</exclusion>
</exclusions>
<!-- <exclusions>-->
<!-- <exclusion>-->
<!-- <artifactid>mybatis-spring-boot-starter</artifactid>-->
......@@ -353,6 +425,10 @@
<artifactId>jsoup</artifactId>
<groupId>org.jsoup</groupId>
</exclusion>
<exclusion>
<artifactId>commons-collections</artifactId>
<groupId>commons-collections</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
......@@ -383,20 +459,27 @@
<artifactId>rest-api-sdk</artifactId>
<version>1.4.2</version>
</dependency>
<!-- OSS-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.8.0</version>
</dependency>
<!-- <dependency>
<groupId>com.github.theresasogunle</groupId>
<artifactId>Rave</artifactId>
<version>1.0.1</version>
</dependency>
</dependency>-->
<!--<dependency>
<dependency>
<groupId>com.github.theresasogunle</groupId>
<artifactId>Rave</artifactId>
<version>1.0.1</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/Rave-1.0.1.jar
</systemPath>
</dependency>-->
</dependency>
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
......@@ -404,6 +487,29 @@
<version>4.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.auth/google-auth-library-oauth2-http -->
<dependency>
<groupId>com.google.auth</groupId>
<artifactId>google-auth-library-oauth2-http</artifactId>
<version>0.17.0</version>
<exclusions>
<exclusion>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
</exclusion>
<exclusion>
<artifactId>grpc-context</artifactId>
<groupId>io.grpc</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
<build>
......
package com.diaoyun.zion.chinafrica.controller;
import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.diaoyun.zion.chinafrica.service.TbCfUserInfoService;
import com.diaoyun.zion.chinafrica.vo.TbCfUserInfoVo;
import com.diaoyun.zion.master.base.BaseController;
import com.diaoyun.zion.master.base.Result;
import com.diaoyun.zion.master.enums.ResultCodeEnum;
import com.diaoyun.zion.master.util.IdUtil;
import com.diaoyun.zion.master.util.OssUtil;
import com.diaoyun.zion.master.validator.Validator;
import com.diaoyun.zion.master.validator.annotation.ValidateParam;
import freemarker.template.TemplateException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.mail.EmailException;
......@@ -18,10 +24,16 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* 用户相关api
......@@ -101,4 +113,20 @@ public class TbCfUserInfoController extends BaseController {
return tbCfUserInfoService.getUserInfo();
}
/**
* 上传头像
*/
@ApiOperation(value = "上传图片", notes = "上传图片")
@ApiImplicitParam(paramType = "query", name = "file", value = "图片", required = true, dataType = "MultipartFile")
@PostMapping("/imageUpload")
public String imageUpload(@RequestParam("file") MultipartFile file) throws Exception {
if (file.isEmpty()) {
throw new Exception("上传图片不能为空");
}
//上传头像
String secondaryFolderName="userHeadImage";
String url = OssUtil.upload(file,secondaryFolderName);
return url;
}
}
package com.diaoyun.zion.chinafrica.dao;
import com.diaoyun.zion.chinafrica.entity.TbCfExchangeEntity;
import com.diaoyun.zion.master.dao.BaseDao;
import java.math.BigDecimal;
/**
* 汇率管理Dao
*
* @author lipengjun
* @date 2019-12-10 12:21:26
*/
public interface TbCfExchangeDao extends BaseDao<TbCfExchangeEntity> {
void updateByType(String type, BigDecimal rate);
}
package com.diaoyun.zion.chinafrica.service;
import com.diaoyun.zion.chinafrica.entity.TbCfExchangeEntity;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
/**
* 汇率管理Service接口
*
* @author lipengjun
* @date 2019-12-10 11:15:53
*/
public interface TbCfExchangeService {
/**
* 根据主键查询实体
*
* @param id 主键
* @return 实体
*/
TbCfExchangeEntity queryObject(String id);
/**
* 分页查询
*
* @param map 参数
* @return list
*/
List<TbCfExchangeEntity> queryList(Map<String, Object> map);
/**
* 分页统计总数
*
* @param map 参数
* @return 总数
*/
int queryTotal(Map<String, Object> map);
/**
* 保存实体
*
* @param tbCfExchange 实体
* @return 保存条数
*/
int save(TbCfExchangeEntity tbCfExchange);
/**
* 根据主键更新实体
*
* @param tbCfExchange 实体
* @return 更新条数
*/
int update(TbCfExchangeEntity tbCfExchange);
/**
* 根据主键删除
*
* @param id
* @return 删除条数
*/
int delete(String id);
/**
* 根据主键批量删除
*
* @param ids
* @return 删除条数
*/
int deleteBatch(String[] ids);
void updateByType(String type, BigDecimal rate);
}
......@@ -7,6 +7,7 @@ import freemarker.template.TemplateException;
import io.swagger.annotations.ApiParam;
import org.apache.commons.mail.EmailException;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
......@@ -190,4 +191,6 @@ public interface TbCfUserInfoService {
int updateIsSend(String email);
Result checkByPhone(String phone);
String updateHead(MultipartFile file) throws Exception;
}
package com.diaoyun.zion.chinafrica.service.impl;
import com.diaoyun.zion.chinafrica.dao.TbCfExchangeDao;
import com.diaoyun.zion.chinafrica.entity.TbCfExchangeEntity;
import com.diaoyun.zion.chinafrica.service.TbCfExchangeService;
import com.diaoyun.zion.master.util.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 汇率管理Service实现类
*
* @author lipengjun
* @date 2019-12-10 11:15:53
*/
@Service("tbCfExchangeService")
public class TbCfExchangeServiceImpl implements TbCfExchangeService {
@Autowired
private TbCfExchangeDao tbCfExchangeDao;
@Override
public TbCfExchangeEntity queryObject(String id) {
return tbCfExchangeDao.queryObject(id);
}
@Override
public List<TbCfExchangeEntity> queryList(Map<String, Object> map) {
return tbCfExchangeDao.queryList(map);
}
@Override
public int queryTotal(Map<String, Object> map) {
return tbCfExchangeDao.queryTotal(map);
}
@Override
public int save(TbCfExchangeEntity tbCfExchange) {
tbCfExchange.setId(IdUtil.createIdbyUUID());
tbCfExchange.setDelFlag(0);
tbCfExchange.setCreateTime(new Date());
tbCfExchange.setUpdateTime(new Date());
return tbCfExchangeDao.save(tbCfExchange);
}
@Override
public int update(TbCfExchangeEntity tbCfExchange) {
tbCfExchange.setUpdateTime(new Date());
return tbCfExchangeDao.update(tbCfExchange);
}
@Override
public int delete(String id) {
return tbCfExchangeDao.delete(id);
}
@Override
public int deleteBatch(String[] ids) {
return tbCfExchangeDao.deleteBatch(ids);
}
@Override
public void updateByType(String type, BigDecimal rate) {
tbCfExchangeDao.updateByType(type,rate);
}
}
......@@ -24,10 +24,7 @@ import com.diaoyun.zion.master.enums.SexEnum;
import com.diaoyun.zion.master.enums.UserTypeEnum;
import com.diaoyun.zion.master.exception.ApplicationException;
import com.diaoyun.zion.master.security.JwtTokenProvider;
import com.diaoyun.zion.master.util.EmailHelper;
import com.diaoyun.zion.master.util.IdUtil;
import com.diaoyun.zion.master.util.RandomCodeHelper;
import com.diaoyun.zion.master.util.SMSUtil;
import com.diaoyun.zion.master.util.*;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.mail.EmailException;
......@@ -38,6 +35,7 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
......@@ -579,6 +577,17 @@ public class TbCfUserInfoServiceImpl implements TbCfUserInfoService {
return tbCfUserInfoDao.updateIsSend(email);
}
@Override
public String updateHead(MultipartFile file) throws Exception {
String token = jwtTokenProvider.resolveToken(request);
TbCfUserInfoVo loginUser = tokenManager.validate(token);
if (file == null || file.getSize() <= 0) {
throw new Exception("头像不能为空");
}
String imgUrl = OssUtil.upload(file);
return imgUrl;
}
@Override
public Result checkByPhone(String phone) {
Result result = new Result();
......
package com.diaoyun.zion.master.quartz;
import com.diaoyun.zion.chinafrica.service.TbCfExchangeService;
import com.diaoyun.zion.chinafrica.service.TbCfExpCatRelService;
import com.diaoyun.zion.chinafrica.service.TbCfUserInfoService;
import com.diaoyun.zion.master.util.HttpClientUtil;
import freemarker.template.TemplateException;
import org.apache.commons.mail.EmailException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.util.List;
......@@ -15,6 +22,10 @@ import java.util.List;
public class QuartzMethod {
@Autowired
private TbCfUserInfoService tbCfUserInfoService;
@Autowired
private TbCfExchangeService tbCfExchangeService;
//@Scheduled(cron = "0 0/1 * * * ? ")
public void sendEmail() throws EmailException, TemplateException, IOException {
System.out.println("////////////////////////////////////////////////////");
......@@ -27,4 +38,38 @@ public class QuartzMethod {
}
}
}
/**
* 美元-克瓦查
* @throws IOException
* @throws URISyntaxException
*/
@Scheduled(cron = "0 0/2 * * * ? ")
public void getRent() throws IOException, URISyntaxException {
String content = HttpClientUtil.getContentByUrl("https://cn.valutafx.com/USD-ZMW.htm?amount=1", "rent");
// 解析为 Document 对象
Document document = Jsoup.parse(content);
String rent = document.select("div[class=rate-value]").text();
BigDecimal rate=new BigDecimal(rent);
System.err.println(rate);
String type="USD-ZMW";
tbCfExchangeService.updateByType(type,rate);
}
/**
* 美元-人民币
* @throws IOException
* @throws URISyntaxException
*/
@Scheduled(cron = "0 0/2 * * * ? ")
public void getRate() throws IOException, URISyntaxException {
String content = HttpClientUtil.getContentByUrl("https://cn.valutafx.com/USD-CNY.htm?amount=1", "rent");
// 解析为 Document 对象
Document document = Jsoup.parse(content);
String rent = document.select("div[class=rate-value]").text();
BigDecimal rate=new BigDecimal(rent);
System.err.println(rate);
String type="USD-CNY";
tbCfExchangeService.updateByType(type,rate);
}
}
package com.diaoyun.zion.master.util;
import java.util.HashMap;
import java.util.Map;
public final class AppInfo {
public static final int SUCCESS = 0;
public static final int MAX_SIZE = 1;
public static final int PERMISSION_DENIED = 2;
public static final int FAILED_CREATE_FILE = 3;
public static final int IO_ERROR = 4;
public static final int NOT_MULTIPART_CONTENT = 5;
public static final int PARSE_REQUEST_ERROR = 6;
public static final int NOTFOUND_UPLOAD_DATA = 7;
public static final int NOT_ALLOW_FILE_TYPE = 8;
public static final int INVALID_ACTION = 101;
public static final int CONFIG_ERROR = 102;
public static final int PREVENT_HOST = 201;
public static final int CONNECTION_ERROR = 202;
public static final int REMOTE_FAIL = 203;
public static final int NOT_DIRECTORY = 301;
public static final int NOT_EXIST = 302;
public static final int ILLEGAL = 401;
public static Map<Integer, String> info = new HashMap<Integer, String>();
static {
info.put(AppInfo.SUCCESS, "SUCCESS");
// 无效的Action
info.put(AppInfo.INVALID_ACTION, "\u65E0\u6548\u7684Action");
// 配置文件初始化失败
info.put(AppInfo.CONFIG_ERROR, "\u914D\u7F6E\u6587\u4EF6\u521D\u59CB\u5316\u5931\u8D25");
// 抓取远程图片失败
info.put(AppInfo.REMOTE_FAIL, "\u6293\u53D6\u8FDC\u7A0B\u56FE\u7247\u5931\u8D25");
// 被阻止的远程主机
info.put(AppInfo.PREVENT_HOST, "\u88AB\u963B\u6B62\u7684\u8FDC\u7A0B\u4E3B\u673A");
// 远程连接出错
info.put(AppInfo.CONNECTION_ERROR, "\u8FDC\u7A0B\u8FDE\u63A5\u51FA\u9519");
// "文件大小超出限制"
info.put(AppInfo.MAX_SIZE, "\u6587\u4ef6\u5927\u5c0f\u8d85\u51fa\u9650\u5236");
// 权限不足, 多指写权限
info.put(AppInfo.PERMISSION_DENIED, "\u6743\u9650\u4E0D\u8DB3");
// 创建文件失败
info.put(AppInfo.FAILED_CREATE_FILE, "\u521B\u5EFA\u6587\u4EF6\u5931\u8D25");
// IO错误
info.put(AppInfo.IO_ERROR, "IO\u9519\u8BEF");
// 上传表单不是multipart/form-data类型
info.put(AppInfo.NOT_MULTIPART_CONTENT,
"\u4E0A\u4F20\u8868\u5355\u4E0D\u662Fmultipart/form-data\u7C7B\u578B");
// 解析上传表单错误
info.put(AppInfo.PARSE_REQUEST_ERROR, "\u89E3\u6790\u4E0A\u4F20\u8868\u5355\u9519\u8BEF");
// 未找到上传数据
info.put(AppInfo.NOTFOUND_UPLOAD_DATA, "\u672A\u627E\u5230\u4E0A\u4F20\u6570\u636E");
// 不允许的文件类型
info.put(AppInfo.NOT_ALLOW_FILE_TYPE, "\u4E0D\u5141\u8BB8\u7684\u6587\u4EF6\u7C7B\u578B");
// 指定路径不是目录
info.put(AppInfo.NOT_DIRECTORY, "\u6307\u5B9A\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55");
// 指定路径并不存在
info.put(AppInfo.NOT_EXIST, "\u6307\u5B9A\u8DEF\u5F84\u5E76\u4E0D\u5B58\u5728");
// callback参数名不合法
info.put(AppInfo.ILLEGAL, "Callback\u53C2\u6570\u540D\u4E0D\u5408\u6CD5");
}
public static String getStateInfo ( int key ) {
return AppInfo.info.get( key );
}
}
package com.diaoyun.zion.master.util;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class BaseState implements State {
private boolean state = false;
private String info = null;
private Map<String, String> infoMap = new HashMap<String, String>();
public BaseState() {
this.state = true;
}
public BaseState(boolean state ) {
this.setState( state );
}
public BaseState(boolean state, String info ) {
this.setState( state );
this.info = info;
}
public BaseState(boolean state, int infoCode ) {
this.setState( state );
this.info = AppInfo.getStateInfo( infoCode );
}
public boolean isSuccess () {
return this.state;
}
public void setState ( boolean state ) {
this.state = state;
}
public void setInfo ( String info ) {
this.info = info;
}
public void setInfo ( int infoCode ) {
this.info = AppInfo.getStateInfo( infoCode );
}
@Override
public String toJSONString() {
return this.toString();
}
public String toString () {
String key = null;
String stateVal = this.isSuccess() ? AppInfo.getStateInfo( AppInfo.SUCCESS ) : this.info;
StringBuilder builder = new StringBuilder();
builder.append( "{\"state\": \"" + stateVal + "\"" );
Iterator<String> iterator = this.infoMap.keySet().iterator();
while ( iterator.hasNext() ) {
key = iterator.next();
builder.append( ",\"" + key + "\": \"" + this.infoMap.get(key) + "\"" );
}
builder.append( "}" );
return Encoder.toUnicode( builder.toString() );
}
@Override
public void putInfo(String name, String val) {
this.infoMap.put(name, val);
}
@Override
public void putInfo(String name, long val) {
this.putInfo(name, val+"");
}
}
package com.diaoyun.zion.master.util;
public class Encoder {
public static String toUnicode ( String input ) {
StringBuilder builder = new StringBuilder();
char[] chars = input.toCharArray();
for ( char ch : chars ) {
if ( ch < 256 ) {
builder.append( ch );
} else {
builder.append( "\\u" + Integer.toHexString( ch& 0xffff ) );
}
}
return builder.toString();
}
}
\ No newline at end of file
package com.diaoyun.zion.master.util;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URL;
import java.util.Date;
public class OssUtil {
////////// 阿里云要求jdom使用1.1版本!!!!!!!!!!!!!
//阿里云API的内或外网域名
private static final String ENDPOINT="oss-cn-shenzhen.aliyuncs.com";
//阿里云API的密钥Access Key ID
private static final String ACCESS_KEY_ID="5d6h34keSd9K3l2x";
//阿里云API的密钥Access Key Secret
private static final String ACCESS_KEY_SECRET="l2dJ4LpY6D6qV3jj3iQif7EPByoVQE";
//阿里云API的bucket名称
private static final String BACKET_NAME="diaosaas-prod";
//阿里云API的文件夹名称
private static final String FOLDER="africa-shop/";
// // 阿里云API的内或外网域名
// private static final String ENDPOINT = "oss-cn-shenzhen.aliyuncs.com";
// // 阿里云API的密钥Access Key ID
// private static final String ACCESS_KEY_ID = "5d6h34keSd9K3l2x";
// // 阿里云API的密钥Access Key Secret
// private static final String ACCESS_KEY_SECRET = "l2dJ4LpY6D6qV3jj3iQif7EPByoVQE";
// // 阿里云API的bucket名称
// private static final String BACKET_NAME = "diaosaas-prod";
// // 阿里云API的文件夹名称
// private static final String FOLDER = "wosenad/";
/**
* 获取阿里云OSS客户端对象
*
* @return
*/
public static OSSClient getOSSClient() {
return new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
}
/**
* 创建存储空间
*
* @param ossClient
* @param bucketName
* @return
*/
public static String createBucketName(OSSClient ossClient, String bucketName) {
// 存储空间
final String bucketNames = bucketName;
if (!ossClient.doesBucketExist(bucketName)) {
// 创建存储空间
Bucket bucket = ossClient.createBucket(bucketName);
return bucket.getName();
}
return bucketNames;
}
/**
* 删除存储空间
*
* @param ossClient
* @param bucketName
*/
public static void deleteBucket(OSSClient ossClient, String bucketName) {
ossClient.deleteBucket(bucketName);
}
/**
* 创建模拟文件夹
*
* @param ossClient
* oss连接
* @param bucketName
* 存储空间
* @param folder
* 模拟文件夹名如"wenjianjia/"
* @return
*/
public static String createFolder(OSSClient ossClient, String bucketName, String folder) {
// 文件夹名
final String keySuffixWithSlash = folder;
// 判断文件夹是否存在,不存在则创建
if (!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)) {
// 创建文件夹
ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
;
// 得到文件夹名
OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);
String fileDir = object.getKey();
return fileDir;
}
return keySuffixWithSlash;
}
/**
* 根据key和folder删除OSS服务器上的文件
*
* @param bucketName
* bucketName存储空间
* @param folder
* folder模拟文件夹名 如"qj_nanjing/"
* @param key
* Bucket下的文件的路径名+文件名 如:"upload/cake.jpg"
*/
public static String deleteFile(String bucketName, String folder, String key) {
OSSClient ossClient = getOSSClient();
try {
ossClient.deleteObject(bucketName, folder + key);
return "success";
} catch (Exception e) {
e.printStackTrace();
return "error";
} finally {
ossClient.shutdown();
}
}
/**
* 根据key删除OSS服务器上的文件
*
* @param bucketName
* bucketName存储空间
* @param key
* Bucket下的文件的路径名+文件名 如:"upload/cake.jpg"
*/
public static String deleteFile(String bucketName, String key) {
OSSClient ossClient = getOSSClient();
try {
ossClient.deleteObject(bucketName, key);
return "success";
} catch (Exception e) {
e.printStackTrace();
return "error";
} finally {
ossClient.shutdown();
}
}
/**
* 根据key删除OSS服务器上的文件
*
* @param key
* Bucket下的文件的路径名+文件名 如:"upload/cake.jpg" "http://" + BACKET_NAME +
* "." + ENDPOINT + "/" + FOLDER + secondaryFolderName + "/" +
* fileNameNew
*/
public static boolean deleteFile(String key) {
OSSClient ossClient = getOSSClient();
try {
// 将图片路径前缀去除
String pathPrefix = "https://" + BACKET_NAME + "." + ENDPOINT + "/";
String filePath = key.startsWith(pathPrefix) ? key.substring(pathPrefix.length(), key.length()) : key;
ossClient.deleteObject(BACKET_NAME, filePath);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
ossClient.shutdown();
}
}
/**
* 上传图片至OSS
*
* @param file
* @param secondaryFolderName
* 二级文件夹目录
* @return
*/
public static String uploadObject2OSS(File file, String secondaryFolderName) {
OSSClient ossClient = getOSSClient();
try {
// 以输入流的形式上传文件
InputStream is = new FileInputStream(file);
String path = file.getName();
String fileName = path.substring(path.lastIndexOf("//") + 1);
String type = path.substring(path.lastIndexOf(".") + 1);
int random = (int) (Math.random() * 900) + 10000;
// 文件名
String fileNameNew = fileName.replace(fileName,
String.valueOf(System.currentTimeMillis()) + String.valueOf(random) + "." + type);
// 文件大小
Long fileSize = file.length();
// 创建上传Object的Metadata
ObjectMetadata metadata = new ObjectMetadata();
// 上传的文件的长度
metadata.setContentLength(is.available());
// 指定该Object被下载时的网页的缓存行为
metadata.setCacheControl("no-cache");
// 指定该Object下设置Header
metadata.setHeader("Pragma", "no-cache");
// 指定该Object被下载时的内容编码格式
metadata.setContentEncoding("utf-8");
// 文件的MIME,定义文件的类型及网页编码,决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成,
// 如果没有扩展名则填默认值application/octet-stream
metadata.setContentType(getContentType(fileNameNew));
// 指定该Object被下载时的名称(指示MINME用户代理如何显示附加的文件,打开或下载,及文件名称)
metadata.setContentDisposition("filename/filesize=" + fileNameNew + "/" + fileSize + "Byte.");
//System.out.println(FOLDER + fileNameNew);
// 上传文件 (上传文件流的形式)
PutObjectResult putResult = ossClient.putObject(BACKET_NAME,
FOLDER + secondaryFolderName + "/" + fileNameNew, is, metadata);
// 解析结果
URL url = getUrl(ossClient, putResult.getETag());
return "https://" + BACKET_NAME + "." + ENDPOINT + "/" + FOLDER + secondaryFolderName + "/" + fileNameNew;
} catch (Exception e) {
e.printStackTrace();
return "error";
} finally {
ossClient.shutdown();
}
// return url;
}
/**
* 通过文件名判断并获取OSS服务文件上传时文件的contentType
*
* @param fileName
* @return
*/
public static String getContentType(String fileName) {
// 文件的后缀名
String fileExtension = fileName.substring(fileName.lastIndexOf("."));
if (".bmp".equalsIgnoreCase(fileExtension)) {
return "image/bmp";
}
if (".gif".equalsIgnoreCase(fileExtension)) {
return "image/gif";
}
if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)
|| ".png".equalsIgnoreCase(fileExtension)) {
return "image/jpeg";
}
if (".html".equalsIgnoreCase(fileExtension)) {
return "text/html";
}
if (".txt".equalsIgnoreCase(fileExtension)) {
return "text/plain";
}
if (".vsd".equalsIgnoreCase(fileExtension)) {
return "application/vnd.visio";
}
if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
return "application/vnd.ms-powerpoint";
}
if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
return "application/msword";
}
if (".xml".equalsIgnoreCase(fileExtension)) {
return "text/xml";
}
// 默认返回类型
return "image/jpeg";
}
/**
*
* @param ossClient
* @param key
* @return
*/
public static URL getUrl(OSSClient ossClient, String key) {
// 设置URL过期时间为10年
Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
// 生成URL
URL url = ossClient.generatePresignedUrl(BACKET_NAME, key, expiration);
return url;
}
/**
* MultipartFile 形式上传文件
* @param file
* @return
* @throws Exception
*/
public static String upload(MultipartFile file) throws Exception {
String fileName = file.getOriginalFilename();
String prefix = fileName.substring(fileName.lastIndexOf("."));
final File realfile = File.createTempFile(IdUtil.createIdbyUUID(), prefix);
file.transferTo(realfile);
String url = OssUtil.uploadObject2OSS(realfile, "");
//System.out.println(url);
return url;
}
/**
* MultipartFile 形式上传文件
* @param file
* @return
* @throws Exception
*/
public static String upload(MultipartFile file, String secondaryFolderName) throws Exception {
String fileName = file.getOriginalFilename();
String prefix = fileName.substring(fileName.lastIndexOf("."));
final File realfile = File.createTempFile(IdUtil.createIdbyUUID(), prefix);
file.transferTo(realfile);
String url = OssUtil.uploadObject2OSS(realfile, secondaryFolderName);
//System.out.println(url);
return url;
}
/**
* MultipartFile 形式上传文件
* @param file
* @return
* @throws Exception
*/
public static String upload(MultipartFile file, String fileName, String secondaryFolderName) throws Exception {
String prefix = fileName.substring( fileName.lastIndexOf( "." ) ).toLowerCase();
final File realfile = File.createTempFile(fileName, prefix);
file.transferTo(realfile);
String url = OssUtil.uploadObject2OSS(realfile, secondaryFolderName);
//System.out.println(url);
return url;
}
/**
* MultipartFile 形式上传文件
* @param realfile
* @return
* @throws Exception
*/
public static String upload(File realfile,String secondaryFolderName) {
String url = OssUtil.uploadObject2OSS(realfile, secondaryFolderName);
return url;
}
/**
* 以byte数组上传到oss
* @param fbytes byte数组
* @param fileName 文件名称
* @param secondaryFolderName 二级文件夹目录
* @return
* @throws Exception
*/
public static String upload(byte[] fbytes,String fileName,String secondaryFolderName) throws Exception {
OSSClient ossClient = getOSSClient();
// String fileNameNew = "1.jpg";
// 上传Byte数组。
PutObjectResult putResult = ossClient.putObject(BACKET_NAME, FOLDER + secondaryFolderName + "/" + fileName, new ByteArrayInputStream(fbytes));
// 解析结果
URL url = getUrl(ossClient, putResult.getETag());
// System.out.println(url);
// 关闭OSSClient。
ossClient.shutdown();
return "https://" + BACKET_NAME + "." + ENDPOINT + "/" + FOLDER + secondaryFolderName + "/" + fileName;
}
/**
* 将文件转换成byte数组
* @param tradeFile
* @return
*/
public static byte[] File2byte(File tradeFile){
byte[] buffer = null;
try
{
FileInputStream fis = new FileInputStream(tradeFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1)
{
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return buffer;
}
public static void main(String [] args) throws Exception {
boolean flag = deleteFile("http://guangzhou-douli.oss-cn-shenzhen.aliyuncs.com/shouli/qcrod/2.jpg");
//System.out.println(flag);
File file = new File("C:\\Users\\yangshanlin\\Desktop\\bg-sfxt.jpg");
byte[] b = File2byte(file);
//System.out.println(b);
String s = upload(b,"3.jpg","qcrod");
//System.out.println(s);
}
public static State uploadToAliOss(byte[] data, String fileName, String secondaryFolderName) throws Exception {
String path=upload(data,fileName,secondaryFolderName);
State state = new BaseState(true, path);
state.putInfo("size", data.length);
state.putInfo("title",fileName);
state.putInfo("url",path);
return state;
}
public static State uploadFileToAliOss(File realfile, String secondaryFolderName) {
String url = OssUtil.uploadObject2OSS(realfile, secondaryFolderName);
State state = new BaseState(true, url);
state.putInfo("title",realfile.getName());
state.putInfo("url",url);
return state;
}
}
package com.diaoyun.zion.master.util;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
import java.net.URISyntaxException;
public class RentUtil {
public static String getRent() throws IOException, URISyntaxException {
String content = HttpClientUtil.getContentByUrl("https://cn.valutafx.com/USD-ZMW.htm?amount=1", "rent");
// 解析为 Document 对象
Document document = Jsoup.parse(content);
String rent = document.select("div[class=rate-value]").text();
System.err.println(rent);
return rent;
}
}
package com.diaoyun.zion.master.util;
/**
* 处理状态接口
* @author hancong03@baidu.com
*
*/
public interface State {
public boolean isSuccess();
public void putInfo(String name, String val);
public void putInfo(String name, long val);
public String toJSONString();
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.diaoyun.zion.chinafrica.dao.TbCfExchangeDao">
<resultMap type="com.diaoyun.zion.chinafrica.entity.TbCfExchangeEntity" id="tbCfExchangeMap">
<result property="id" column="id"/>
<result property="type" column="type"/>
<result property="currency" column="currency"/>
<result property="exchangeCurrency" column="exchange_currency"/>
<result property="exchangeRate" column="exchange_rate"/>
<result property="delFlag" column="del_flag"/>
<result property="createTime" column="create_time"/>
<result property="updateTime" column="update_time"/>
</resultMap>
<select id="queryObject" resultType="com.diaoyun.zion.chinafrica.entity.TbCfExchangeEntity">
select
`id`,
`type`,
`currency`,
`exchange_currency`,
`exchange_rate`,
`del_flag`,
`create_time`,
`update_time`
from tb_cf_exchange
where id = #{id}
</select>
<select id="queryList" resultType="com.diaoyun.zion.chinafrica.entity.TbCfExchangeEntity">
select
`id`,
`type`,
`currency`,
`exchange_currency`,
`exchange_rate`,
`del_flag`,
`create_time`,
`update_time`
from tb_cf_exchange
WHERE 1=1
<if test="name != null and name.trim() != ''">
AND name LIKE concat('%',#{name},'%')
</if>
<choose>
<when test="sidx != null and sidx.trim() != ''">
order by ${sidx} ${order}
</when>
<otherwise>
order by id desc
</otherwise>
</choose>
<if test="offset != null and limit != null">
limit #{offset}, #{limit}
</if>
</select>
<select id="queryTotal" resultType="int">
select count(*) from tb_cf_exchange
WHERE 1=1
<if test="name != null and name.trim() != ''">
AND name LIKE concat('%',#{name},'%')
</if>
</select>
<insert id="save" parameterType="com.diaoyun.zion.chinafrica.entity.TbCfExchangeEntity">
insert into tb_cf_exchange(
`id`,
`type`,
`currency`,
`exchange_currency`,
`exchange_rate`,
`del_flag`,
`create_time`,
`update_time`)
values(
#{id},
#{type},
#{currency},
#{exchangeCurrency},
#{exchangeRate},
#{delFlag},
#{createTime},
#{updateTime})
</insert>
<update id="update" parameterType="com.diaoyun.zion.chinafrica.entity.TbCfExchangeEntity">
update tb_cf_exchange
<set>
<if test="type != null">`type` = #{type},</if>
<if test="currency != null">`currency` = #{currency},</if>
<if test="exchangeCurrency != null">`exchange_currency` = #{exchangeCurrency},</if>
<if test="exchangeRate != null">`exchange_rate` = #{exchangeRate},</if>
<if test="delFlag != null">`del_flag` = #{delFlag},</if>
<if test="createTime != null">`create_time` = #{createTime},</if>
<if test="updateTime != null">`update_time` = #{updateTime}</if>
</set>
where id = #{id}
</update>
<delete id="delete">
delete from tb_cf_exchange where id = #{value}
</delete>
<delete id="deleteBatch">
delete from tb_cf_exchange where id in
<foreach item="id" collection="array" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
<update id="updateByType">
update tb_cf_exchange set exchange_rate = #{rate} where type=#{type};
</update>
</mapper>
\ No newline at end of file
......@@ -69,8 +69,6 @@ public class PayTest {
list.add(product_type);
}
}
System.out.println(list);
}
@Test
......@@ -86,7 +84,6 @@ public class PayTest {
JSONArray products = JSONObject.fromObject(data).getJSONArray("products");
for (int i = 0; i < products.size(); i++) {
Products product = JSON.parseObject(data, Products.class);
System.out.println(products);
}
}
......@@ -94,7 +91,6 @@ public class PayTest {
public void test3() {
Integer count = 0;
while (count < 4) {
System.out.println("helloworld!");
count++;
}
}
......@@ -127,10 +123,7 @@ public class PayTest {
String url = "http://www.oschina.net/search?scope=bbs&q=C%E8%AF%AD%E8%A8%80";
String targetUrl = URLDecoder.decode(url, "utf-8");
Map<String, String> paramMap = HttpClientUtil.getParamMap(targetUrl);
System.out.println(paramMap);
String q = URLDecoder.decode(paramMap.get("q"), "utf-8");
System.out.println(q);
}
......@@ -147,15 +140,10 @@ public class PayTest {
.headers(new HashMap<>())
.asString();
System.out.println(response.getBody());
System.out.println("========================");
List<String> link = response.getHeaders().get("Link");
String str = link.get(0);
String[] split = str.split(",");
String s = split[0];
System.out.println(s.substring(s.lastIndexOf("page_info="), s.lastIndexOf(">;")));
}
/**
......@@ -187,7 +175,6 @@ public class PayTest {
String code = RandomStringUtils.randomNumeric(6);
param.put(YunpianConstant.TEXT, text);
com.yunpian.sdk.model.Result<SmsBatchSend> result = clnt.sms().batch_send(param);
System.out.println(result);
}
......@@ -221,7 +208,6 @@ public class PayTest {
// param.put(EXTEND, "001");
// param.put(UID, "10001");
com.yunpian.sdk.model.Result<SmsBatchSend> r = clnt.sms().tpl_batch_send(param);
System.out.println(r);
}
@Test
......@@ -233,13 +219,11 @@ public class PayTest {
if (!list.contains("20")) {
flag = true;
}
System.out.println(false);
}
@Test
public void testBigdecimal(){
BigDecimal b=new BigDecimal("0");
System.out.println(b!=null);
}
@Test
......
package com.diaoyun.zion;
public class Thead implements Runnable {
@Override
public void run() {
for (int i =0;i<10;i++) {
System.out.println("你好呀");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.diaoyun.zion;
public class ThreadImp {
public static void main(String[] args) {
Runnable r = new Thead();
Thread t = new Thread(r);
t.start();
}
}
......@@ -37,6 +37,12 @@ import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
@RunWith(SpringRunner.class)
@SpringBootTest
......@@ -425,7 +431,7 @@ public class ZionApplicationTests {
@Test
public void testDate() throws ParseException {
String res = "2019-12-10 10:04:59";
String res = "2019-12-17 04:44:00";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = simpleDateFormat.parse(res);
long it = date.getTime();
......@@ -517,28 +523,21 @@ public class ZionApplicationTests {
}
}
/* @Test
public void sendEmail() throws EmailException, TemplateException, IOException {
List<String> emailList= tbCfUserInfoService.findEmails();
for (String email:emailList){
}
String email="1203063316@qq.com";
tbCfUserInfoService.sendRegister(email);
}*/
@Test
public void sendMessageToAll() {
// String phone = "";
// List<TbCfUserInfoEntity> list = tbCfUserInfoService.selectUserByPhone();
// for (TbCfUserInfoEntity user : list) {
// phone += user.getPhone();
// phone += ",";
// }
// System.out.println(phone);
String text = "【Afrishop】We've updated!\n" +
String phone = "";
List<TbCfUserInfoEntity> list = tbCfUserInfoService.selectUserByPhone();
for (TbCfUserInfoEntity user : list) {
phone += user.getPhone();
phone += ",";
}
// System.out.println(phone);
String text = "We've updated!\n" +
"Thank you for downloading Afrishop. If you get a 'Server Busy' notification as you are trying to shop, be sure to sign out and sign in again. Be sure to check your device store for the lastest app updates.\n" +
"You can also shop using our website www.afrieshop.com\n" +
"Happy Shopping!";
SMSUtil.sendMessageByText(/*phone.trim()*/"+8613751400455,18607444177", text);
SMSUtil.sendMessageByText(/*phone.trim()*/"+8613751400455,+8618607444177", text);
}
@Resource
......@@ -549,16 +548,15 @@ public class ZionApplicationTests {
// String hour = orderRedisCache.expire("order_detf28b71d685a34c528180782520fef886");
String hour = getHour("3662");
System.out.println(hour);
// System.out.println(hour);
}
@Test
public void test01() {
System.out.println(orderRedisCache.expire("order_det3d8a6dc48d9c4916998ba25a75e91bc7"));
// System.out.println(orderRedisCache.expire("order_det3d8a6dc48d9c4916998ba25a75e91bc7"));
// orderRedisCache.set("order_detf28b71d685a34c528180782520fef886", 0);
//
// System.out.println(orderRedisCache.expire("order_detf28b71d685a34c528180782520fef886"));
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论