Commit e398eab0 authored by Administrator's avatar Administrator

Merge branch 'staging' into 'master'

Staging

See merge request !146
parents 2fb169b3 89b62bef
package com.edgec.browserbackend; package com.edgec.browserbackend;
import com.mongodb.MongoClient;
import net.javacrumbs.shedlock.core.LockProvider;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.Jsr310Converters; import org.springframework.data.convert.Jsr310Converters;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions; import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.provider.token.AuthenticationKeyGenerator; import org.springframework.security.oauth2.provider.token.AuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator; import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;
import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfiguration;
...@@ -35,10 +24,8 @@ import java.time.LocalDate; ...@@ -35,10 +24,8 @@ import java.time.LocalDate;
import java.time.ZoneId; import java.time.ZoneId;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.concurrent.CompletableFuture;
@SpringBootApplication @SpringBootApplication
@EnableGlobalMethodSecurity(prePostEnabled = true) @EnableGlobalMethodSecurity(prePostEnabled = true)
......
...@@ -2,16 +2,15 @@ package com.edgec.browserbackend.account.controller; ...@@ -2,16 +2,15 @@ package com.edgec.browserbackend.account.controller;
import com.edgec.browserbackend.account.domain.*; import com.edgec.browserbackend.account.domain.*;
import com.edgec.browserbackend.account.dto.*; import com.edgec.browserbackend.account.dto.*;
import com.edgec.browserbackend.account.service.AccountService;
import com.edgec.browserbackend.account.service.EmailService;
import com.edgec.browserbackend.account.service.PaymentService;
import com.edgec.browserbackend.alipay.AlipayConfig; import com.edgec.browserbackend.alipay.AlipayConfig;
import com.edgec.browserbackend.alipay.AlipaySubmit;
import com.edgec.browserbackend.alipay.VpsAlipayConfig; import com.edgec.browserbackend.alipay.VpsAlipayConfig;
import com.edgec.browserbackend.browser.ErrorCode.BrowserErrorCode; import com.edgec.browserbackend.browser.ErrorCode.BrowserErrorCode;
import com.edgec.browserbackend.common.auth.Securitys; import com.edgec.browserbackend.common.auth.Securitys;
import com.edgec.browserbackend.common.commons.error.ClientRequestException; import com.edgec.browserbackend.common.commons.error.ClientRequestException;
import com.edgec.browserbackend.common.commons.utils.DateConverter; import com.edgec.browserbackend.common.commons.utils.DateConverter;
import com.edgec.browserbackend.account.service.AccountService;
import com.edgec.browserbackend.account.service.EmailService;
import com.edgec.browserbackend.account.service.PaymentService;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils; import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
...@@ -27,10 +26,6 @@ import org.springframework.web.multipart.MultipartFile; ...@@ -27,10 +26,6 @@ import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid; import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.security.Principal; import java.security.Principal;
import java.time.ZoneOffset; import java.time.ZoneOffset;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
...@@ -38,7 +33,7 @@ import java.time.format.DateTimeFormatter; ...@@ -38,7 +33,7 @@ import java.time.format.DateTimeFormatter;
import java.util.*; import java.util.*;
@RestController @RestController
@RequestMapping("user") @RequestMapping("/user")
public class AccountController { public class AccountController {
public static final String WECHAT_PAY_CALLBACK_URL = "https://cloudam.cn/accounts/0xwxpaycallback/"; public static final String WECHAT_PAY_CALLBACK_URL = "https://cloudam.cn/accounts/0xwxpaycallback/";
...@@ -123,6 +118,7 @@ public class AccountController { ...@@ -123,6 +118,7 @@ public class AccountController {
accountService.sendSmsOtp(mobile.getMobile()); accountService.sendSmsOtp(mobile.getMobile());
resultDto.setStatus(0); resultDto.setStatus(0);
} catch (ClientRequestException e) { } catch (ClientRequestException e) {
logger.error("fail to send sms", e);
resultDto.setStatus(-1); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>(); Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode()); statusInfo.put("code", e.getErrorCode());
...@@ -206,14 +202,6 @@ public class AccountController { ...@@ -206,14 +202,6 @@ public class AccountController {
return accountService.findOverviewByYearAndMonth(principal.getName(), year, month, zoneId, service); return accountService.findOverviewByYearAndMonth(principal.getName(), year, month, zoneId, service);
} }
public static void main(String[] args) {
String intStr = "08";
int month = Integer.parseInt(intStr);
System.out.println(month);
}
@RequestMapping(path = "/current/updatetoken", method = RequestMethod.POST) @RequestMapping(path = "/current/updatetoken", method = RequestMethod.POST)
void updateUserToken(@RequestParam("username") String username, @RequestParam("token") String token) { void updateUserToken(@RequestParam("username") String username, @RequestParam("token") String token) {
accountService.updateUserToken(username, token); accountService.updateUserToken(username, token);
...@@ -225,7 +213,7 @@ public class AccountController { ...@@ -225,7 +213,7 @@ public class AccountController {
try { try {
accountService.resetPassword(principal.getName(), user); accountService.resetPassword(principal.getName(), user);
resultDto.setStatus(0); resultDto.setStatus(0);
}catch (ClientRequestException e) { } catch (ClientRequestException e) {
resultDto.setStatus(-1); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>(); Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode()); statusInfo.put("code", e.getErrorCode());
...@@ -246,7 +234,7 @@ public class AccountController { ...@@ -246,7 +234,7 @@ public class AccountController {
try { try {
accountService.resetPasswordWithOtp(user); accountService.resetPasswordWithOtp(user);
resultDto.setStatus(0); resultDto.setStatus(0);
}catch (ClientRequestException e) { } catch (ClientRequestException e) {
resultDto.setStatus(-1); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>(); Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode()); statusInfo.put("code", e.getErrorCode());
...@@ -356,8 +344,8 @@ public class AccountController { ...@@ -356,8 +344,8 @@ public class AccountController {
Pageable pageable = PageRequest.of(page, size); Pageable pageable = PageRequest.of(page, size);
String[] datas = strDate.split("-"); String[] datas = strDate.split("-");
int year = Integer.valueOf(datas[0]); int year = Integer.parseInt(datas[0]);
int month = Integer.valueOf(datas[1]); int month = Integer.parseInt(datas[1]);
int day = 0; int day = 0;
if (datas.length > 2) { if (datas.length > 2) {
day = Integer.valueOf(datas[2]); day = Integer.valueOf(datas[2]);
...@@ -399,7 +387,7 @@ public class AccountController { ...@@ -399,7 +387,7 @@ public class AccountController {
} }
@RequestMapping(path = "/preorder/delete/{username}", method = RequestMethod.POST) @RequestMapping(path = "/preorder/delete/{username}", method = RequestMethod.POST)
public String deletePreOrder( @PathVariable("username") String username) { public String deletePreOrder(@PathVariable("username") String username) {
return accountService.deletePreOrder(username); return accountService.deletePreOrder(username);
} }
...@@ -439,7 +427,7 @@ public class AccountController { ...@@ -439,7 +427,7 @@ public class AccountController {
} }
accountService.authorizeCompany(principal.getName(), companyAuthorizeDto); accountService.authorizeCompany(principal.getName(), companyAuthorizeDto);
resultDto.setStatus(0); resultDto.setStatus(0);
}catch (ClientRequestException e) { } catch (ClientRequestException e) {
resultDto.setStatus(-1); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>(); Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode()); statusInfo.put("code", e.getErrorCode());
...@@ -450,14 +438,14 @@ public class AccountController { ...@@ -450,14 +438,14 @@ public class AccountController {
} }
@RequestMapping(path = "/ali/login", method = RequestMethod.GET) @RequestMapping(path = "/ali/login", method = RequestMethod.GET)
public String save(HttpServletRequest request,HttpServletResponse response) { public String save(HttpServletRequest request, HttpServletResponse response) {
//页面回调地址 必须与应用中的设置一样 //页面回调地址 必须与应用中的设置一样
String return_url = "http://https://www.fangguanlian.cn/ali/withdraw"; String return_url = "http://https://www.fangguanlian.cn/ali/withdraw";
//回调地址必须经encode //回调地址必须经encode
return_url = java.net.URLEncoder.encode(return_url); return_url = java.net.URLEncoder.encode(return_url);
//重定向到授权页面 //重定向到授权页面
AlipayConfig alipayConfig = new VpsAlipayConfig(); AlipayConfig alipayConfig = new VpsAlipayConfig();
return "redirect:"+ VpsAlipayConfig.ALIPAY_AUTH_URL + "?app_id=" + alipayConfig.getAPPID() + "&scope=auth_user&redirect_uri=" + return_url; return "redirect:" + VpsAlipayConfig.ALIPAY_AUTH_URL + "?app_id=" + alipayConfig.getAPPID() + "&scope=auth_user&redirect_uri=" + return_url;
} }
@RequestMapping(path = "/ali/withdraw", method = RequestMethod.PUT) @RequestMapping(path = "/ali/withdraw", method = RequestMethod.PUT)
......
...@@ -7,37 +7,37 @@ public enum AccountErrorCode implements ErrorCode { ...@@ -7,37 +7,37 @@ public enum AccountErrorCode implements ErrorCode {
/* client errors */ /* client errors */
UNKNOWN(ErrorCode.COMMON_UNKNOWN,"unknown"), UNKNOWN(ErrorCode.COMMON_UNKNOWN, "unknown"),
NAMEEXIST(ACCOUNT_BASE+100, "Username exists"), NAMEEXIST(ACCOUNT_BASE + 100, "Username exists"),
NAMENOTEXIST(ACCOUNT_BASE+102, "Username does not exist"), NAMENOTEXIST(ACCOUNT_BASE + 102, "Username does not exist"),
EMAILEXIST(ACCOUNT_BASE+101, "Email exists"), EMAILEXIST(ACCOUNT_BASE + 101, "Email exists"),
EMAILNOTEXIST(ACCOUNT_BASE+103, "Email does not exist"), EMAILNOTEXIST(ACCOUNT_BASE + 103, "Email does not exist"),
NAMEOREMAILNOTEXIST(ACCOUNT_BASE+104, "Username or Email does not exist"), NAMEOREMAILNOTEXIST(ACCOUNT_BASE + 104, "Username or Email does not exist"),
NOTALLOWEDTOCREATESUBUSER(ACCOUNT_BASE+105, "The account isn't allowed to create sub user"), NOTALLOWEDTOCREATESUBUSER(ACCOUNT_BASE + 105, "The account isn't allowed to create sub user"),
PHONEEXIST(ACCOUNT_BASE+106, "Phone number exists"), PHONEEXIST(ACCOUNT_BASE + 106, "Phone number exists"),
OTPWRONG(ACCOUNT_BASE+107, "otp invalid or expires"), OTPWRONG(ACCOUNT_BASE + 107, "otp invalid or expires"),
OTPSENDFAILS(ACCOUNT_BASE+108, "otp sends failure"), OTPSENDFAILS(ACCOUNT_BASE + 108, "otp sends failure"),
PHONENOTEXIST(ACCOUNT_BASE+109, "Can not find account with phone number"), PHONENOTEXIST(ACCOUNT_BASE + 109, "Can not find account with phone number"),
INVALIDTOKEN(ErrorCode.COMMON_INVALID_TOKEN, "Invalid token"), INVALIDTOKEN(ErrorCode.COMMON_INVALID_TOKEN, "Invalid token"),
UNAUTHORIZED(ErrorCode.COMMON_UNAUTHRORIZED, "Unauthorized operation"), UNAUTHORIZED(ErrorCode.COMMON_UNAUTHRORIZED, "Unauthorized operation"),
NAMEEMPTY(ACCOUNT_BASE+110, "Username connot be empty"), NAMEEMPTY(ACCOUNT_BASE + 110, "Username connot be empty"),
EMAILEMPTY(ACCOUNT_BASE+111, "Email connot be empty"), EMAILEMPTY(ACCOUNT_BASE + 111, "Email connot be empty"),
PHONEEMPTY(ACCOUNT_BASE+112, "PhoneNumber connot be empty"), PHONEEMPTY(ACCOUNT_BASE + 112, "PhoneNumber connot be empty"),
AGENCYNOEXIST(ACCOUNT_BASE+113, "uuid dose not exists"), AGENCYNOEXIST(ACCOUNT_BASE + 113, "uuid dose not exists"),
CHILDSCALINGSTATEUNABATED(ACCOUNT_BASE+114, "Can't delete child whose still have scaling group "), CHILDSCALINGSTATEUNABATED(ACCOUNT_BASE + 114, "Can't delete child whose still have scaling group "),
BINDORDERERROR_NOTEXIST(ACCOUNT_BASE+115,"This order is not exist"), BINDORDERERROR_NOTEXIST(ACCOUNT_BASE + 115, "This order is not exist"),
BINDORDERERROR_BINDBYOTHERS(ACCOUNT_BASE+116,"This order has been bind by others"), BINDORDERERROR_BINDBYOTHERS(ACCOUNT_BASE + 116, "This order has been bind by others"),
BINDORDERERROR_NOTQUALIFIED(ACCOUNT_BASE+117,"You don't have free qualified"), BINDORDERERROR_NOTQUALIFIED(ACCOUNT_BASE + 117, "You don't have free qualified"),
BINDORDERERROR_HAVEORDER(ACCOUNT_BASE+118,"You have an unpaid order"), BINDORDERERROR_HAVEORDER(ACCOUNT_BASE + 118, "You have an unpaid order"),
BINDORDERERROR_NOTKNOW(ACCOUNT_BASE+119,"Order generate error,please try again"), BINDORDERERROR_NOTKNOW(ACCOUNT_BASE + 119, "Order generate error,please try again"),
/* http request error */ /* http request error */
OTHERS(ErrorCode.COMMON_OTHERS, "http request error"), OTHERS(ErrorCode.COMMON_OTHERS, "http request error"),
...@@ -45,19 +45,22 @@ public enum AccountErrorCode implements ErrorCode { ...@@ -45,19 +45,22 @@ public enum AccountErrorCode implements ErrorCode {
/* server errors */ /* server errors */
EMAILSENTERROR(ErrorCode.COMMON_SERVER_ERROR, "email sending error"), EMAILSENTERROR(ErrorCode.COMMON_SERVER_ERROR, "email sending error"),
/** wechat errors */ /**
WECHATERROR(ACCOUNT_BASE+120, "Wechat order generation error"), * wechat errors
*/
WECHATERROR(ACCOUNT_BASE + 120, "Wechat order generation error"),
/** alipay errors */ /**
ALIPAYERROR(ACCOUNT_BASE+130, "Alipay order generation error"), * alipay errors
*/
ALIPAYERROR(ACCOUNT_BASE + 130, "Alipay order generation error"),
NOPERMISSION(ACCOUNT_BASE+140, "You have no right to do this operarion"), NOPERMISSION(ACCOUNT_BASE + 140, "You have no right to do this operarion"),
GROUPMAX(ACCOUNT_BASE+141, "You can not have more groups"), GROUPMAX(ACCOUNT_BASE + 141, "You can not have more groups"),
SHOPMAX(ACCOUNT_BASE+142, "You can not have more shops"), SHOPMAX(ACCOUNT_BASE + 142, "You can not have more shops"),
CHILDMAX(ACCOUNT_BASE+143, "You can not have more subUsers"), CHILDMAX(ACCOUNT_BASE + 143, "You can not have more subUsers"),
NOTENOUGHBALANCE(ErrorCode.ACCOUNT_BASE+150, "Your balance is not enough");
NOTENOUGHBALANCE(ErrorCode.ACCOUNT_BASE + 150, "Your balance is not enough");
private final int code; private final int code;
...@@ -68,10 +71,12 @@ public enum AccountErrorCode implements ErrorCode { ...@@ -68,10 +71,12 @@ public enum AccountErrorCode implements ErrorCode {
this.reason = reasonPhrase; this.reason = reasonPhrase;
} }
@Override
public int value() { public int value() {
return this.code; return this.code;
} }
@Override
@JsonValue @JsonValue
public int getCode() { public int getCode() {
return code; return code;
...@@ -82,6 +87,7 @@ public enum AccountErrorCode implements ErrorCode { ...@@ -82,6 +87,7 @@ public enum AccountErrorCode implements ErrorCode {
return Integer.toString(this.code); return Integer.toString(this.code);
} }
@Override
public String getReason() { public String getReason() {
return reason; return reason;
} }
......
package com.edgec.browserbackend.account.service.impl; package com.edgec.browserbackend.account.service.impl;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.edgec.browserbackend.account.dto.*;
import com.edgec.browserbackend.account.service.AccountService;
import com.edgec.browserbackend.account.service.PaymentService;
import com.edgec.browserbackend.account.domain.*; import com.edgec.browserbackend.account.domain.*;
import com.edgec.browserbackend.account.dto.*;
import com.edgec.browserbackend.account.exception.AccountErrorCode; import com.edgec.browserbackend.account.exception.AccountErrorCode;
import com.edgec.browserbackend.account.repository.*; import com.edgec.browserbackend.account.repository.*;
import com.edgec.browserbackend.account.service.AccountService;
import com.edgec.browserbackend.account.service.EmailService; import com.edgec.browserbackend.account.service.EmailService;
import com.edgec.browserbackend.account.service.PaymentService;
import com.edgec.browserbackend.account.service.SmsUtils; import com.edgec.browserbackend.account.service.SmsUtils;
import com.edgec.browserbackend.account.utils.AccountServicePool; import com.edgec.browserbackend.account.utils.AccountServicePool;
import com.edgec.browserbackend.auth.exception.AuthErrorCode; import com.edgec.browserbackend.auth.exception.AuthErrorCode;
...@@ -33,7 +33,7 @@ import org.springframework.transaction.annotation.Transactional; ...@@ -33,7 +33,7 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.thymeleaf.util.StringUtils; import org.thymeleaf.util.StringUtils;
import java.io.*; import java.io.File;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.time.Instant; import java.time.Instant;
import java.time.YearMonth; import java.time.YearMonth;
...@@ -322,7 +322,8 @@ public class AccountServiceImpl implements AccountService { ...@@ -322,7 +322,8 @@ public class AccountServiceImpl implements AccountService {
@Override @Override
public ResultDto getAccountByName(String name) { public ResultDto getAccountByName(String name) {
Assert.hasLength(name); Assert.hasLength(name, "账户名不能为空");
ResultDto resultDto = new ResultDto(); ResultDto resultDto = new ResultDto();
try { try {
Account account = this.findByName(name); Account account = this.findByName(name);
...@@ -398,6 +399,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -398,6 +399,7 @@ public class AccountServiceImpl implements AccountService {
return resultDto; return resultDto;
} }
@Override
public void deleteByName(String name) { public void deleteByName(String name) {
userService.deleteUser(name); userService.deleteUser(name);
repository.deleteById(name); repository.deleteById(name);
...@@ -411,6 +413,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -411,6 +413,7 @@ public class AccountServiceImpl implements AccountService {
return create(user, null); return create(user, null);
} }
@Override
public void deleteSub(String parent, String child) { public void deleteSub(String parent, String child) {
Assert.hasText(parent); Assert.hasText(parent);
Account childAccount = repository.findByName(child); Account childAccount = repository.findByName(child);
...@@ -1177,8 +1180,7 @@ public class AccountServiceImpl implements AccountService { ...@@ -1177,8 +1180,7 @@ public class AccountServiceImpl implements AccountService {
CompanyAuthorize companyAuthorize = companyAuthorizeRepository.findByUsername(username); CompanyAuthorize companyAuthorize = companyAuthorizeRepository.findByUsername(username);
account.setCompanyName(companyAuthorize.getCompanyName()); account.setCompanyName(companyAuthorize.getCompanyName());
repository.save(account); repository.save(account);
} } else {
else {
account.setAuthorized(3); account.setAuthorized(3);
account.setCompanyName(null); account.setCompanyName(null);
repository.save(account); repository.save(account);
......
...@@ -30,9 +30,10 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { ...@@ -30,9 +30,10 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
.csrf().disable(); .csrf().disable();
} }
@Override
public void configure(WebSecurity web) throws Exception { public void configure(WebSecurity web) throws Exception {
web.ignoring() web.ignoring()
.antMatchers( "/user/authCode", "/user/signUp", .antMatchers("/user/authCode", "/user/signUp",
"/user/forgot**", "/0xadministrator/getconfig**"); "/user/forgot**", "/0xadministrator/getconfig**");
} }
......
...@@ -8,16 +8,16 @@ public enum AuthErrorCode implements ErrorCode { ...@@ -8,16 +8,16 @@ public enum AuthErrorCode implements ErrorCode {
/* http request error */ /* http request error */
OTHERS(ErrorCode.COMMON_OTHERS, "http request error"), OTHERS(ErrorCode.COMMON_OTHERS, "http request error"),
AUTHENTICATION_ERROR(ErrorCode.AUTH_BASE+100, "authentication failure"), AUTHENTICATION_ERROR(ErrorCode.AUTH_BASE + 100, "authentication failure"),
AUTHORIZATION_ERROR(ErrorCode.AUTH_BASE+200, "authorization failure"), AUTHORIZATION_ERROR(ErrorCode.AUTH_BASE + 200, "authorization failure"),
NAMEEXIST(AUTH_BASE+106, "Username exists"), NAMEEXIST(AUTH_BASE + 106, "Username exists"),
NAMENOTEXIST(AUTH_BASE+102, "Username does not exist"), NAMENOTEXIST(AUTH_BASE + 102, "Username does not exist"),
EMAILEXIST(AUTH_BASE+101, "Email exists"), EMAILEXIST(AUTH_BASE + 101, "Email exists"),
EMAILNOTEXIST(AUTH_BASE+103, "Email does not exist"), EMAILNOTEXIST(AUTH_BASE + 103, "Email does not exist"),
NAMEOREMAILNOTEXIST(AUTH_BASE+104, "Username or Email does not exist"), NAMEOREMAILNOTEXIST(AUTH_BASE + 104, "Username or Email does not exist"),
WRONGEMAILCODE(AUTH_BASE+105, "Wrong verification code"), WRONGEMAILCODE(AUTH_BASE + 105, "Wrong verification code"),
LOGINTIMESEXCEEDED(AUTH_BASE+107, "Login times exceeded"), LOGINTIMESEXCEEDED(AUTH_BASE + 107, "Login times exceeded"),
/* server errors */ /* server errors */
INTERNALSERVERERROR(ErrorCode.COMMON_SERVER_ERROR, "internal server error"); INTERNALSERVERERROR(ErrorCode.COMMON_SERVER_ERROR, "internal server error");
...@@ -31,11 +31,13 @@ public enum AuthErrorCode implements ErrorCode { ...@@ -31,11 +31,13 @@ public enum AuthErrorCode implements ErrorCode {
this.reason = reasonPhrase; this.reason = reasonPhrase;
} }
@Override
public int value() { public int value() {
return this.code; return this.code;
} }
@JsonValue @JsonValue
@Override
public int getCode() { public int getCode() {
return code; return code;
} }
...@@ -45,6 +47,7 @@ public enum AuthErrorCode implements ErrorCode { ...@@ -45,6 +47,7 @@ public enum AuthErrorCode implements ErrorCode {
return Integer.toString(this.code); return Integer.toString(this.code);
} }
@Override
public String getReason() { public String getReason() {
return reason; return reason;
} }
......
...@@ -12,8 +12,6 @@ import org.springframework.context.ApplicationListener; ...@@ -12,8 +12,6 @@ import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent; import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.Date;
@Component @Component
public class AuthenticationSuccessEventListener implements ApplicationListener<AuthenticationSuccessEvent> { public class AuthenticationSuccessEventListener implements ApplicationListener<AuthenticationSuccessEvent> {
...@@ -30,9 +28,9 @@ public class AuthenticationSuccessEventListener implements ApplicationListener<A ...@@ -30,9 +28,9 @@ public class AuthenticationSuccessEventListener implements ApplicationListener<A
User user = userRepository.findById(username).orElse(null); User user = userRepository.findById(username).orElse(null);
if (user != null) { if (user != null) {
UserAttemptsLogin userAttempts = userAttemptsLoginRepository.findById(username).orElse(null); UserAttemptsLogin userAttempts = userAttemptsLoginRepository.findById(username).orElse(null);
if(userAttempts != null) { if (userAttempts != null) {
if (userAttempts.getAttempts() >= 20) { if (userAttempts.getAttempts() >= 20) {
if (userAttempts.getDate().getTime() >= (new Date().getTime() - 600000)) if (userAttempts.getDate().getTime() >= (System.currentTimeMillis() - 600000))
throw new ClientRequestException(AuthErrorCode.LOGINTIMESEXCEEDED, "Login times exceeded"); throw new ClientRequestException(AuthErrorCode.LOGINTIMESEXCEEDED, "Login times exceeded");
} else if (userAttempts.getAttempts() != 0) { } else if (userAttempts.getAttempts() != 0) {
saveUserAttemptsLogin(username, 0); saveUserAttemptsLogin(username, 0);
......
...@@ -7,20 +7,20 @@ public enum BrowserErrorCode implements ErrorCode { ...@@ -7,20 +7,20 @@ public enum BrowserErrorCode implements ErrorCode {
/* client errors */ /* client errors */
UNKNOWN(ErrorCode.COMMON_UNKNOWN,"unknown"), UNKNOWN(ErrorCode.COMMON_UNKNOWN, "unknown"),
INFORMATIONNOTCOMPELETE(BROWSER_BASE+100, "The information about shop does not complete"), INFORMATIONNOTCOMPELETE(BROWSER_BASE + 100, "The information about shop does not complete"),
SHOPNOTEXIST(BROWSER_BASE+101, "The shop does not exist"), SHOPNOTEXIST(BROWSER_BASE + 101, "The shop does not exist"),
SHOP_BINDED(BROWSER_BASE + 102, "The shop has bind with ip"),
IPNOTEXIST(BROWSER_BASE+201, "The ip do not exist"), IPNOTEXIST(BROWSER_BASE + 201, "The ip do not exist"),
IPNOTBINDTOSHOP(BROWSER_BASE+202, "The ip does not bind this shop."), IPNOTBINDTOSHOP(BROWSER_BASE + 202, "The ip does not bind this shop."),
GROUPNOTEXIST(BROWSER_BASE+301, "The group does not exist"), GROUPNOTEXIST(BROWSER_BASE + 301, "The group does not exist"),
IPTRANSACTIONNOTEXIST(BROWSER_BASE+401, "The ipTransaction does not exist"), IPTRANSACTIONNOTEXIST(BROWSER_BASE + 401, "The ipTransaction does not exist"),
COMPANYAUTHORIZEEXIST(BROWSER_BASE+501, "The authority exists"),
COMPANYAUTHORIZENOTEXIST(BROWSER_BASE+502, "The authority dose not exist");
COMPANYAUTHORIZEEXIST(BROWSER_BASE + 501, "The authority exists"),
COMPANYAUTHORIZENOTEXIST(BROWSER_BASE + 502, "The authority dose not exist");
private final int code; private final int code;
...@@ -31,11 +31,13 @@ public enum BrowserErrorCode implements ErrorCode { ...@@ -31,11 +31,13 @@ public enum BrowserErrorCode implements ErrorCode {
this.reason = reasonPhrase; this.reason = reasonPhrase;
} }
@Override
public int value() { public int value() {
return this.code; return this.code;
} }
@JsonValue @JsonValue
@Override
public int getCode() { public int getCode() {
return code; return code;
} }
...@@ -45,6 +47,7 @@ public enum BrowserErrorCode implements ErrorCode { ...@@ -45,6 +47,7 @@ public enum BrowserErrorCode implements ErrorCode {
return Integer.toString(this.code); return Integer.toString(this.code);
} }
@Override
public String getReason() { public String getReason() {
return reason; return reason;
} }
......
package com.edgec.browserbackend.browser.controller; package com.edgec.browserbackend.browser.controller;
import com.edgec.browserbackend.account.dto.ResultDto; import com.edgec.browserbackend.account.dto.ResultDto;
import com.edgec.browserbackend.browser.domain.OperationHistory;
import com.edgec.browserbackend.browser.dto.HistoryListRequestDto; import com.edgec.browserbackend.browser.dto.HistoryListRequestDto;
import com.edgec.browserbackend.browser.dto.IpResourceRequestDto;
import com.edgec.browserbackend.browser.dto.LoginHistoryDto; import com.edgec.browserbackend.browser.dto.LoginHistoryDto;
import com.edgec.browserbackend.browser.dto.OperationHistoryDto; import com.edgec.browserbackend.browser.dto.OperationHistoryDto;
import com.edgec.browserbackend.browser.service.HistoryService; import com.edgec.browserbackend.browser.service.HistoryService;
...@@ -32,11 +30,7 @@ public class HistoryController { ...@@ -32,11 +30,7 @@ public class HistoryController {
historyService.addLoginHistory(principal.getName(), loginHistoryDto); historyService.addLoginHistory(principal.getName(), loginHistoryDto);
resultDto.setStatus(0); resultDto.setStatus(0);
} catch (ClientRequestException e) { } catch (ClientRequestException e) {
resultDto.setStatus(-1); dealClientRequestException(resultDto, e);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
...@@ -48,11 +42,7 @@ public class HistoryController { ...@@ -48,11 +42,7 @@ public class HistoryController {
historyService.addOperationHistory(principal.getName(), operationHistoryDto); historyService.addOperationHistory(principal.getName(), operationHistoryDto);
resultDto.setStatus(0); resultDto.setStatus(0);
} catch (ClientRequestException e) { } catch (ClientRequestException e) {
resultDto.setStatus(-1); dealClientRequestException(resultDto, e);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
...@@ -64,11 +54,7 @@ public class HistoryController { ...@@ -64,11 +54,7 @@ public class HistoryController {
resultDto.setData(historyService.getLoginHistories(principal.getName(), historyListRequestDto)); resultDto.setData(historyService.getLoginHistories(principal.getName(), historyListRequestDto));
resultDto.setStatus(0); resultDto.setStatus(0);
} catch (ClientRequestException e) { } catch (ClientRequestException e) {
resultDto.setStatus(-1); dealClientRequestException(resultDto, e);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
...@@ -80,12 +66,16 @@ public class HistoryController { ...@@ -80,12 +66,16 @@ public class HistoryController {
resultDto.setData(historyService.getOperationHistories(principal.getName(), historyListRequestDto)); resultDto.setData(historyService.getOperationHistories(principal.getName(), historyListRequestDto));
resultDto.setStatus(0); resultDto.setStatus(0);
} catch (ClientRequestException e) { } catch (ClientRequestException e) {
dealClientRequestException(resultDto, e);
}
return resultDto;
}
private void dealClientRequestException(ResultDto resultDto, ClientRequestException e) {
resultDto.setStatus(-1); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>(); Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode()); statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage()); statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo); resultDto.setStatusInfo(statusInfo);
} }
return resultDto;
}
} }
package com.edgec.browserbackend.browser.controller; package com.edgec.browserbackend.browser.controller;
import com.edgec.browserbackend.account.dto.ResultDto; import com.edgec.browserbackend.account.dto.ResultDto;
import com.edgec.browserbackend.browser.dto.*; import com.edgec.browserbackend.browser.dto.IpListRequestDto;
import com.edgec.browserbackend.browser.dto.IpPageResultDto;
import com.edgec.browserbackend.browser.dto.IpResourceRequestDto;
import com.edgec.browserbackend.browser.dto.IpResourceUpdateDto;
import com.edgec.browserbackend.browser.service.IpResourceService; import com.edgec.browserbackend.browser.service.IpResourceService;
import com.edgec.browserbackend.common.auth.Securitys; import com.edgec.browserbackend.common.auth.Securitys;
import com.edgec.browserbackend.common.commons.error.ClientRequestException; import com.edgec.browserbackend.common.commons.error.ClientRequestException;
...@@ -25,7 +28,7 @@ public class IpControlloer { ...@@ -25,7 +28,7 @@ public class IpControlloer {
private IpResourceService ipResourceService; private IpResourceService ipResourceService;
@RequestMapping(value = "/buy", method = RequestMethod.POST) @RequestMapping(value = "/buy", method = RequestMethod.POST)
public ResultDto buyIp(Principal principal, @RequestBody IpResourceRequestDto ipResourceRequestDto){ public ResultDto buyIp(Principal principal, @RequestBody IpResourceRequestDto ipResourceRequestDto) {
ResultDto resultDto = new ResultDto(); ResultDto resultDto = new ResultDto();
try { try {
List<String> ipResourceDto = ipResourceService.buyIp(principal.getName(), ipResourceRequestDto); List<String> ipResourceDto = ipResourceService.buyIp(principal.getName(), ipResourceRequestDto);
...@@ -93,7 +96,7 @@ public class IpControlloer { ...@@ -93,7 +96,7 @@ public class IpControlloer {
ipListRequestDto.getAmount(), ipListRequestDto.getFilter()); ipListRequestDto.getAmount(), ipListRequestDto.getFilter());
resultDto.setData(ipResourceDto); resultDto.setData(ipResourceDto);
resultDto.setStatus(0); resultDto.setStatus(0);
}catch (ClientRequestException e) { } catch (ClientRequestException e) {
resultDto.setStatus(-1); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>(); Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode()); statusInfo.put("code", e.getErrorCode());
...@@ -110,6 +113,12 @@ public class IpControlloer { ...@@ -110,6 +113,12 @@ public class IpControlloer {
try { try {
ipResourceService.updateIp(principal.getName(), ipResourceUpdateDto); ipResourceService.updateIp(principal.getName(), ipResourceUpdateDto);
resultDto.setStatus(0); resultDto.setStatus(0);
} catch (ClientRequestException e) {
resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode().getCode());
statusInfo.put("message", e.getErrorCode().getReason());
resultDto.setStatusInfo(statusInfo);
} catch (Exception e) { } catch (Exception e) {
resultDto.setStatus(-1); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>(); Map<String, Object> statusInfo = new HashMap<>();
......
package com.edgec.browserbackend.browser.controller; package com.edgec.browserbackend.browser.controller;
import com.alibaba.fastjson.JSONObject;
import com.edgec.browserbackend.account.dto.ResultDto; import com.edgec.browserbackend.account.dto.ResultDto;
import com.edgec.browserbackend.browser.ErrorCode.BrowserErrorCode; import com.edgec.browserbackend.browser.ErrorCode.BrowserErrorCode;
import com.edgec.browserbackend.browser.domain.Shop; import com.edgec.browserbackend.browser.dto.ShopPageResultDto;
import com.edgec.browserbackend.browser.dto.*; import com.edgec.browserbackend.browser.dto.ShopRequestDto;
import com.edgec.browserbackend.browser.dto.ShopResultDto;
import com.edgec.browserbackend.browser.dto.ShopStringResultDto;
import com.edgec.browserbackend.browser.service.IpAndShopService; import com.edgec.browserbackend.browser.service.IpAndShopService;
import com.edgec.browserbackend.browser.service.ShopService; import com.edgec.browserbackend.browser.service.ShopService;
import com.edgec.browserbackend.common.commons.error.ClientRequestException; import com.edgec.browserbackend.common.commons.error.ClientRequestException;
import com.edgec.browserbackend.common.utils.FileUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -16,7 +18,6 @@ import org.springframework.web.multipart.MultipartFile; ...@@ -16,7 +18,6 @@ import org.springframework.web.multipart.MultipartFile;
import java.io.IOException; import java.io.IOException;
import java.security.Principal; import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
...@@ -41,12 +42,8 @@ public class ShopController { ...@@ -41,12 +42,8 @@ public class ShopController {
shopStringResultDto.setId(shopService.addShop(principal.getName(), shopResultDto)); shopStringResultDto.setId(shopService.addShop(principal.getName(), shopResultDto));
resultDto.setData(shopStringResultDto); resultDto.setData(shopStringResultDto);
resultDto.setStatus(0); resultDto.setStatus(0);
}catch (ClientRequestException e) { } catch (ClientRequestException e) {
resultDto.setStatus(-1); dealClientRequestException(resultDto, e);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
...@@ -55,7 +52,7 @@ public class ShopController { ...@@ -55,7 +52,7 @@ public class ShopController {
public ResultDto addShops(Principal principal, @RequestParam("file") MultipartFile file) { public ResultDto addShops(Principal principal, @RequestParam("file") MultipartFile file) {
ResultDto resultDto = new ResultDto(); ResultDto resultDto = new ResultDto();
String name = file.getOriginalFilename(); String name = file.getOriginalFilename();
if(name.length()<6 || !name.substring(name.length()-5).equals(".xlsx")){ if (name.length() < 6 || !name.substring(name.length() - 5).equals(".xlsx")) {
resultDto.setStatus(-1); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>(); Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", BrowserErrorCode.INFORMATIONNOTCOMPELETE.getCode()); statusInfo.put("code", BrowserErrorCode.INFORMATIONNOTCOMPELETE.getCode());
...@@ -72,10 +69,7 @@ public class ShopController { ...@@ -72,10 +69,7 @@ public class ShopController {
statusInfo.put("message", e.getMessage()); statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo); resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
@RequestMapping(value = "/update", method = RequestMethod.POST) @RequestMapping(value = "/update", method = RequestMethod.POST)
...@@ -86,12 +80,8 @@ public class ShopController { ...@@ -86,12 +80,8 @@ public class ShopController {
shopStringResultDto.setId(shopService.updateShop(principal.getName(), shopResultDto)); shopStringResultDto.setId(shopService.updateShop(principal.getName(), shopResultDto));
resultDto.setData(shopStringResultDto); resultDto.setData(shopStringResultDto);
resultDto.setStatus(0); resultDto.setStatus(0);
}catch (ClientRequestException e) { } catch (ClientRequestException e) {
resultDto.setStatus(-1); dealClientRequestException(resultDto, e);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
...@@ -102,12 +92,8 @@ public class ShopController { ...@@ -102,12 +92,8 @@ public class ShopController {
try { try {
shopService.deleteShop(principal.getName(), shopRequestDto.getShopId()); shopService.deleteShop(principal.getName(), shopRequestDto.getShopId());
resultDto.setStatus(0); resultDto.setStatus(0);
}catch (ClientRequestException e) { } catch (ClientRequestException e) {
resultDto.setStatus(-1); dealClientRequestException(resultDto, e);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
...@@ -118,12 +104,9 @@ public class ShopController { ...@@ -118,12 +104,9 @@ public class ShopController {
try { try {
ipAndShopService.bindShop(principal.getName(), shopRequestDto); ipAndShopService.bindShop(principal.getName(), shopRequestDto);
resultDto.setStatus(0); resultDto.setStatus(0);
}catch (ClientRequestException e) { } catch (ClientRequestException e) {
resultDto.setStatus(-1); logger.error("fail to bind shop", e);
Map<String, Object> statusInfo = new HashMap<>(); dealClientRequestException(resultDto, e);
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
...@@ -134,12 +117,8 @@ public class ShopController { ...@@ -134,12 +117,8 @@ public class ShopController {
try { try {
ipAndShopService.unBindShop(principal.getName(), shopRequestDto); ipAndShopService.unBindShop(principal.getName(), shopRequestDto);
resultDto.setStatus(0); resultDto.setStatus(0);
}catch (ClientRequestException e) { } catch (ClientRequestException e) {
resultDto.setStatus(-1); dealClientRequestException(resultDto, e);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
...@@ -150,12 +129,8 @@ public class ShopController { ...@@ -150,12 +129,8 @@ public class ShopController {
try { try {
shopService.transferShop(principal.getName(), shopRequestDto.getShopId(), shopRequestDto.getToGroup()); shopService.transferShop(principal.getName(), shopRequestDto.getShopId(), shopRequestDto.getToGroup());
resultDto.setStatus(0); resultDto.setStatus(0);
}catch (ClientRequestException e) { } catch (ClientRequestException e) {
resultDto.setStatus(-1); dealClientRequestException(resultDto, e);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
...@@ -166,30 +141,23 @@ public class ShopController { ...@@ -166,30 +141,23 @@ public class ShopController {
try { try {
shopService.assignShops(principal.getName(), shopRequestDto.getShopIds(), shopRequestDto.getToUsers()); shopService.assignShops(principal.getName(), shopRequestDto.getShopIds(), shopRequestDto.getToUsers());
resultDto.setStatus(0); resultDto.setStatus(0);
}catch (ClientRequestException e) { } catch (ClientRequestException e) {
resultDto.setStatus(-1); dealClientRequestException(resultDto, e);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
@RequestMapping(value = "/list",method = RequestMethod.POST) @RequestMapping(value = "/list", method = RequestMethod.POST)
public ResultDto getShopList(Principal principal, @RequestBody ShopRequestDto shopRequestDto) { public ResultDto getShopList(Principal principal, @RequestBody ShopRequestDto shopRequestDto) {
logger.info("shop list params {}", JSONObject.toJSONString(shopRequestDto));
ResultDto resultDto = new ResultDto(); ResultDto resultDto = new ResultDto();
try { try {
ShopPageResultDto shopDtos = shopService.getShopList(principal.getName(), shopRequestDto.getGroup(), shopRequestDto.getPage(), ShopPageResultDto shopDtos = shopService.getShopList(principal.getName(), shopRequestDto.getGroup(),
shopRequestDto.getAmount(), shopRequestDto.getFilter()); shopRequestDto.getPage(), shopRequestDto.getAmount(), shopRequestDto.getFilter());
resultDto.setData(shopDtos); resultDto.setData(shopDtos);
resultDto.setStatus(0); resultDto.setStatus(0);
}catch (ClientRequestException e) { } catch (ClientRequestException e) {
resultDto.setStatus(-1); dealClientRequestException(resultDto, e);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
...@@ -201,12 +169,8 @@ public class ShopController { ...@@ -201,12 +169,8 @@ public class ShopController {
List<String> subUsers = shopService.getShopUsers(principal.getName(), shopRequestDto.getShopId()); List<String> subUsers = shopService.getShopUsers(principal.getName(), shopRequestDto.getShopId());
resultDto.setData(subUsers); resultDto.setData(subUsers);
resultDto.setStatus(0); resultDto.setStatus(0);
}catch (ClientRequestException e) { } catch (ClientRequestException e) {
resultDto.setStatus(-1); dealClientRequestException(resultDto, e);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
...@@ -218,12 +182,8 @@ public class ShopController { ...@@ -218,12 +182,8 @@ public class ShopController {
List<String> subUsers = shopService.getBatchShopUsers(principal.getName(), shopRequestDto.getShopIds()); List<String> subUsers = shopService.getBatchShopUsers(principal.getName(), shopRequestDto.getShopIds());
resultDto.setData(subUsers); resultDto.setData(subUsers);
resultDto.setStatus(0); resultDto.setStatus(0);
}catch (ClientRequestException e) { } catch (ClientRequestException e) {
resultDto.setStatus(-1); dealClientRequestException(resultDto, e);
Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo);
} }
return resultDto; return resultDto;
} }
...@@ -235,13 +195,17 @@ public class ShopController { ...@@ -235,13 +195,17 @@ public class ShopController {
ShopResultDto shopDto = shopService.queryShop(principal.getName(), shopRequestDto.getShopId()); ShopResultDto shopDto = shopService.queryShop(principal.getName(), shopRequestDto.getShopId());
resultDto.setData(shopDto); resultDto.setData(shopDto);
resultDto.setStatus(0); resultDto.setStatus(0);
}catch (ClientRequestException e) { } catch (ClientRequestException e) {
dealClientRequestException(resultDto, e);
}
return resultDto;
}
private void dealClientRequestException(ResultDto resultDto, ClientRequestException e) {
resultDto.setStatus(-1); resultDto.setStatus(-1);
Map<String, Object> statusInfo = new HashMap<>(); Map<String, Object> statusInfo = new HashMap<>();
statusInfo.put("code", e.getErrorCode()); statusInfo.put("code", e.getErrorCode());
statusInfo.put("message", e.getMessage()); statusInfo.put("message", e.getMessage());
resultDto.setStatusInfo(statusInfo); resultDto.setStatusInfo(statusInfo);
} }
return resultDto;
}
} }
package com.edgec.browserbackend.browser.domain; package com.edgec.browserbackend.browser.domain;
import com.edgec.browserbackend.browser.dto.Interval;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects;
@Document(collection = "ipresource") @Document(collection = "ipresource")
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class IpResource implements Serializable { public class IpResource implements Serializable {
@Id @Id
private String id; private String id;
private String addr; private String addr;
...@@ -311,4 +311,22 @@ public class IpResource implements Serializable { ...@@ -311,4 +311,22 @@ public class IpResource implements Serializable {
public void setShopId(String shopId) { public void setShopId(String shopId) {
this.shopId = shopId; this.shopId = shopId;
} }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof IpResource)) return false;
IpResource that = (IpResource) o;
return Objects.equals(getId(), that.getId());
}
@Override
public int hashCode() {
return Objects.hash(getId());
}
} }
package com.edgec.browserbackend.browser.dto; package com.edgec.browserbackend.browser.dto;
import com.alibaba.fastjson.JSONObject;
import com.edgec.browserbackend.browser.domain.IpResource;
import com.edgec.browserbackend.browser.domain.Shop; import com.edgec.browserbackend.browser.domain.Shop;
import com.edgec.browserbackend.browser.domain.TransferStatus; import com.edgec.browserbackend.browser.domain.TransferStatus;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.google.gson.JsonObject;
import org.elasticsearch.client.license.LicensesStatus;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class ShopResultDto { public class ShopResultDto {
......
package com.edgec.browserbackend.browser.repository; package com.edgec.browserbackend.browser.repository;
import com.edgec.browserbackend.browser.domain.IpResource; import com.edgec.browserbackend.browser.domain.IpResource;
import com.edgec.browserbackend.browser.domain.IpType;
import com.edgec.browserbackend.browser.domain.Shop;
import com.google.gson.internal.$Gson$Preconditions;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.MongoRepository;
...@@ -13,27 +9,45 @@ import java.util.List; ...@@ -13,27 +9,45 @@ import java.util.List;
public interface IpResourceRepository extends MongoRepository<IpResource, String>, IpResourceRepositoryCustom { public interface IpResourceRepository extends MongoRepository<IpResource, String>, IpResourceRepositoryCustom {
IpResource findByAddr(String addr); IpResource findByAddr(String addr);
IpResource findByAddrAndIsDeletedAndIsLocked(String addr, boolean isDeleted, boolean isLocked); IpResource findByAddrAndIsDeletedAndIsLocked(String addr, boolean isDeleted, boolean isLocked);
IpResource findByAddrAndIsDeleted(String addr, boolean isDeleted); IpResource findByAddrAndIsDeleted(String addr, boolean isDeleted);
IpResource findByIdAndIsDeletedAndIsLocked(String id, boolean isDeleted, boolean isLocked); IpResource findByIdAndIsDeletedAndIsLocked(String id, boolean isDeleted, boolean isLocked);
IpResource findByIdAndIsDeleted(String id, boolean isDeleted); IpResource findByIdAndIsDeleted(String id, boolean isDeleted);
Page<IpResource> findByIdInAndIsDeletedOrderByPurchasedTimeDesc(List<String> ipIds, boolean isDeleted, Pageable pageable); Page<IpResource> findByIdInAndIsDeletedOrderByPurchasedTimeDesc(List<String> ipIds, boolean isDeleted, Pageable pageable);
List<IpResource> findByOwnerAndIsDeletedAndBind(String owner, boolean isDeleted, boolean bind); List<IpResource> findByOwnerAndIsDeletedAndBind(String owner, boolean isDeleted, boolean bind);
List<IpResource> findByOwnerAndStatusIsNotInAndIsDeletedAndBind(String owner, List<Integer> status, boolean isDeleted, boolean bind); List<IpResource> findByOwnerAndStatusIsNotInAndIsDeletedAndBind(String owner, List<Integer> status, boolean isDeleted, boolean bind);
List<IpResource> findByOwnerAndStatusInAndIsDeletedAndBind(String owner, List<Integer> status, boolean isDeleted, boolean bind);
List<IpResource> findByOwnerAndStatusAndIsDeletedAndBind(String owner, int status, boolean isDeleted, boolean bind); List<IpResource> findByOwnerAndStatusAndIsDeletedAndBind(String owner, int status, boolean isDeleted, boolean bind);
List<IpResource> findByOwnerInAndIsDeletedAndBind(List<String> owner, boolean isDeleted, boolean bind); List<IpResource> findByOwnerInAndIsDeletedAndBind(List<String> owner, boolean isDeleted, boolean bind);
List<IpResource> findByOwnerInAndStatusIsNotInAndIsDeletedAndBind(List<String> owner, List<Integer> status, boolean isDeleted, boolean bind); List<IpResource> findByOwnerInAndStatusIsNotInAndIsDeletedAndBind(List<String> owner, List<Integer> status, boolean isDeleted, boolean bind);
List<IpResource> findByOwnerInAndStatusInAndIsDeletedAndBind(List<String> owner, List<Integer> status, boolean isDeleted, boolean bind);
List<IpResource> findByOwnerInAndStatusAndIsDeletedAndBind(List<String> owner, int status, boolean isDeleted, boolean bind); List<IpResource> findByOwnerInAndStatusAndIsDeletedAndBind(List<String> owner, int status, boolean isDeleted, boolean bind);
Page<IpResource> findByIsDeletedAndIdInAndAddrLikeOrderByPurchasedTimeDesc(boolean isDeleted, List<String> ipIds, String addr, Pageable pageable); Page<IpResource> findByIsDeletedAndIdInAndAddrLikeOrderByPurchasedTimeDesc(boolean isDeleted, List<String> ipIds, String addr, Pageable pageable);
Page<IpResource> findByIsDeletedAndIdInAndVendorCnLikeOrderByPurchasedTimeDesc(boolean isDeleted, List<String> ipIds, String vendorCn, Pageable pageable); Page<IpResource> findByIsDeletedAndIdInAndVendorCnLikeOrderByPurchasedTimeDesc(boolean isDeleted, List<String> ipIds, String vendorCn, Pageable pageable);
Page<IpResource> findByIsDeletedAndIdInAndVendorLikeOrderByPurchasedTimeDesc(boolean isDeleted, List<String> ipIds, String vendor, Pageable pageable); Page<IpResource> findByIsDeletedAndIdInAndVendorLikeOrderByPurchasedTimeDesc(boolean isDeleted, List<String> ipIds, String vendor, Pageable pageable);
Page<IpResource> findByIsDeletedAndIdInAndRegionCnLikeOrderByPurchasedTimeDesc(boolean isDeleted, List<String> ipIds, String region, Pageable pageable); Page<IpResource> findByIsDeletedAndIdInAndRegionCnLikeOrderByPurchasedTimeDesc(boolean isDeleted, List<String> ipIds, String region, Pageable pageable);
List<IpResource> findByIsDeleted(boolean isDeleted); List<IpResource> findByIsDeleted(boolean isDeleted);
List<IpResource> findByOwnerInAndSpecialLine(List<String> owners, boolean specialLine); List<IpResource> findByOwnerInAndSpecialLine(List<String> owners, boolean specialLine);
List<IpResource> findBySpecialLineAndIsDeleted(boolean specialLine, boolean isDeleted); List<IpResource> findBySpecialLineAndIsDeleted(boolean specialLine, boolean isDeleted);
List<IpResource> findByRegionInAndIsDeleted(List<String> regions, boolean isDeleted); List<IpResource> findByRegionInAndIsDeleted(List<String> regions, boolean isDeleted);
...@@ -49,6 +63,8 @@ public interface IpResourceRepository extends MongoRepository<IpResource, String ...@@ -49,6 +63,8 @@ public interface IpResourceRepository extends MongoRepository<IpResource, String
long countAllByIsDeletedAndValidTimeGreaterThan(boolean isDeleted, long time); long countAllByIsDeletedAndValidTimeGreaterThan(boolean isDeleted, long time);
long countAllByOwnerAndIsDeletedAndValidTimeGreaterThan(String username, boolean isDeleted, long time); long countAllByOwnerAndIsDeletedAndValidTimeGreaterThan(String username, boolean isDeleted, long time);
long countAllByOwnerInAndIsDeletedAndValidTimeGreaterThan(List<String> username, boolean isDeleted, long time); long countAllByOwnerInAndIsDeletedAndValidTimeGreaterThan(List<String> username, boolean isDeleted, long time);
long countAllByOwner(String username); long countAllByOwner(String username);
} }
...@@ -19,6 +19,8 @@ public interface IpResourceRepositoryCustom { ...@@ -19,6 +19,8 @@ public interface IpResourceRepositoryCustom {
List<IpResource> sampleTasks(List<Integer> status); List<IpResource> sampleTasks(List<Integer> status);
List<IpResource> findIds();
boolean addShopId(String ipId, String shopId); boolean addShopId(String ipId, String shopId);
boolean deleteShopId(String ipId, String shopId, BindHistory bindHistory); boolean deleteShopId(String ipId, String shopId, BindHistory bindHistory);
......
...@@ -3,17 +3,13 @@ package com.edgec.browserbackend.browser.repository; ...@@ -3,17 +3,13 @@ package com.edgec.browserbackend.browser.repository;
import com.edgec.browserbackend.browser.domain.BindHistory; import com.edgec.browserbackend.browser.domain.BindHistory;
import com.edgec.browserbackend.browser.domain.IpResource; import com.edgec.browserbackend.browser.domain.IpResource;
import com.edgec.browserbackend.browser.dto.IpResourceUnwindResultDto; import com.edgec.browserbackend.browser.dto.IpResourceUnwindResultDto;
import com.edgec.browserbackend.common.utils.JsonUtils;
import com.mongodb.client.result.UpdateResult; import com.mongodb.client.result.UpdateResult;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document; import org.bson.Document;
import org.elasticsearch.common.recycler.Recycler;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.*; import org.springframework.data.mongodb.core.aggregation.*;
import org.springframework.data.mongodb.core.query.BasicQuery; import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Update; import org.springframework.data.mongodb.core.query.Update;
import java.time.Instant; import java.time.Instant;
...@@ -101,7 +97,7 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto ...@@ -101,7 +97,7 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto
MatchOperation match = Aggregation.match(matchCriteria); MatchOperation match = Aggregation.match(matchCriteria);
SampleOperation sample = Aggregation.sample(20); SampleOperation sample = Aggregation.sample(100);
AggregationResults<IpResource> results = mongoTemplate.aggregate(Aggregation.newAggregation(match, sample), IpResource.class, IpResource.class); AggregationResults<IpResource> results = mongoTemplate.aggregate(Aggregation.newAggregation(match, sample), IpResource.class, IpResource.class);
List<IpResource> mappedResults = results.getMappedResults(); List<IpResource> mappedResults = results.getMappedResults();
...@@ -111,7 +107,7 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto ...@@ -111,7 +107,7 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto
@Override @Override
public List<IpResource> sampleTasks(List<Integer> status) { public List<IpResource> sampleTasks(List<Integer> status) {
Criteria matchCriteria = new Criteria(); Criteria matchCriteria = new Criteria();
matchCriteria.orOperator(where("status").in(status).and("isLocked").is(false).and("validTime").gt(Instant.now().toEpochMilli()).and("isDeleted").is(false).and("healthLockTimestamp").lte(Instant.now().minusSeconds(60*30).toEpochMilli()), matchCriteria.orOperator(where("status").in(status).and("isLocked").is(false).and("validTime").gt(Instant.now().toEpochMilli()).and("isDeleted").is(false).and("healthLockTimestamp").lte(Instant.now().minusSeconds(60 * 30).toEpochMilli()),
where("status").in(status).and("isLocked").is(true).and("healthLockTimestamp").lte(Instant.now().minusSeconds(600).toEpochMilli()).and("isDeleted").is(false)); where("status").in(status).and("isLocked").is(true).and("healthLockTimestamp").lte(Instant.now().minusSeconds(600).toEpochMilli()).and("isDeleted").is(false));
MatchOperation match = Aggregation.match(matchCriteria); MatchOperation match = Aggregation.match(matchCriteria);
...@@ -194,7 +190,7 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto ...@@ -194,7 +190,7 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto
if (ipResourceUnwindResultDtos.isEmpty()) { if (ipResourceUnwindResultDtos.isEmpty()) {
return new ArrayList<>(); return new ArrayList<>();
} }
HashMap<String ,IpResource> ipResourceHashMap = new HashMap<>(); HashMap<String, IpResource> ipResourceHashMap = new HashMap<>();
ipResourceUnwindResultDtos.forEach(x -> { ipResourceUnwindResultDtos.forEach(x -> {
if (ipResourceHashMap.containsKey(x.getId())) { if (ipResourceHashMap.containsKey(x.getId())) {
ipResourceHashMap.get(x.getId()).getShopIds().add(x.getShopId()); ipResourceHashMap.get(x.getId()).getShopIds().add(x.getShopId());
...@@ -203,8 +199,8 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto ...@@ -203,8 +199,8 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto
} }
}); });
List<IpResource> result = new ArrayList<>(); List<IpResource> result = new ArrayList<>();
Set<Map.Entry<String,IpResource>> entry = ipResourceHashMap.entrySet(); Set<Map.Entry<String, IpResource>> entry = ipResourceHashMap.entrySet();
for(Map.Entry<String,IpResource> e:entry){ for (Map.Entry<String, IpResource> e : entry) {
result.add(e.getValue()); result.add(e.getValue());
} }
return result; return result;
...@@ -220,7 +216,7 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto ...@@ -220,7 +216,7 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto
if (ipResourceUnwindResultDtos.isEmpty()) { if (ipResourceUnwindResultDtos.isEmpty()) {
return new ArrayList<>(); return new ArrayList<>();
} }
HashMap<String ,IpResource> ipResourceHashMap = new HashMap<>(); HashMap<String, IpResource> ipResourceHashMap = new HashMap<>();
ipResourceUnwindResultDtos.forEach(x -> { ipResourceUnwindResultDtos.forEach(x -> {
if (ipResourceHashMap.containsKey(x.getId())) { if (ipResourceHashMap.containsKey(x.getId())) {
ipResourceHashMap.get(x.getId()).getShopIds().add(x.getShopId()); ipResourceHashMap.get(x.getId()).getShopIds().add(x.getShopId());
...@@ -229,8 +225,8 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto ...@@ -229,8 +225,8 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto
} }
}); });
List<IpResource> result = new ArrayList<>(); List<IpResource> result = new ArrayList<>();
Set<Map.Entry<String,IpResource>> entry = ipResourceHashMap.entrySet(); Set<Map.Entry<String, IpResource>> entry = ipResourceHashMap.entrySet();
for(Map.Entry<String,IpResource> e:entry){ for (Map.Entry<String, IpResource> e : entry) {
result.add(e.getValue()); result.add(e.getValue());
} }
return result; return result;
...@@ -246,7 +242,7 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto ...@@ -246,7 +242,7 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto
if (ipResourceUnwindResultDtos.isEmpty()) { if (ipResourceUnwindResultDtos.isEmpty()) {
return new ArrayList<>(); return new ArrayList<>();
} }
HashMap<String ,IpResource> ipResourceHashMap = new HashMap<>(); HashMap<String, IpResource> ipResourceHashMap = new HashMap<>();
ipResourceUnwindResultDtos.forEach(x -> { ipResourceUnwindResultDtos.forEach(x -> {
if (ipResourceHashMap.containsKey(x.getId())) { if (ipResourceHashMap.containsKey(x.getId())) {
ipResourceHashMap.get(x.getId()).getShopIds().add(x.getShopId()); ipResourceHashMap.get(x.getId()).getShopIds().add(x.getShopId());
...@@ -255,10 +251,19 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto ...@@ -255,10 +251,19 @@ public class IpResourceRepositoryCustomImpl implements IpResourceRepositoryCusto
} }
}); });
List<IpResource> result = new ArrayList<>(); List<IpResource> result = new ArrayList<>();
Set<Map.Entry<String,IpResource>> entry = ipResourceHashMap.entrySet(); Set<Map.Entry<String, IpResource>> entry = ipResourceHashMap.entrySet();
for(Map.Entry<String,IpResource> e:entry){ for (Map.Entry<String, IpResource> e : entry) {
result.add(e.getValue()); result.add(e.getValue());
} }
return result; return result;
} }
@Override
public List<IpResource> findIds() {
BasicQuery basicQuery = new BasicQuery(new Document());
basicQuery.fields().include("id");
return mongoTemplate.find(basicQuery, IpResource.class);
}
} }
package com.edgec.browserbackend.browser.repository; package com.edgec.browserbackend.browser.repository;
import com.edgec.browserbackend.account.repository.FileRepository;
import com.edgec.browserbackend.account.repository.FileRepositoryImpl; import com.edgec.browserbackend.account.repository.FileRepositoryImpl;
import com.edgec.browserbackend.browser.domain.ProxyConfig; import com.edgec.browserbackend.browser.domain.ProxyConfig;
import com.edgec.browserbackend.browser.domain.UserShop;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult; import com.mongodb.client.result.UpdateResult;
import org.bson.Document; import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery; import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Update; import org.springframework.data.mongodb.core.query.Update;
import java.io.File; import java.io.File;
import static org.springframework.data.mongodb.core.query.Criteria.where;
public class ProxyConfigRepositoryCustomImpl implements ProxyConfigRepositoryCustom { public class ProxyConfigRepositoryCustomImpl implements ProxyConfigRepositoryCustom {
@Autowired @Autowired
...@@ -33,10 +27,8 @@ public class ProxyConfigRepositoryCustomImpl implements ProxyConfigRepositoryCus ...@@ -33,10 +27,8 @@ public class ProxyConfigRepositoryCustomImpl implements ProxyConfigRepositoryCus
Update update = new Update(); Update update = new Update();
update.set("configFileId", fileId).set("timestamp", time); update.set("configFileId", fileId).set("timestamp", time);
UpdateResult operation = mongoTemplate.upsert(basicQuery, update, ProxyConfig.class); UpdateResult operation = mongoTemplate.upsert(basicQuery, update, ProxyConfig.class);
if (operation.getModifiedCount() < 1)
return false; return operation.getModifiedCount() >= 1;
else
return true;
} }
} }
...@@ -36,39 +36,44 @@ public class HistoryServiceImpl implements HistoryService { ...@@ -36,39 +36,44 @@ public class HistoryServiceImpl implements HistoryService {
@Override @Override
public void addLoginHistory(String username, LoginHistoryDto loginHistoryDto) { public void addLoginHistory(String username, LoginHistoryDto loginHistoryDto) {
Account account = accountRepository.findById(username).orElse(null); Account account = accountRepository.findById(username)
if (account == null) .orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
int num = loginHistoryRepository.countByUsername(username); int num = loginHistoryRepository.countByUsername(username);
if (num > 10000) if (num > 10000) {
loginHistoryRepository.delete(loginHistoryRepository.findFirstByUsername(username)); loginHistoryRepository.delete(loginHistoryRepository.findFirstByUsername(username));
}
LoginHistory loginHistory = new LoginHistory(loginHistoryDto); LoginHistory loginHistory = new LoginHistory(loginHistoryDto);
loginHistory.setLoginTime(Instant.now().toEpochMilli()); loginHistory.setLoginTime(Instant.now().toEpochMilli());
loginHistory.setUsername(username); loginHistory.setUsername(username);
if (account.getParent() == null) if (account.getParent() == null) {
loginHistory.setAdministrator(username); loginHistory.setAdministrator(username);
else } else {
loginHistory.setAdministrator(account.getParent()); loginHistory.setAdministrator(account.getParent());
}
loginHistory.setNickname(account.getNickname()); loginHistory.setNickname(account.getNickname());
loginHistoryRepository.save(loginHistory); loginHistoryRepository.save(loginHistory);
} }
@Override @Override
public void addOperationHistory(String username, OperationHistoryDto operationHistoryDto) { public void addOperationHistory(String username, OperationHistoryDto operationHistoryDto) {
Account account = accountRepository.findById(username).orElse(null); Account account = accountRepository.findById(username).orElseThrow(() -> new ClientRequestException(AccountErrorCode.NAMENOTEXIST));
if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
int num = operationHistoryRepository.countByUsername(username); int num = operationHistoryRepository.countByUsername(username);
if (num > 10000) if (num > 10000) {
operationHistoryRepository.delete(operationHistoryRepository.findFirstByUsername(username)); operationHistoryRepository.delete(operationHistoryRepository.findFirstByUsername(username));
}
OperationHistory operationHistory = new OperationHistory(operationHistoryDto); OperationHistory operationHistory = new OperationHistory(operationHistoryDto);
operationHistory.setOperationTime(Instant.now().toEpochMilli()); operationHistory.setOperationTime(Instant.now().toEpochMilli());
operationHistory.setUsername(username); operationHistory.setUsername(username);
operationHistory.setNickname(account.getNickname()); operationHistory.setNickname(account.getNickname());
if (account.getParent() == null) if (account.getParent() == null) {
operationHistory.setAdministrator(username); operationHistory.setAdministrator(username);
else } else {
operationHistory.setAdministrator(account.getParent()); operationHistory.setAdministrator(account.getParent());
}
operationHistoryRepository.save(operationHistory); operationHistoryRepository.save(operationHistory);
} }
...@@ -99,7 +104,7 @@ public class HistoryServiceImpl implements HistoryService { ...@@ -99,7 +104,7 @@ public class HistoryServiceImpl implements HistoryService {
PageInfo pageInfo = new PageInfo(); PageInfo pageInfo = new PageInfo();
pageInfo.setCurrentPage(loginHistoryPage.getNumber()); pageInfo.setCurrentPage(loginHistoryPage.getNumber());
pageInfo.setTotalPages(loginHistoryPage.getTotalPages()); pageInfo.setTotalPages(loginHistoryPage.getTotalPages());
pageInfo.setTotalItems((int)loginHistoryPage.getTotalElements()); pageInfo.setTotalItems((int) loginHistoryPage.getTotalElements());
historyPageResultDto.setHistoryPage(pageInfo); historyPageResultDto.setHistoryPage(pageInfo);
return historyPageResultDto; return historyPageResultDto;
} }
...@@ -131,7 +136,7 @@ public class HistoryServiceImpl implements HistoryService { ...@@ -131,7 +136,7 @@ public class HistoryServiceImpl implements HistoryService {
PageInfo pageInfo = new PageInfo(); PageInfo pageInfo = new PageInfo();
pageInfo.setCurrentPage(operationHistories.getNumber()); pageInfo.setCurrentPage(operationHistories.getNumber());
pageInfo.setTotalPages(operationHistories.getTotalPages()); pageInfo.setTotalPages(operationHistories.getTotalPages());
pageInfo.setTotalItems((int)operationHistories.getTotalElements()); pageInfo.setTotalItems((int) operationHistories.getTotalElements());
historyPageResultDto.setHistoryPage(pageInfo); historyPageResultDto.setHistoryPage(pageInfo);
return historyPageResultDto; return historyPageResultDto;
} }
......
...@@ -43,18 +43,22 @@ public class IpAndShopServiceImpl implements IpAndShopService { ...@@ -43,18 +43,22 @@ public class IpAndShopServiceImpl implements IpAndShopService {
@Override @Override
public void bindShop(String username, ShopRequestDto shopRequestDto) { public void bindShop(String username, ShopRequestDto shopRequestDto) {
String shopId = shopRequestDto.getShopId(); // 1. 根据id 来获取账户
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username);
if (account == null) { if (account == null) {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
} }
String shopId = shopRequestDto.getShopId();
// 2.获取当前账户下指定的商铺
UserShop userShop = userShopRepository.findByUsernameAndShopId(username, shopId); UserShop userShop = userShopRepository.findByUsernameAndShopId(username, shopId);
if (account.getPermission() < 4 || userShop == null) { if (account.getPermission() < 4 || userShop == null) {
throw new ClientRequestException(AccountErrorCode.NOPERMISSION); throw new ClientRequestException(AccountErrorCode.NOPERMISSION);
} }
Shop shop = shopRepository.findById(shopId).orElse(null); // 3.根据shopId获取商铺的详情
if (shop == null) Shop shop = shopRepository.findById(shopId).orElseThrow(() -> new ClientRequestException(BrowserErrorCode.SHOPNOTEXIST));
throw new ClientRequestException(BrowserErrorCode.SHOPNOTEXIST);
// 4.根据传入的id或者addr查询是否有指定的 ip 资源
IpResource ipResource = null; IpResource ipResource = null;
if (StringUtils.isNotBlank(shopRequestDto.getIpAddr())) { if (StringUtils.isNotBlank(shopRequestDto.getIpAddr())) {
ipResource = ipResourceRepository.findByAddrAndIsDeleted(shopRequestDto.getIpAddr(), false); ipResource = ipResourceRepository.findByAddrAndIsDeleted(shopRequestDto.getIpAddr(), false);
...@@ -62,17 +66,21 @@ public class IpAndShopServiceImpl implements IpAndShopService { ...@@ -62,17 +66,21 @@ public class IpAndShopServiceImpl implements IpAndShopService {
ipResource = ipResourceRepository.findByIdAndIsDeleted(shopRequestDto.getIpId(), false); ipResource = ipResourceRepository.findByIdAndIsDeleted(shopRequestDto.getIpId(), false);
} }
if (ipResource == null) if (ipResource == null) {
throw new ClientRequestException(BrowserErrorCode.IPNOTEXIST); throw new ClientRequestException(BrowserErrorCode.IPNOTEXIST);
}
// 5.根据shopId来查询指定 isDeleted 为 false 的 ip资源
IpResource bind = ipResourceRepository.findFirstByShopIdsIsAndIsDeleted(shopId, false); IpResource bind = ipResourceRepository.findFirstByShopIdsIsAndIsDeleted(shopId, false);
if (bind != null) { if (bind != null) {
return; throw new ClientRequestException(BrowserErrorCode.SHOP_BINDED);
} }
try { try {
// 6.绑定ip,将shopId添加到ip资源中,且将 bind 状态设置为 true
ipResourceRepository.addShopId(ipResource.getId(), shopId); ipResourceRepository.addShopId(ipResource.getId(), shopId);
} catch (Exception e) { } catch (Exception e) {
logger.error("fail to bind shop and ip", e.getMessage()); logger.error("fail to bind shop and ip", e);
throw new ClientRequestException(BrowserErrorCode.UNKNOWN); throw new ClientRequestException(BrowserErrorCode.UNKNOWN);
} }
} }
......
...@@ -47,33 +47,11 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -47,33 +47,11 @@ public class IpResourceServiceImpl implements IpResourceService {
private static String USERNAME = "fangguanlianbrowser"; private static String USERNAME = "fangguanlianbrowser";
public static List<String> region = Arrays.asList( public static List<String> region = Arrays.asList(
"asiapa", "asiapa", "hongkong", "japan", "s-korea", "us", "malaysia",
"hongkong", "yajiada", "singapore", "australia", "germany", "uk", "brazil",
"japan", "moscow", "canada", "france", "sweden", "s-korea", "india", "meast",
"s-korea", "brazil", "virginia", "ohio", "california", "oregon", "ireland", "london", "ireland"
"us", );
"malaysia",
"yajiada",
"singapore",
"australia",
"germany",
"uk",
"brazil",
"moscow",
"canada",
"france",
"sweden",
"s-korea",
"india",
"meast",
"brazil",
"virginia",
"ohio",
"california",
"oregon",
"ireland",
"london",
"ireland");
private static List<String> port = Arrays.asList("20000", "20001"); private static List<String> port = Arrays.asList("20000", "20001");
...@@ -206,7 +184,7 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -206,7 +184,7 @@ public class IpResourceServiceImpl implements IpResourceService {
String price = vendorPrices.stream() String price = vendorPrices.stream()
.filter(x -> Vendor.valueOf(ipResourceRequestDto.getVendor()).getValue().equals(x.substring(0, x.indexOf("-")))) .filter(x -> Vendor.valueOf(ipResourceRequestDto.getVendor()).getValue().equals(x.substring(0, x.indexOf("-"))))
.map(x -> x.substring(x.lastIndexOf("-") + 1)).collect(Collectors.joining()); .map(x -> x.substring(x.lastIndexOf("-") + 1)).collect(Collectors.joining());
newprice = ipResourceRequestDto.getUnit().equals("week") ? (Integer.valueOf(price)/3) : Integer.valueOf(price); newprice = ipResourceRequestDto.getUnit().equals("week") ? (Integer.valueOf(price) / 3) : Integer.valueOf(price);
} }
IpChargeResultDto ipChargeResultDto = accountService.preChargeByMoney(username, newprice * ipResourceRequestDto.getAmount() * ipResourceRequestDto.getPeriod()); IpChargeResultDto ipChargeResultDto = accountService.preChargeByMoney(username, newprice * ipResourceRequestDto.getAmount() * ipResourceRequestDto.getPeriod());
...@@ -290,7 +268,7 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -290,7 +268,7 @@ public class IpResourceServiceImpl implements IpResourceService {
ipResource.setProxyUsername(ipResource.getAddr()); ipResource.setProxyUsername(ipResource.getAddr());
ipResource.setProxyPassword(genRandom(3, 12)); ipResource.setProxyPassword(genRandom(3, 12));
ipResource.setSpecialLine(true); ipResource.setSpecialLine(true);
ipResource.setHealthLockTimestamp(Instant.now().minusSeconds(60*20).toEpochMilli()); ipResource.setHealthLockTimestamp(Instant.now().minusSeconds(60 * 20).toEpochMilli());
} }
ipResource.setRegionCn(ipResourceRequestDto.getRegionCn()); ipResource.setRegionCn(ipResourceRequestDto.getRegionCn());
ipResource.setProtocol(protocol); ipResource.setProtocol(protocol);
...@@ -322,7 +300,7 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -322,7 +300,7 @@ public class IpResourceServiceImpl implements IpResourceService {
@Override @Override
public IpOperationResultDto renewIp(String username, IpResourceRequestDto ipResourceRequestDto) { public IpOperationResultDto renewIp(String username, IpResourceRequestDto ipResourceRequestDto) {
String URL = (profiles.equals("dev") || profiles.equals("staging"))? TESTURL : CLOUDAMURL; String URL = (profiles.equals("dev") || profiles.equals("staging")) ? TESTURL : CLOUDAMURL;
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username);
if (account == null) if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
...@@ -343,12 +321,13 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -343,12 +321,13 @@ public class IpResourceServiceImpl implements IpResourceService {
else else
prices = priceList.get("自有"); prices = priceList.get("自有");
} }
for(String vendorprice:prices) { for (String vendorprice : prices) {
if (ipResource.getVendor().getValue().equals(vendorprice.substring(0, vendorprice.indexOf("-")))) if (ipResource.getVendor().getValue().equals(vendorprice.substring(0, vendorprice.indexOf("-"))))
totalprice.updateAndGet(v -> new Double( v + Double.valueOf(vendorprice.substring(vendorprice.lastIndexOf("-") + 1)))); totalprice.updateAndGet(v -> new Double(v + Double.valueOf(vendorprice.substring(vendorprice.lastIndexOf("-") + 1))));
} }); }
});
double newprice = ipResourceRequestDto.getUnit().equals("week") ? (int) (totalprice.get()/3) : totalprice.get().intValue(); double newprice = ipResourceRequestDto.getUnit().equals("week") ? (int) (totalprice.get() / 3) : totalprice.get().intValue();
IpChargeResultDto ipChargeResultDto = accountService.preChargeByMoney(username, newprice * ipResourceRequestDto.getPeriod() * ipResourceRequestDto.getAmount()); IpChargeResultDto ipChargeResultDto = accountService.preChargeByMoney(username, newprice * ipResourceRequestDto.getPeriod() * ipResourceRequestDto.getAmount());
if (!ipChargeResultDto.isSuccess()) { if (!ipChargeResultDto.isSuccess()) {
throw new ClientRequestException(AccountErrorCode.NOTENOUGHBALANCE); throw new ClientRequestException(AccountErrorCode.NOTENOUGHBALANCE);
...@@ -386,7 +365,7 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -386,7 +365,7 @@ public class IpResourceServiceImpl implements IpResourceService {
.filter(vendorprice -> ipResource.getVendor().getValue().equals(vendorprice.substring(0, vendorprice.indexOf("-")))) .filter(vendorprice -> ipResource.getVendor().getValue().equals(vendorprice.substring(0, vendorprice.indexOf("-"))))
.map(vendorprice -> vendorprice.substring(vendorprice.lastIndexOf("-") + 1)).collect(Collectors.joining()); .map(vendorprice -> vendorprice.substring(vendorprice.lastIndexOf("-") + 1)).collect(Collectors.joining());
double newprice1 = ipResourceRequestDto.getUnit().equals("week") ? (Integer.valueOf(price)/3) : Integer.valueOf(price); double newprice1 = ipResourceRequestDto.getUnit().equals("week") ? (Integer.valueOf(price) / 3) : Integer.valueOf(price);
IpChargeRequestDto ipChargeRequestDto = buildIpChargeRequestDto(ipResourceRequestDto, 2, ipResourceRequestDto.getPayMethod()); IpChargeRequestDto ipChargeRequestDto = buildIpChargeRequestDto(ipResourceRequestDto, 2, ipResourceRequestDto.getPayMethod());
accountService.chargeByMoney(username, newprice1 * ipResourceRequestDto.getPeriod() * ipResourceRequestDto.getAmount(), ipChargeRequestDto); accountService.chargeByMoney(username, newprice1 * ipResourceRequestDto.getPeriod() * ipResourceRequestDto.getAmount(), ipChargeRequestDto);
...@@ -440,7 +419,7 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -440,7 +419,7 @@ public class IpResourceServiceImpl implements IpResourceService {
@Override @Override
public IpOperationResultDto deleteIp(String username, IpResourceRequestDto ipResourceRequestDto) { public IpOperationResultDto deleteIp(String username, IpResourceRequestDto ipResourceRequestDto) {
String URL = (profiles.equals("dev") || profiles.equals("staging"))? TESTURL : CLOUDAMURL; String URL = (profiles.equals("dev") || profiles.equals("staging")) ? TESTURL : CLOUDAMURL;
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username);
if (account == null) if (account == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
...@@ -591,23 +570,29 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -591,23 +570,29 @@ public class IpResourceServiceImpl implements IpResourceService {
break; break;
case 4: case 4:
if (!isParent) if (!isParent)
notUsed = ipResourceRepository.findByOwnerAndStatusIsNotInAndIsDeletedAndBind(username, Arrays.asList(3, 5, 6),false, false); notUsed = ipResourceRepository.findByOwnerAndStatusIsNotInAndIsDeletedAndBind(username, Arrays.asList(3, 5, 6), false, false);
else else
notUsed = ipResourceRepository.findByOwnerInAndStatusIsNotInAndIsDeletedAndBind(children, Arrays.asList(3, 5, 6), false, false); notUsed = ipResourceRepository.findByOwnerInAndStatusIsNotInAndIsDeletedAndBind(children, Arrays.asList(3, 5, 6), false, false);
break; break;
case 5:
// 已分配
ipResources = ipResourceRepository.findShopIdInList(shopIds, false);
if (!isParent)
notUsed = ipResourceRepository.findByOwnerAndStatusInAndIsDeletedAndBind(username, Arrays.asList(0, 2, 4, 8), false, false);
else
notUsed = ipResourceRepository.findByOwnerInAndStatusInAndIsDeletedAndBind(children, Arrays.asList(0, 2, 4, 8), false, false);
break;
} }
if (notUsed != null) if (notUsed != null)
ipResources.addAll(notUsed); ipResources.addAll(notUsed);
List<IpResourceDto> ipResourceDtos = new ArrayList<>(); List<IpResourceDto> ipResourceDtos = new ArrayList<>();
List<String> allIpIds = ipResources.stream().map(x -> x.getId()).collect(Collectors.toList()); List<String> allIpIds = ipResources.stream().distinct().map(x -> x.getId()).collect(Collectors.toList());
Page<IpResource> ipResources1 = null; Page<IpResource> ipResources1 = null;
if (ipFilterDto != null && StringUtils.isNotBlank(ipFilterDto.getRegion())) { if (ipFilterDto != null && StringUtils.isNotBlank(ipFilterDto.getRegion())) {
ipResources1 = ipResourceRepository.findByIsDeletedAndIdInAndRegionCnLikeOrderByPurchasedTimeDesc(false, allIpIds, ipFilterDto.getRegion(), pageable); ipResources1 = ipResourceRepository.findByIsDeletedAndIdInAndRegionCnLikeOrderByPurchasedTimeDesc(false, allIpIds, ipFilterDto.getRegion(), pageable);
} } else if (ipFilterDto != null && StringUtils.isNotBlank(ipFilterDto.getAddr())) {
else if (ipFilterDto != null && StringUtils.isNotBlank(ipFilterDto.getAddr())) {
ipResources1 = ipResourceRepository.findByIsDeletedAndIdInAndAddrLikeOrderByPurchasedTimeDesc(false, allIpIds, ipFilterDto.getAddr(), pageable); ipResources1 = ipResourceRepository.findByIsDeletedAndIdInAndAddrLikeOrderByPurchasedTimeDesc(false, allIpIds, ipFilterDto.getAddr(), pageable);
} } else if (ipFilterDto != null && StringUtils.isNotBlank(ipFilterDto.getVendor())) {
else if (ipFilterDto != null && StringUtils.isNotBlank(ipFilterDto.getVendor())) {
ipResources1 = ipResourceRepository.findByIsDeletedAndIdInAndVendorCnLikeOrderByPurchasedTimeDesc(false, allIpIds, ipFilterDto.getVendor(), pageable); ipResources1 = ipResourceRepository.findByIsDeletedAndIdInAndVendorCnLikeOrderByPurchasedTimeDesc(false, allIpIds, ipFilterDto.getVendor(), pageable);
} else { } else {
ipResources1 = ipResourceRepository.findByIdInAndIsDeletedOrderByPurchasedTimeDesc(allIpIds, false, pageable); ipResources1 = ipResourceRepository.findByIdInAndIsDeletedOrderByPurchasedTimeDesc(allIpIds, false, pageable);
...@@ -628,13 +613,11 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -628,13 +613,11 @@ public class IpResourceServiceImpl implements IpResourceService {
if (StringUtils.isNotBlank(x.getAddr())) { if (StringUtils.isNotBlank(x.getAddr())) {
if (x.getLockTimestamp() >= Instant.now().minusSeconds(120).toEpochMilli() && x.getIpType() == IpType.VENDOR && (x.getStatus() == 0 || x.getStatus() == 2)) { if (x.getLockTimestamp() >= Instant.now().minusSeconds(120).toEpochMilli() && x.getIpType() == IpType.VENDOR && (x.getStatus() == 0 || x.getStatus() == 2)) {
x.setStatus(3); x.setStatus(3);
} } else if (x.getValidTime() <= Instant.now().plusSeconds(60 * 60 * 24 * 7).toEpochMilli() && x.getValidTime() > Instant.now().toEpochMilli()) {
else if (x.getValidTime() <= Instant.now().plusSeconds(60*60*24*7).toEpochMilli() && x.getValidTime() >Instant.now().toEpochMilli()) {
if (x.getStatus() != 5 && x.getStatus() != 3 && x.getStatus() != 6) { if (x.getStatus() != 5 && x.getStatus() != 3 && x.getStatus() != 6) {
ipResourceRepository.updateStatus(x.getId(), 2); ipResourceRepository.updateStatus(x.getId(), 2);
} }
} } else if (x.getValidTime() <= Instant.now().minusSeconds(60 * 60 * 24 * 7).toEpochMilli() && x.getStatus() != 3 && x.getStatus() != 6) {
else if (x.getValidTime() <= Instant.now().minusSeconds(60*60*24*7).toEpochMilli() && x.getStatus() != 3 && x.getStatus() != 6) {
if (x.getIpType() == IpType.VENDOR) { if (x.getIpType() == IpType.VENDOR) {
IpResourceRequestDto ipResourceRequestDto = new IpResourceRequestDto(); IpResourceRequestDto ipResourceRequestDto = new IpResourceRequestDto();
ipResourceRequestDto.setAddr(Arrays.asList(x.getAddr())); ipResourceRequestDto.setAddr(Arrays.asList(x.getAddr()));
...@@ -645,19 +628,17 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -645,19 +628,17 @@ public class IpResourceServiceImpl implements IpResourceService {
deleteIp(username, ipResourceRequestDto); deleteIp(username, ipResourceRequestDto);
} }
return; return;
} } else if (x.getValidTime() <= Instant.now().toEpochMilli() && x.getStatus() != 3 && x.getStatus() != 6) {
else if (x.getValidTime() <= Instant.now().toEpochMilli() && x.getStatus() != 3 && x.getStatus() != 6) {
ipResourceRepository.updateStatus(x.getId(), 1); ipResourceRepository.updateStatus(x.getId(), 1);
} } else {
else {
if ((x.getStatus() == 0 || x.getStatus() == 1 || x.getStatus() == 2) && !x.getVendor().equals(Vendor.local)) { if ((x.getStatus() == 0 || x.getStatus() == 1 || x.getStatus() == 2) && !x.getVendor().equals(Vendor.local)) {
ipResourceRepository.updateStatus(x.getId(), 0); ipResourceRepository.updateStatus(x.getId(), 0);
} else if (x.getIpType().equals(IpType.LOCAL) && (x.getStatus() == 1 || x.getStatus() == 2) && x.getAddr().equals("本地Ip未使用") ) { } else if (x.getIpType().equals(IpType.LOCAL) && (x.getStatus() == 1 || x.getStatus() == 2) && x.getAddr().equals("本地Ip未使用")) {
ipResourceRepository.updateStatus(x.getId(), 4); ipResourceRepository.updateStatus(x.getId(), 4);
} }
} }
} }
if (x.getStatus() == 6 || (x.isSpecialLine() && x.getPurchasedTime() > (Instant.now().toEpochMilli() - 12*60*1000))) if (x.getStatus() == 6 || (x.isSpecialLine() && x.getPurchasedTime() > (Instant.now().toEpochMilli() - 12 * 60 * 1000)))
x.setStatus(3); x.setStatus(3);
if (x.getStatus() == 3) { if (x.getStatus() == 3) {
x.setAddr(""); x.setAddr("");
...@@ -717,7 +698,7 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -717,7 +698,7 @@ public class IpResourceServiceImpl implements IpResourceService {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
IpSummary ipSummary = new IpSummary(); IpSummary ipSummary = new IpSummary();
List<String> shopIds = userShopRepository.findByUsername(username).stream().map(x -> x.getShopId()).collect(Collectors.toList()); List<String> shopIds = userShopRepository.findByUsername(username).stream().map(x -> x.getShopId()).collect(Collectors.toList());
List<String> used = ipResourceRepository.findShopIdInList(shopIds,false).stream().map(x -> x.getId()).collect(Collectors.toList()); List<String> used = ipResourceRepository.findShopIdInList(shopIds, false).stream().map(x -> x.getId()).collect(Collectors.toList());
List<String> unbind = ipResourceRepository.findByOwnerAndIsDeletedAndBind(username, false, false).stream().map(x -> x.getId()).collect(Collectors.toList()); List<String> unbind = ipResourceRepository.findByOwnerAndIsDeletedAndBind(username, false, false).stream().map(x -> x.getId()).collect(Collectors.toList());
ipSummary.setUnbind(unbind.size()); ipSummary.setUnbind(unbind.size());
unbind.addAll(used); unbind.addAll(used);
...@@ -731,24 +712,41 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -731,24 +712,41 @@ public class IpResourceServiceImpl implements IpResourceService {
@Override @Override
public void updateIp(String username, IpResourceUpdateDto ipResourceUpdateDto) { public void updateIp(String username, IpResourceUpdateDto ipResourceUpdateDto) {
// 1. 根据id 来获取账户
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username);
if (account == null) if (account == null) {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
if (account.getPermission() < 8) }
/// 这个地方本来是8,现在由于更新ip失败,改为和绑定店铺时一样的 4
if (account.getPermission() < 4) {
throw new ClientRequestException(AccountErrorCode.NOPERMISSION); throw new ClientRequestException(AccountErrorCode.NOPERMISSION);
}
// 2.根据传入的id查询是否有指定的 isDelete 为 false的 ip 资源
IpResource ipResource = ipResourceRepository.findByIdAndIsDeleted(ipResourceUpdateDto.getIpId(), false); IpResource ipResource = ipResourceRepository.findByIdAndIsDeleted(ipResourceUpdateDto.getIpId(), false);
if (ipResource == null) if (ipResource == null) {
throw new ClientRequestException(BrowserErrorCode.IPNOTEXIST); throw new ClientRequestException(BrowserErrorCode.IPNOTEXIST);
}
// 封装 ipResource 部分信息
dealIpResource(ipResourceUpdateDto, ipResource);
// 3.更新ip资源
ipResourceRepository.save(ipResource);
}
private void dealIpResource(IpResourceUpdateDto ipResourceUpdateDto, IpResource ipResource) {
if (StringUtils.isNotBlank(ipResourceUpdateDto.getAddr())) { if (StringUtils.isNotBlank(ipResourceUpdateDto.getAddr())) {
ipResource.setAddr(ipResourceUpdateDto.getAddr()); ipResource.setAddr(ipResourceUpdateDto.getAddr());
} }
if (StringUtils.isNotBlank(ipResource.getRegion()) && region.contains(ipResource.getRegion())) { if (StringUtils.isNotBlank(ipResource.getRegion()) && region.contains(ipResource.getRegion())) {
ipResource.setProxyUsername(ipResource.getAddr()); ipResource.setProxyUsername(ipResource.getAddr());
ipResource.setProxyPassword(genRandom(3, 12)); ipResource.setProxyPassword(genRandom(3, 12));
ipResource.setSpecialLine(true); ipResource.setSpecialLine(true);
} }
ipResource.setStatus(ipResourceUpdateDto.getStatus()); ipResource.setStatus(ipResourceUpdateDto.getStatus());
ipResourceRepository.save(ipResource);
} }
@Override @Override
...@@ -822,7 +820,7 @@ public class IpResourceServiceImpl implements IpResourceService { ...@@ -822,7 +820,7 @@ public class IpResourceServiceImpl implements IpResourceService {
@Override @Override
public void releaseDeletedIp() { public void releaseDeletedIp() {
String URL = (profiles.equals("dev") || profiles.equals("staging"))? TESTURL : CLOUDAMURL; String URL = (profiles.equals("dev") || profiles.equals("staging")) ? TESTURL : CLOUDAMURL;
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = buildGetHeader(); HttpHeaders headers = buildGetHeader();
Map<String, String> params = new HashMap<String, String>(); Map<String, String> params = new HashMap<String, String>();
......
...@@ -106,7 +106,7 @@ public class ShopServiceImpl implements ShopService { ...@@ -106,7 +106,7 @@ public class ShopServiceImpl implements ShopService {
//可以优化 //可以优化
account.setShopCount(account.getShopCount() + 1); account.setShopCount(account.getShopCount() + 1);
accountRepository.save(account); accountRepository.save(account);
}catch (Exception e) { } catch (Exception e) {
throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE); throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE);
} }
return id; return id;
...@@ -170,7 +170,7 @@ public class ShopServiceImpl implements ShopService { ...@@ -170,7 +170,7 @@ public class ShopServiceImpl implements ShopService {
account.setShopCount(account.getShopCount() + 1); account.setShopCount(account.getShopCount() + 1);
accountRepository.save(account); accountRepository.save(account);
ids.add(id); ids.add(id);
}catch (Exception e) { } catch (Exception e) {
logger.error("fail to add shops", e.getMessage()); logger.error("fail to add shops", e.getMessage());
throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE); throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE);
} }
...@@ -197,7 +197,7 @@ public class ShopServiceImpl implements ShopService { ...@@ -197,7 +197,7 @@ public class ShopServiceImpl implements ShopService {
try { try {
shop_old = shop_old.of(shopResultDto); shop_old = shop_old.of(shopResultDto);
shopRepository.save(shop_old); shopRepository.save(shop_old);
}catch (Exception e) { } catch (Exception e) {
logger.error("fail to update", e.getMessage()); logger.error("fail to update", e.getMessage());
throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE); throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE);
} }
...@@ -277,8 +277,7 @@ public class ShopServiceImpl implements ShopService { ...@@ -277,8 +277,7 @@ public class ShopServiceImpl implements ShopService {
if (accounts == null || accounts.size() != users.size()) if (accounts == null || accounts.size() != users.size())
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
for (Account ac : accounts) { for (Account ac : accounts) {
if (ac.getParent() == null || !ac.getParent().equals(username)) if (ac.getParent() == null || !ac.getParent().equals(username)) {
{
throw new ClientRequestException(AccountErrorCode.NOPERMISSION); throw new ClientRequestException(AccountErrorCode.NOPERMISSION);
} }
} }
...@@ -297,7 +296,7 @@ public class ShopServiceImpl implements ShopService { ...@@ -297,7 +296,7 @@ public class ShopServiceImpl implements ShopService {
throw new ClientRequestException(BrowserErrorCode.UNKNOWN); throw new ClientRequestException(BrowserErrorCode.UNKNOWN);
} }
} else { } else {
shops.stream().forEach(shop -> { shops.forEach(shop -> {
try { try {
for (Account account1 : accounts) { for (Account account1 : accounts) {
UserShop userShop1 = userShopRepository.findByUsernameAndShopId(account1.getName(), shop.getShopId()); UserShop userShop1 = userShopRepository.findByUsernameAndShopId(account1.getName(), shop.getShopId());
...@@ -336,44 +335,43 @@ public class ShopServiceImpl implements ShopService { ...@@ -336,44 +335,43 @@ public class ShopServiceImpl implements ShopService {
if (ipResource.isSpecialLine()) { if (ipResource.isSpecialLine()) {
SpecialLine specialLine = specialLineRepository.findAll().get(0); SpecialLine specialLine = specialLineRepository.findAll().get(0);
shopResultDto = ShopResultDto.of(shop, group, new IpResourceDto(ipResource, null, false, specialLine)); shopResultDto = ShopResultDto.of(shop, group, new IpResourceDto(ipResource, null, false, specialLine));
} } else
else
shopResultDto = ShopResultDto.of(shop, group, new IpResourceDto(ipResource, null, false)); shopResultDto = ShopResultDto.of(shop, group, new IpResourceDto(ipResource, null, false));
return shopResultDto; return shopResultDto;
} }
@Override @Override
public ShopPageResultDto getShopList(String username, String groupId, int page, int amount, ShopFilterDto shopFilterDto) { public ShopPageResultDto getShopList(String username, String groupId, int pageNum, int amount, ShopFilterDto shopFilterDto) {
if (amount > 100)
amount = 100;
Pageable pageable = PageRequest.of(page, amount);
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username);
if (account == null) { if (account == null) {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
} }
Group group = null; Group group = null;
if (groupId != null) if (groupId != null) {
group = groupRepository.findById(groupId).orElse(null); group = groupRepository.findById(groupId).orElse(null);
if (group == null) }
if (group == null) {
throw new ClientRequestException(BrowserErrorCode.GROUPNOTEXIST); throw new ClientRequestException(BrowserErrorCode.GROUPNOTEXIST);
if (group != null && group.getOwner() != null && !group.getOwner().equals(username)) { }
if (group.getOwner() != null && !group.getOwner().equals(username)) {
throw new ClientRequestException(AccountErrorCode.NOPERMISSION); throw new ClientRequestException(AccountErrorCode.NOPERMISSION);
} }
List<String> shopIds = new ArrayList<>(); List<String> shopIds = new ArrayList<>();
if (groupId.equals("-1")) { if ("-1".equals(groupId)) {
if (shopFilterDto.getBindIp() == 0) if (shopFilterDto.getBindIp() == 0) {
shopIds = userShopRepository.findByUsername(username).stream(). // 获取当前用户下所有的商铺id
map(x -> x.getShopId()).collect(Collectors.toList()); shopIds = userShopRepository.findByUsername(username).stream()
else if (shopFilterDto.getBindIp() == 1) { .map(UserShop::getShopId).collect(Collectors.toList());
} else if (shopFilterDto.getBindIp() == 1) {
List<String> allIds = userShopRepository.findByUsername(username).stream() List<String> allIds = userShopRepository.findByUsername(username).stream()
.map(x -> x.getShopId()).collect(Collectors.toList()); .map(UserShop::getShopId).collect(Collectors.toList());
shopIds = ipResourceRepository.findShopIdInList(allIds, false) shopIds = ipResourceRepository.findShopIdInList(allIds, false).stream()
.stream().flatMap((x -> x.getShopIds().stream())).collect(Collectors.toList()); .flatMap((x -> x.getShopIds().stream())).collect(Collectors.toList());
} } else {
else {
List<String> allIds = userShopRepository.findByUsername(username).stream() List<String> allIds = userShopRepository.findByUsername(username).stream()
.map(x -> x.getShopId()).collect(Collectors.toList()); .map(UserShop::getShopId).collect(Collectors.toList());
for (String id:allIds) { for (String id : allIds) {
IpResource ipResource = ipResourceRepository.findFirstByShopIdsIsAndIsDeleted(id, false); IpResource ipResource = ipResourceRepository.findFirstByShopIdsIsAndIsDeleted(id, false);
if (ipResource == null) { if (ipResource == null) {
shopIds.add(id); shopIds.add(id);
...@@ -381,44 +379,52 @@ public class ShopServiceImpl implements ShopService { ...@@ -381,44 +379,52 @@ public class ShopServiceImpl implements ShopService {
} }
} }
} else { } else {
if (shopFilterDto.getBindIp() == 0) if (shopFilterDto.getBindIp() == 0) {
shopIds = userShopRepository.findByUsernameAndGroupId(username, groupId).stream(). shopIds = userShopRepository.findByUsernameAndGroupId(username, groupId).stream().
map(x -> x.getShopId()).collect(Collectors.toList()); map(UserShop::getShopId).collect(Collectors.toList());
else if (shopFilterDto.getBindIp() == 1) { } else if (shopFilterDto.getBindIp() == 1) {
List<String> allIds = userShopRepository.findByUsernameAndGroupId(username, groupId).stream(). List<String> allIds = userShopRepository.findByUsernameAndGroupId(username, groupId).stream()
map(x -> x.getShopId()).collect(Collectors.toList()); .map(UserShop::getShopId).collect(Collectors.toList());
shopIds = ipResourceRepository.findShopIdInList(allIds, false) shopIds = ipResourceRepository.findShopIdInList(allIds, false).stream()
.stream().flatMap((x -> x.getShopIds().stream())).collect(Collectors.toList()); .flatMap((x -> x.getShopIds().stream())).collect(Collectors.toList());
} } else {
else {
List<String> allIds = userShopRepository.findByUsernameAndGroupId(username, groupId).stream() List<String> allIds = userShopRepository.findByUsernameAndGroupId(username, groupId).stream()
.map(x -> x.getShopId()).collect(Collectors.toList()); .map(UserShop::getShopId).collect(Collectors.toList());
for (String id:allIds) { for (String id : allIds) {
IpResource ipResource = ipResourceRepository.findFirstByShopIdsIsAndIsDeleted(id, false); IpResource ipResource = ipResourceRepository.findFirstByShopIdsIsAndIsDeleted(id, false);
if (ipResource == null) if (ipResource == null) {
shopIds.add(id); shopIds.add(id);
} }
} }
} }
}
if (amount > 100) {
amount = 100;
}
Pageable pageable = PageRequest.of(pageNum, amount);
Page<Shop> shops; Page<Shop> shops;
if (shopFilterDto != null && StringUtils.isNotBlank(shopFilterDto.getIpRegion())) { if (StringUtils.isNotBlank(shopFilterDto.getIpRegion())) {
List<String> filter = ipResourceRepository.findShopIdInListAndRegionLike(shopIds, false, shopFilterDto.getIpRegion()) List<String> filter = ipResourceRepository.findShopIdInListAndRegionLike(shopIds, false, shopFilterDto.getIpRegion())
.stream().flatMap((x -> x.getShopIds().stream())).collect(Collectors.toList()); .stream().flatMap((x -> x.getShopIds().stream())).collect(Collectors.toList());
shops = shopRepository.findByShopIdInOrderByCreateTimeDesc(filter, pageable); shops = shopRepository.findByShopIdInOrderByCreateTimeDesc(filter, pageable);
} } else if (StringUtils.isNotBlank(shopFilterDto.getShopAccount())) {
else if (shopFilterDto != null && StringUtils.isNotBlank(shopFilterDto.getShopAccount()))
shops = shopRepository.findByShopIdInAndShopAccountLikeOrderByCreateTimeDesc(shopIds, shopFilterDto.getShopAccount(), pageable); shops = shopRepository.findByShopIdInAndShopAccountLikeOrderByCreateTimeDesc(shopIds, shopFilterDto.getShopAccount(), pageable);
else if (shopFilterDto != null && StringUtils.isNotBlank(shopFilterDto.getShopName())) } else if (StringUtils.isNotBlank(shopFilterDto.getShopName())) {
shops = shopRepository.findByShopIdInAndShopNameLikeOrderByCreateTimeDesc(shopIds, shopFilterDto.getShopName(), pageable); shops = shopRepository.findByShopIdInAndShopNameLikeOrderByCreateTimeDesc(shopIds, shopFilterDto.getShopName(), pageable);
else } else {
shops = shopRepository.findByShopIdInOrderByCreateTimeDesc(shopIds, pageable); shops = shopRepository.findByShopIdInOrderByCreateTimeDesc(shopIds, pageable);
if (shops == null || shops.getNumberOfElements() < 1) }
return new ShopPageResultDto();
ShopPageResultDto<ShopResultDto> shopPageResultDto = new ShopPageResultDto<>();
if (shops == null || shops.getNumberOfElements() < 1) {
return shopPageResultDto;
} else {
List<ShopResultDto> shopResultDtos = new ArrayList<>(); List<ShopResultDto> shopResultDtos = new ArrayList<>();
shops.getContent().stream().forEach(x -> { shops.getContent().stream().forEach(x -> {
IpResource ipResource = ipResourceRepository.findFirstByShopIdsIsAndIsDeleted(x.getShopId(), false); IpResource ipResource = ipResourceRepository.findFirstByShopIdsIsAndIsDeleted(x.getShopId(), false);
if (ipResource != null) { if (ipResource != null && StringUtils.isNotBlank(ipResource.getAddr())) {
if (StringUtils.isNotBlank(ipResource.getAddr())) {
if (ipResource.getValidTime() <= Instant.now().plusSeconds(60 * 60 * 24 * 7).toEpochMilli() && ipResource.getValidTime() > Instant.now().toEpochMilli()) { if (ipResource.getValidTime() <= Instant.now().plusSeconds(60 * 60 * 24 * 7).toEpochMilli() && ipResource.getValidTime() > Instant.now().toEpochMilli()) {
if (ipResource.getStatus() != 5 && ipResource.getStatus() != 3 && ipResource.getStatus() != 6) { if (ipResource.getStatus() != 5 && ipResource.getStatus() != 3 && ipResource.getStatus() != 6) {
ipResource.setStatus(2); ipResource.setStatus(2);
...@@ -456,21 +462,23 @@ public class ShopServiceImpl implements ShopService { ...@@ -456,21 +462,23 @@ public class ShopServiceImpl implements ShopService {
} }
} }
} }
} if (ipResource == null) {
if (ipResource == null)
ipResource = new IpResource(); ipResource = new IpResource();
}
String group1 = userShopRepository.findByUsernameAndShopId(username, x.getShopId()).getGroupId(); String group1 = userShopRepository.findByUsernameAndShopId(username, x.getShopId()).getGroupId();
ShopResultDto shopResultDto = null; ShopResultDto shopResultDto = null;
if (ipResource.isSpecialLine()) { if (ipResource.isSpecialLine()) {
SpecialLine specialLine = specialLineRepository.findAll().get(0); SpecialLine specialLine = specialLineRepository.findAll().get(0);
shopResultDto = ShopResultDto.of(x, group1, new IpResourceDto(ipResource, null, false, specialLine)); shopResultDto = ShopResultDto.of(x, group1, new IpResourceDto(ipResource, null, false, specialLine));
} } else {
else
shopResultDto = ShopResultDto.of(x, group1, new IpResourceDto(ipResource, null, false)); shopResultDto = ShopResultDto.of(x, group1, new IpResourceDto(ipResource, null, false));
}
shopResultDtos.add(shopResultDto); shopResultDtos.add(shopResultDto);
}); });
Page<ShopResultDto> shopDtoPage = new PageImpl<>(shopResultDtos, pageable, shopIds.size()); Page<ShopResultDto> shopDtoPage = new PageImpl<>(shopResultDtos, pageable, shopIds.size());
ShopPageResultDto shopPageResultDto = new ShopPageResultDto();
shopPageResultDto.setShopList(shopDtoPage.getContent()); shopPageResultDto.setShopList(shopDtoPage.getContent());
PageInfo pageInfo = new PageInfo(); PageInfo pageInfo = new PageInfo();
pageInfo.setCurrentPage(shopDtoPage.getPageable().getPageNumber()); pageInfo.setCurrentPage(shopDtoPage.getPageable().getPageNumber());
...@@ -479,17 +487,21 @@ public class ShopServiceImpl implements ShopService { ...@@ -479,17 +487,21 @@ public class ShopServiceImpl implements ShopService {
shopPageResultDto.setShopPage(pageInfo); shopPageResultDto.setShopPage(pageInfo);
return shopPageResultDto; return shopPageResultDto;
} }
}
@Override @Override
public ShopSummary getShopSummary(String username) { public ShopSummary getShopSummary(String username) {
Account account = accountRepository.findByName(username); Account account = accountRepository.findByName(username);
if (account == null) if (account == null) {
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST); throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST);
}
ShopSummary shopSummary = new ShopSummary(); ShopSummary shopSummary = new ShopSummary();
List<String> allShopIds = userShopRepository.findByUsername(username).stream().map(x -> x.getShopId()).collect(Collectors.toList()); List<String> allShopIds = userShopRepository.findByUsername(username).stream()
.map(UserShop::getShopId).collect(Collectors.toList());
List<String> unbind = new ArrayList<>(); List<String> unbind = new ArrayList<>();
if (allShopIds != null && allShopIds.size() > 0) { if (!allShopIds.isEmpty()) {
for (String id:allShopIds) { for (String id : allShopIds) {
IpResource ipResource = ipResourceRepository.findFirstByShopIdsIsAndIsDeleted(id, false); IpResource ipResource = ipResourceRepository.findFirstByShopIdsIsAndIsDeleted(id, false);
if (ipResource == null) { if (ipResource == null) {
unbind.add(id); unbind.add(id);
...@@ -497,8 +509,11 @@ public class ShopServiceImpl implements ShopService { ...@@ -497,8 +509,11 @@ public class ShopServiceImpl implements ShopService {
} }
} }
shopSummary.setUnbind(unbind.size()); shopSummary.setUnbind(unbind.size());
List<String> shopIds = userShopRepository.findByUsername(username).stream().map(x -> x.getShopId()).collect(Collectors.toList());
List<String> bind = ipResourceRepository.findShopIdInList(shopIds, false).stream().map(x -> x.getId()).collect(Collectors.toList()); List<String> shopIds = userShopRepository.findByUsername(username).stream()
.map(UserShop::getShopId).collect(Collectors.toList());
List<String> bind = ipResourceRepository.findShopIdInList(shopIds, false).stream()
.map(IpResource::getId).collect(Collectors.toList());
int expired = ipResourceRepository.countByStatusAndIdInAndIsDeleted(1, bind, false); int expired = ipResourceRepository.countByStatusAndIdInAndIsDeleted(1, bind, false);
int willexpired = ipResourceRepository.countByStatusAndIdInAndIsDeleted(2, bind, false); int willexpired = ipResourceRepository.countByStatusAndIdInAndIsDeleted(2, bind, false);
shopSummary.setExpired(expired); shopSummary.setExpired(expired);
...@@ -529,7 +544,7 @@ public class ShopServiceImpl implements ShopService { ...@@ -529,7 +544,7 @@ public class ShopServiceImpl implements ShopService {
if (shopIds != null && shopIds.size() > 0) { if (shopIds != null && shopIds.size() > 0) {
String maxShopId = null; String maxShopId = null;
int max = 0; int max = 0;
for (String shopId:shopIds) { for (String shopId : shopIds) {
int userCount = userShopRepository.countByShopId(shopId); int userCount = userShopRepository.countByShopId(shopId);
if (userCount > max) { if (userCount > max) {
max = userCount; max = userCount;
......
...@@ -26,12 +26,8 @@ import org.slf4j.Logger; ...@@ -26,12 +26,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.io.IOException; import java.io.IOException;
import java.time.Instant; import java.time.Instant;
...@@ -83,15 +79,14 @@ public class BrowserTask { ...@@ -83,15 +79,14 @@ public class BrowserTask {
return headers; return headers;
} }
public HttpHeaders buildPostHeader() { public Map<String, String> buildPostHeader() {
HttpHeaders header = new HttpHeaders(); Map<String, String> headers = new HashMap<>();
header.setContentType(MediaType.APPLICATION_JSON); headers.put("Content-Type", "application/json");
if (profiles.equals("dev") || profiles.equals("staging")) { if (profiles.equals("dev") || profiles.equals("staging"))
header.setBearerAuth("oq5tg3gMsflHcK5iZ2741G5R30XYd9blyOqH9qeBItKtrzfTsGIoy8AsxqqNXdcm"); headers.put("Authorization", "Bearer oq5tg3gMsflHcK5iZ2741G5R30XYd9blyOqH9qeBItKtrzfTsGIoy8AsxqqNXdcm");
} else if (profiles.equals("prod")) { else if (profiles.equals("prod"))
header.setBearerAuth("tKWsuHzcngf0RQPMss70f9jgymDIwgQ9zbLfESJdcou3pZSNWl7lNTzto8VQgwaO"); headers.put("Authorization", "Bearer tKWsuHzcngf0RQPMss70f9jgymDIwgQ9zbLfESJdcou3pZSNWl7lNTzto8VQgwaO");
} return headers;
return header;
} }
private IpChargeRequestDto buildIpChargeRequestDto(IpResource request, int chargeType, int payMethod) { private IpChargeRequestDto buildIpChargeRequestDto(IpResource request, int chargeType, int payMethod) {
...@@ -111,14 +106,15 @@ public class BrowserTask { ...@@ -111,14 +106,15 @@ public class BrowserTask {
String URL = (profiles.equals("dev") || profiles.equals("staging")) ? TESTURL : CLOUDAMURL; String URL = (profiles.equals("dev") || profiles.equals("staging")) ? TESTURL : CLOUDAMURL;
long time = Instant.now().minusSeconds(300).toEpochMilli(); long time = Instant.now().minusSeconds(300).toEpochMilli();
List<IpResource> ipResources = ipResourceRepository.sampleTasks(6, time); List<IpResource> ipResources = ipResourceRepository.sampleTasks(6, time);
log.error("buyIpTasks sample {} tasks", ipResources.size());
List<CompletableFuture> futureList = new ArrayList<>();
for (IpResource ipResource : ipResources) { for (IpResource ipResource : ipResources) {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
CompletableFuture.runAsync(() -> { CompletableFuture future = CompletableFuture.runAsync(() -> {
if (ipResourceRepository.lockTask(ipResource)) { if (ipResourceRepository.lockTask(ipResource)) {
try { try {
boolean result = false; boolean result = false;
RestTemplate restTemplate = new RestTemplate(); Map<String, String> header = buildPostHeader();
HttpHeaders header = buildPostHeader();
HashMap<String, Object> map = new HashMap<>(); HashMap<String, Object> map = new HashMap<>();
map.put("name", ipResource.getUsername()); map.put("name", ipResource.getUsername());
map.put("region", ipResource.getRegion()); map.put("region", ipResource.getRegion());
...@@ -130,10 +126,11 @@ public class BrowserTask { ...@@ -130,10 +126,11 @@ public class BrowserTask {
map.put("startscript", ""); map.put("startscript", "");
map.put("ipkeptperiod", 7); map.put("ipkeptperiod", 7);
map.put("persistSystemDiskOnTermination", false); map.put("persistSystemDiskOnTermination", false);
HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(map, header); // HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(map, header);
IpBuyResultDto ipBuyResultDto = null; IpBuyResultDto ipBuyResultDto = null;
try { try {
ipBuyResultDto = restTemplate.postForObject(URL + "/intelligroup/ipresources?accountId=browser", httpEntity, IpBuyResultDto.class); String requestResult = HttpClientutils.doPost(URL + "/intelligroup/ipresources?accountId=browser", header, JSONObject.toJSONString(map));
ipBuyResultDto = JSONObject.parseObject(requestResult, IpBuyResultDto.class);
if (StringUtils.isNotBlank(ipBuyResultDto.getErrorCode())) { if (StringUtils.isNotBlank(ipBuyResultDto.getErrorCode())) {
log.error("fail to buy ip"); log.error("fail to buy ip");
log.error(ipBuyResultDto.getErrorCode()); log.error(ipBuyResultDto.getErrorCode());
...@@ -186,7 +183,9 @@ public class BrowserTask { ...@@ -186,7 +183,9 @@ public class BrowserTask {
} }
} }
}, ThreadPoolUtils.buyIpTasksPool); }, ThreadPoolUtils.buyIpTasksPool);
futureList.add(future);
} }
CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0])).join();
} }
@Scheduled(cron = "0 0/1 * * * ?") @Scheduled(cron = "0 0/1 * * * ?")
...@@ -358,6 +357,20 @@ public class BrowserTask { ...@@ -358,6 +357,20 @@ public class BrowserTask {
return responseBody.string(); return responseBody.string();
} }
public static String doPost(String url, Map<String, String> headers, String body) throws IOException {
Headers httpHeaders = Headers.of(headers);
Request request = new Request.Builder()
.post(RequestBody.create(body, okhttp3.MediaType.get("application/json")))
.url(url)
.headers(httpHeaders)
.build();
Call call = client.newCall(request);
Response response = call.execute();
ResponseBody responseBody = response.body();
return responseBody.string();
}
} }
......
package com.edgec.browserbackend.browser.task; package com.edgec.browserbackend.browser.task;
import com.edgec.browserbackend.account.repository.AccountRepository; import com.edgec.browserbackend.account.repository.AccountRepository;
import com.edgec.browserbackend.auth.domain.mongo.MongoOAuth2AccessToken;
import com.edgec.browserbackend.auth.repository.mongo.MongoOAuth2AccessTokenRepository; import com.edgec.browserbackend.auth.repository.mongo.MongoOAuth2AccessTokenRepository;
import com.edgec.browserbackend.browser.domain.IpResource; import com.edgec.browserbackend.browser.domain.IpResource;
import com.edgec.browserbackend.browser.domain.IpType; import com.edgec.browserbackend.browser.domain.IpType;
import com.edgec.browserbackend.browser.domain.ProxyConfig;
import com.edgec.browserbackend.browser.repository.IpResourceRepository; import com.edgec.browserbackend.browser.repository.IpResourceRepository;
import com.edgec.browserbackend.browser.repository.ProxyConfigRepository; import com.edgec.browserbackend.browser.repository.ProxyConfigRepository;
import com.edgec.browserbackend.browser.repository.SpecialLineRepository; import com.edgec.browserbackend.browser.repository.SpecialLineRepository;
...@@ -19,8 +19,10 @@ import org.springframework.stereotype.Component; ...@@ -19,8 +19,10 @@ import org.springframework.stereotype.Component;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.File; import java.io.File;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException;
import java.time.Instant; import java.time.Instant;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
@Component @Component
public class Set3proxyTask { public class Set3proxyTask {
...@@ -42,22 +44,21 @@ public class Set3proxyTask { ...@@ -42,22 +44,21 @@ public class Set3proxyTask {
@Autowired @Autowired
private ProxyConfigRepository proxyConfigRepository; private ProxyConfigRepository proxyConfigRepository;
@Scheduled(cron = "0 0/10 * * * ?") @Scheduled(cron = "0 0/2 * * * ?")
@SchedulerLock(name = "proxyTask", lockAtLeastFor = 60 * 1000 * 5, lockAtMostFor = 60 * 1000 * 9) @SchedulerLock(name = "proxyTask", lockAtLeastFor = 60 * 1000 * 5, lockAtMostFor = 60 * 1000 * 9)
public void set3proxy() { public void set3proxy() {
long nowtime = Instant.now().toEpochMilli(); long validTime = Instant.now().minusSeconds(43200).toEpochMilli();
// List<String> tokenUsernames = mongoOAuth2AccessTokenRepository.findByCreatedAtGreaterThan(validTime).stream().map(MongoOAuth2AccessToken::getUsername).collect(Collectors.toList());
// List<String> accountParents = accountRepository.findByNameIn(tokenUsernames).stream().map(x -> x.getParent() == null ? x.getName() : x.getParent()).distinct().collect(Collectors.toList()); List<String> tokenUsernames = mongoOAuth2AccessTokenRepository.findByCreatedAtGreaterThan(validTime).stream().map(MongoOAuth2AccessToken::getUsername).collect(Collectors.toList());
// List<IpResource> ipResources = ipResourceRepository.findByOwnerInAndSpecialLine(accountParents, true); List<String> accountParents = accountRepository.findByNameIn(tokenUsernames).stream().map(x -> x.getParent() == null ? x.getName() : x.getParent()).distinct().collect(Collectors.toList());
List<IpResource> ipResources = ipResourceRepository.findBySpecialLineAndIsDeleted(true, false); List<IpResource> ipResources = ipResourceRepository.findByOwnerInAndSpecialLine(accountParents, true);
// List<IpResource> ipResources = ipResourceRepository.findBySpecialLineAndIsDeleted(true, false);
File file = new File("3proxy_" + Instant.now().toEpochMilli()); File file = new File("3proxy_" + Instant.now().toEpochMilli());
try { try {
try {
file.delete(); file.delete();
file.createNewFile(); file.createNewFile();
} catch (Exception t1) {
log.error(t1.getMessage(), t1);
}
FileWriter fileWriter = new FileWriter(file, true); FileWriter fileWriter = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(fileWriter); BufferedWriter bw = new BufferedWriter(fileWriter);
...@@ -66,53 +67,55 @@ public class Set3proxyTask { ...@@ -66,53 +67,55 @@ public class Set3proxyTask {
bw.write("config /root/3proxy.cfg\n"); bw.write("config /root/3proxy.cfg\n");
bw.write("monitor /root/3proxy.cfg\n"); bw.write("monitor /root/3proxy.cfg\n");
for (IpResource ipResource : ipResources) { // 写入 ipResources 相关信息
if (StringUtils.isNotBlank(ipResource.getAddr())) if (ipResources.size() != 0) {
bw.write("users \"" + ipResource.getProxyUsername() + ":CL:" + ipResource.getProxyPassword() + "\"\n"); bwWriteIpResources(ipResources, bw);
ipResource.setUsingSpecialLine(true);
} }
bw.write("\nauth strong\n"); bw.write("\nauth strong\n");
a:
for (IpResource ipResource : ipResources) {
if (StringUtils.isNotBlank(ipResource.getAddr())) {
if (ipResource.getPort() == null || ipResource.getPort().size() == 0)
continue a;
bw.write("allow " + ipResource.getProxyUsername() + "\n");
if (ipResource.getIpType() != IpType.OWN) {
bw.write("parent 1000 http " + ipResource.getAddr() + " " +
(ipResource.getPort().size() > 1 ? ipResource.getPort().get(1) : ipResource.getPort().get(0)) + " fangguanlianbrowser " + ipResource.getPassword() + "\n");
} else {
bw.write("parent 1000 http " + ipResource.getAddr() + " " +
(ipResource.getPort().size() > 1 ? ipResource.getPort().get(1) : ipResource.getPort().get(0)) + " " + ipResource.getUsername() + " " + ipResource.getPassword() + "\n");
}
}
}
bw.write("\nallow none\nproxy -p20004\nsocks -p20005\n"); bw.write("\nallow none\nproxy -p20004\nsocks -p20005\n");
bw.flush(); bw.flush();
bw.close(); bw.close();
log.error("成功写入文件"); log.info("成功写入文件");
if (proxyConfigRepository.count() > 0) { long nowtime = Instant.now().toEpochMilli();
ProxyConfig proxyConfig = proxyConfigRepository.findAll().get(0); long proxyConfigTimestamp = proxyConfigRepository.findAll().get(0).getTimestamp();
if (nowtime < proxyConfig.getTimestamp()) { if (proxyConfigRepository.count() > 0 && nowtime < proxyConfigTimestamp) {
file.delete();
return;
} else {
proxyConfigRepository.updateProxy(file, nowtime);
file.delete(); file.delete();
}
} else { } else {
proxyConfigRepository.updateProxy(file, nowtime); proxyConfigRepository.updateProxy(file, nowtime);
file.delete(); file.delete();
} }
} catch (Exception e) { } catch (Exception e) {
log.error("出错了");
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
} }
} }
private void bwWriteIpResources(List<IpResource> ipResources, BufferedWriter bw) throws IOException {
for (IpResource ipResource : ipResources) {
ipResource.setUsingSpecialLine(true);
if (StringUtils.isNotBlank(ipResource.getAddr())) {
bw.write("users \"" + ipResource.getProxyUsername() + ":CL:" + ipResource.getProxyPassword() + "\"\n");
if (ipResource.getPort() == null || ipResource.getPort().size() == 0) {
continue;
}
bw.write("allow " + ipResource.getProxyUsername() + "\n");
String textStart = "parent 1000 http " + ipResource.getAddr() + " ";
String textMiddle = ipResource.getPort().size() > 1 ? ipResource.getPort().get(1) : ipResource.getPort().get(0);
if (ipResource.getIpType() != IpType.OWN) {
bw.write(textStart + textMiddle
+ " fangguanlianbrowser " + ipResource.getPassword() + "\n");
} else {
bw.write(textStart + textMiddle
+ " " + ipResource.getUsername() + " " + ipResource.getPassword() + "\n");
}
}
}
}
} }
...@@ -26,7 +26,7 @@ public class ClientRequestException extends IllegalArgumentException { ...@@ -26,7 +26,7 @@ public class ClientRequestException extends IllegalArgumentException {
this.errorCode = errorCode; this.errorCode = errorCode;
} }
public ClientRequestException(int errorCode, String message){ public ClientRequestException(int errorCode, String message) {
super(message); super(message);
} }
......
...@@ -12,7 +12,6 @@ public interface ErrorCode { ...@@ -12,7 +12,6 @@ public interface ErrorCode {
public static final int COMMON_UNAUTHRORIZED = 100004; public static final int COMMON_UNAUTHRORIZED = 100004;
public static final int ACCOUNT_BASE = 400000; public static final int ACCOUNT_BASE = 400000;
public static final int AUTH_BASE = 500000; public static final int AUTH_BASE = 500000;
...@@ -20,9 +19,11 @@ public interface ErrorCode { ...@@ -20,9 +19,11 @@ public interface ErrorCode {
public static final int BROWSER_BASE = 600000; public static final int BROWSER_BASE = 600000;
int value() ; int value();
@JsonValue @JsonValue
int getCode() ; int getCode();
String getReason();
} }
...@@ -3,12 +3,9 @@ package com.edgec.browserbackend.common.utils; ...@@ -3,12 +3,9 @@ package com.edgec.browserbackend.common.utils;
import com.edgec.browserbackend.browser.ErrorCode.BrowserErrorCode; import com.edgec.browserbackend.browser.ErrorCode.BrowserErrorCode;
import com.edgec.browserbackend.common.commons.error.ClientRequestException; import com.edgec.browserbackend.common.commons.error.ClientRequestException;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.*; import java.io.*;
import java.util.ArrayList; import java.util.ArrayList;
...@@ -29,12 +26,12 @@ public class FileUtil { ...@@ -29,12 +26,12 @@ public class FileUtil {
String line = null; String line = null;
StringBuffer buf = new StringBuffer(); StringBuffer buf = new StringBuffer();
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(f), charset); try (InputStreamReader reader = new InputStreamReader(new FileInputStream(f), charset);
BufferedReader br = new BufferedReader(reader);){ BufferedReader br = new BufferedReader(reader);) {
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
buf.append(line+System.getProperty("line.separator")); buf.append(line + System.getProperty("line.separator"));
} }
} catch (Exception e) { } catch (Exception e) {
log.error("[" + f.getName() + "]文件读出失败{}",e); log.error("[" + f.getName() + "]文件读出失败{}", e);
return null; return null;
} }
log.debug("[" + f.getName() + "]文件读出成功"); log.debug("[" + f.getName() + "]文件读出成功");
...@@ -46,14 +43,14 @@ public class FileUtil { ...@@ -46,14 +43,14 @@ public class FileUtil {
List<String> lineList = new ArrayList<String>(); List<String> lineList = new ArrayList<String>();
StringBuffer buf = new StringBuffer(); StringBuffer buf = new StringBuffer();
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(f), charset); try (InputStreamReader reader = new InputStreamReader(new FileInputStream(f), charset);
BufferedReader br = new BufferedReader(reader);){ BufferedReader br = new BufferedReader(reader);) {
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
lineList.add(line); lineList.add(line);
} }
br.close(); br.close();
reader.close(); reader.close();
} catch (Exception e) { } catch (Exception e) {
log.error("[" + f.getName() + "]文件读出失败{}",e); log.error("[" + f.getName() + "]文件读出失败{}", e);
return null; return null;
} }
log.debug("[" + f.getName() + "]文件读出成功"); log.debug("[" + f.getName() + "]文件读出成功");
...@@ -61,10 +58,10 @@ public class FileUtil { ...@@ -61,10 +58,10 @@ public class FileUtil {
} }
public static boolean write(String content, File file) { public static boolean write(String content, File file) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))){ try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
bw.write(content); bw.write(content);
} catch (Exception e) { } catch (Exception e) {
log.error("[" + file.getName() + "]写入失败{}",e); log.error("[" + file.getName() + "]写入失败{}", e);
return false; return false;
} }
log.debug("[" + file.getName() + "]文件写入成功"); log.debug("[" + file.getName() + "]文件写入成功");
...@@ -72,7 +69,7 @@ public class FileUtil { ...@@ -72,7 +69,7 @@ public class FileUtil {
} }
//读取excel //读取excel
public static List<List<Object>> readExcel(InputStream inputStream){ public static List<List<Object>> readExcel(InputStream inputStream) {
List<List<Object>> list = new ArrayList<>(); List<List<Object>> list = new ArrayList<>();
Workbook workbook = null; Workbook workbook = null;
try { try {
...@@ -89,7 +86,8 @@ public class FileUtil { ...@@ -89,7 +86,8 @@ public class FileUtil {
//总列数 //总列数
int colLength = row.getLastCellNum(); int colLength = row.getLastCellNum();
//得到指定的单元格 //得到指定的单元格
Cell cell = row.getCell(0);; Cell cell = row.getCell(0);
;
int size = 1; int size = 1;
boolean first = false; boolean first = false;
for (int i = 1; i < rowLength; i++) { for (int i = 1; i < rowLength; i++) {
...@@ -99,7 +97,7 @@ public class FileUtil { ...@@ -99,7 +97,7 @@ public class FileUtil {
for (int j = 0; j < colLength; j++) { for (int j = 0; j < colLength; j++) {
cell = row.getCell(j); cell = row.getCell(j);
// System.out.println(cell); // System.out.println(cell);
if (cell!=null) { if (cell != null) {
Object cellValue = getCellFormatValue(cell); Object cellValue = getCellFormatValue(cell);
if (cellValue.toString().contains("店铺名称")) { if (cellValue.toString().contains("店铺名称")) {
first = true; first = true;
...@@ -109,8 +107,7 @@ public class FileUtil { ...@@ -109,8 +107,7 @@ public class FileUtil {
if (StringUtils.isNotBlank(cellValue.toString())) { if (StringUtils.isNotBlank(cellValue.toString())) {
size++; size++;
} }
} } else
else
rowvalue.add(""); rowvalue.add("");
} }
if (first) { if (first) {
...@@ -127,37 +124,37 @@ public class FileUtil { ...@@ -127,37 +124,37 @@ public class FileUtil {
log.error("parse excel file error :", e); log.error("parse excel file error :", e);
throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE); throw new ClientRequestException(BrowserErrorCode.INFORMATIONNOTCOMPELETE);
} }
return list ; return list;
} }
public static Object getCellFormatValue(Cell cell){ public static Object getCellFormatValue(Cell cell) {
Object cellValue = null; Object cellValue = null;
if(cell!=null){ if (cell != null) {
//判断cell类型 //判断cell类型
switch(cell.getCellType()){ switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:{ case Cell.CELL_TYPE_NUMERIC: {
cellValue = String.valueOf((int)cell.getNumericCellValue()); cellValue = String.valueOf((int) cell.getNumericCellValue());
break; break;
} }
case Cell.CELL_TYPE_FORMULA:{ case Cell.CELL_TYPE_FORMULA: {
//判断cell是否为日期格式 //判断cell是否为日期格式
if(DateUtil.isCellDateFormatted(cell)){ if (DateUtil.isCellDateFormatted(cell)) {
//转换为日期格式YYYY-mm-dd //转换为日期格式YYYY-mm-dd
cellValue = cell.getDateCellValue(); cellValue = cell.getDateCellValue();
}else{ } else {
//数字 //数字
cellValue = String.valueOf(cell.getNumericCellValue()); cellValue = String.valueOf(cell.getNumericCellValue());
} }
break; break;
} }
case Cell.CELL_TYPE_STRING:{ case Cell.CELL_TYPE_STRING: {
cellValue = cell.getRichStringCellValue().getString(); cellValue = cell.getRichStringCellValue().getString();
break; break;
} }
default: default:
cellValue = ""; cellValue = "";
} }
}else{ } else {
cellValue = ""; cellValue = "";
} }
return cellValue; return cellValue;
...@@ -165,25 +162,26 @@ public class FileUtil { ...@@ -165,25 +162,26 @@ public class FileUtil {
/** /**
* 方法说明将files打包放到一个zip中。 * 方法说明将files打包放到一个zip中。
*
* @return * @return
* @throws IOException * @throws IOException
*/ */
public static File putBatchFilesInZip(List<File> filePaths,File tempFile) throws IOException { public static File putBatchFilesInZip(List<File> filePaths, File tempFile) throws IOException {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(tempFile)); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(tempFile));
for(File inputFile : filePaths) { for (File inputFile : filePaths) {
try(FileInputStream fis = new FileInputStream(inputFile);){ try (FileInputStream fis = new FileInputStream(inputFile);) {
//压缩文件中写入名称 //压缩文件中写入名称
ZipEntry entry = new ZipEntry(inputFile.getName()); ZipEntry entry = new ZipEntry(inputFile.getName());
zos.putNextEntry(entry); zos.putNextEntry(entry);
// 向压缩文件中输出数据 // 向压缩文件中输出数据
int len = 0; int len = 0;
byte[] bt = new byte[5*1024]; byte[] bt = new byte[5 * 1024];
while ((len = fis.read(bt)) != -1) { while ((len = fis.read(bt)) != -1) {
//压缩文件中写入真正的文件流 //压缩文件中写入真正的文件流
zos.write(bt, 0, len); zos.write(bt, 0, len);
} }
}catch(Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
throw new RuntimeException(); throw new RuntimeException();
} }
......
package com.edgec.browserbackend.common.utils; package com.edgec.browserbackend.common.utils;
import org.apache.commons.io.Charsets;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
...@@ -12,12 +13,11 @@ import org.apache.http.client.methods.HttpGet; ...@@ -12,12 +13,11 @@ import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader;
public class Trans { public class Trans {
private final Logger logger = LoggerFactory.getLogger(Trans.class); private final Logger logger = LoggerFactory.getLogger(Trans.class);
...@@ -50,7 +50,7 @@ public class Trans { ...@@ -50,7 +50,7 @@ public class Trans {
*/ */
public static void main(String[] args) { public static void main(String[] args) {
String url = "http://free.ipwhois.io/json/"; String url = "http://free.ipwhois.io/json/";
Trans trans = new Trans("23.105.2.118", "uE5LkzM81UhUaA1"); Trans trans = new Trans("112.74.47.217", 20001, "fangguanlianbrowser", "5D753F36QKqIaA1");
String rs = trans.get(url); String rs = trans.get(url);
System.out.println(rs); System.out.println(rs);
} }
...@@ -84,17 +84,7 @@ public class Trans { ...@@ -84,17 +84,7 @@ public class Trans {
HttpResponse response = client.execute(httpGet); HttpResponse response = client.execute(httpGet);
HttpEntity entry = response.getEntity(); HttpEntity entry = response.getEntity();
return EntityUtils.toString(entry, Charsets.UTF_8);
if (entry != null) {
InputStreamReader is = new InputStreamReader(entry.getContent());
BufferedReader br = new BufferedReader(is);
String str = null;
while ((str = br.readLine()) != null) {
sb.append(str.trim());
}
br.close();
}
return sb.toString();
} catch (ClientProtocolException e) { } catch (ClientProtocolException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
return ""; return "";
...@@ -106,6 +96,11 @@ public class Trans { ...@@ -106,6 +96,11 @@ public class Trans {
return ""; return "";
} finally { } finally {
httpGet.releaseConnection(); httpGet.releaseConnection();
try {
client.close();
} catch (IOException e) {
logger.error("fail to close connection", e);
}
} }
} }
} }
\ No newline at end of file
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