preface
This example is to call Baidu face library interface to add, modify, delete the interface, no policy mode is written three if as follows
@Autowired private AuthService authService; @GetMapping(value = "/old") public String old(String state) { if ("add".equals(state)) { Faceadd.add (authService.getauth (), "153****7719", "123456", "98989897", "Lee s "); } if ("update".equals(state)) { FaceUpdate.faceUpdate(authService.getAuth(), "153****7719", "123456", "98989897", "Bill"); } if ("delete".equals(state)) { FaceDelete.faceDelete(authService.getAuth(), "153****7719", "123456", "98989897"); } return "succ"; }Copy the code
New Modified deleted tool classes
new
/ * * * face registered * / public class FaceAdd {/ * * * important code in the needed tools * FileUtil, Base64Util, HttpUtil, GsonUtils from * please https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72 * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2 * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3 * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3 download * * / public static String add (String accessToken, String image,String groupId,String userId,String user_info) {// Request URL String URL = "Https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add". try { Map<String, Object> map = new HashMap<>(); map.put("image", image); map.put("group_id", groupId); map.put("user_id", userId); map.put("user_info", user_info); map.put("liveness_control", "LOW"); map.put("image_type", "URL"); map.put("quality_control", "LOW"); String param = GsonUtils.toJson(map); The access_token expires in the online environment. The client can cache the access_token and obtain it again after it expires. // String accessToken = "[token obtained by calling the authentication interface]"; String result = HttpUtil.post(url, accessToken, "application/json", param); System.out.println(" add: "+result); return result; } catch (Exception e) { e.printStackTrace(); } return null; }}Copy the code
Modify the
/ * * * face registered * / public class FaceUpdate {/ * * * important code in the needed tools * FileUtil, Base64Util, HttpUtil, GsonUtils from * please https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72 * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2 * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3 * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3 download * * / public static String faceUpdate (String accessToken, String image,String groupId,String userId,String user_info) {// Request URL String URL = "Https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/update". try { Map<String, Object> map = new HashMap<>(); map.put("image", image); map.put("group_id", groupId); map.put("user_id", userId); map.put("image_type", "URL"); map.put("user_info", user_info); map.put("liveness_control", "LOW"); map.put("quality_control", "LOW"); String param = GsonUtils.toJson(map); The access_token expires in the online environment. The client can cache the access_token and obtain it again after it expires. // String accessToken = "[token obtained by calling the authentication interface]"; String result = HttpUtil.post(url, accessToken, "application/json", param); System.out.println(" update: "+result); return result; } catch (Exception e) { e.printStackTrace(); } return null; }}Copy the code
delete
/ face delete * * * * / public class FaceDelete {/ * * * important code in the needed tools * FileUtil, Base64Util, HttpUtil, GsonUtils please from * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72 * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2 * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3 * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3 download * * / public static String faceDelete (String accessToken, String faceToken,String groupId,String userId) {// Request URL String URL = "Https://aip.baidubce.com/rest/2.0/face/v3/faceset/face/delete". try { Map<String, Object> map = new HashMap<>(); map.put("face_token", faceToken); map.put("group_id", groupId); map.put("user_id", userId); String param = GsonUtils.toJson(map); The access_token expires in the online environment. The client can cache the access_token and obtain it again after it expires. // String accessToken = "[token obtained by calling the authentication interface]"; String result = HttpUtil.post(url, accessToken, "application/json", param); System.out.println(" delete: "+result); return result; } catch (Exception e) { e.printStackTrace(); } return null; }}Copy the code
Gets the access_token for the face
@Component public class AuthService {/** * Obtain permission token ** @return Example: * {* "access_token": "24.460 da4889caad24cccdb1fea17221975. 2592000.1491995545.282335-1234567," * "expires_in" : 2592000 * } */ @Autowired private RedisService redisService; Public String getAuth() {// String clientId = "i9EGdUMVvI"; public String getAuth() {// String clientId = "i9EGdUMVvI"; String clientSecret = "2TLdpLcdXn"; String clientSecret = "2TLdpLcdXn"; return getAuth(clientId, clientSecret); } /** * Obtain the API access token * This token has a certain validity period and needs to be managed by itself. * * @param ak - API Key * @param sk - Securet Key * @return assess_token An example is as follows: "*" 24.460 da4889caad24cccdb1fea17221975 2592000.1491995545.282335-1234567 * / public String getAuth (String ak, String sk) { Object object = redisService.get("baidu-token", ak + sk); if (object ! = null) { String access_token = object.toString(); return access_token; } / / access token address String authHost = "https://aip.baidubce.com/oauth/2.0/token?"; String getAccessTokenUrl = authHost // 1. grant_type is a fixed parameter + "grant_type=client_credentials" // 2. API Key + "&client_id=" + ak // 3. Secret Key + "&client_secret=" + sk; try { URL realUrl = new URL(getAccessTokenUrl); // Open a connection between HttpURLConnection connection = (HttpURLConnection) realurl.openConnection (); connection.setRequestMethod("GET"); connection.connect(); / / get all the response header field Map < String, a List < String > > Map = connection. GetHeaderFields (); // For (String key: map.keyset ()) {// system.err. Println (key + "-- >" + map.get(key)); //} // Define the BufferedReader input stream to read the URL response BufferedReader in = new BufferedReader(new) InputStreamReader(connection.getInputStream())); String result = ""; String line; while ((line = in.readLine()) ! = null) { result += line; } / return the result * * * sample * / / / System. Err, println (" result: "+ result); JSONObject jsonObject = new JSONObject(result); String access_token = jsonObject.getString("access_token"); long expires_in = jsonObject.getLong("expires_in")/60; if (StringUtils.isNotBlank(access_token)) { redisService.set("baidu-token", ak + sk, access_token, expires_in); return access_token; }} catch (Exception e) {system.err. Printf (" Failed to get token! ") ); e.printStackTrace(System.err); } return null; }}Copy the code
Policy mode – Create the BaiduFaceService interface
public interface BaiduFaceService {
void operation(String phone, String schoolCode, String uid, String name);
}
Copy the code
Write three implementations add/ Update /delete class BaiduFaceService, and implement InitializingBean initialization execution.
Policy Pattern – The new implementation class writes the new business logic
@Service public class BaiduFaceAddServiceImpl implements BaiduFaceService, InitializingBean { @Autowired private AuthService authService; @Override public void operation(String phone, String schoolCode, String uid, String name) { FaceAdd.add(authService.getAuth(), phone, schoolCode, uid, name); } /** * @auther leichunhong * @desc @date 2020-09-22 19:20 * @param * @return void */ @override public void afterPropertiesSet() throws Exception { BaiduFaceFactory.registerBaiduFace(UtilEnumCode.ENUM_A_VSAFECODE.getCode(), this); }}Copy the code
The Policy Pattern – Change implementation class is primarily the business logic that implements the changes
@Service public class BaiduFaceUpdateServiceImpl implements BaiduFaceService, InitializingBean { @Autowired private AuthService authService; @Override public void operation(String phone, String schoolCode, String uid, String name) { FaceUpdate.faceUpdate(authService.getAuth(), phone, schoolCode, uid, name); } /** * @auther leichunhong * @desc @date 2020-09-22 19:20 * @param * @return void */ @override public void afterPropertiesSet() throws Exception { BaiduFaceFactory.registerBaiduFace(UtilEnumCode.ENUM_U_VSAFECODE.getCode(), this); }}Copy the code
Policy pattern – The deletion implementation class is the business logic to be deleted
@Service public class BaiduFaceDeleteServiceImpl implements BaiduFaceService, InitializingBean { @Autowired private AuthService authService; @Override public void operation(String phone, String schoolCode, String uid, String name) { FaceDelete.faceDelete(authService.getAuth(), phone, schoolCode, uid); } /** * @auther leichunhong * @desc @date 2020-09-22 19:20 * @param * @return void */ @override public void afterPropertiesSet() throws Exception { BaiduFaceFactory.registerBaiduFace(UtilEnumCode.ENUM_D_VSAFECODE.getCode(), this); }}Copy the code
Policy mode – Static factory is actually a key, value structure key is add/update/delete. Value is the three implementation classes above. According to different key(add/ Update /delete) take different implementation classes, tune different methods.
/** * < function description > <br> * < > Static factory report operation type and operation implementation class * Add --> BaiduFaceAddServiceImpl * * @author Leichunhong * @create 2020-09-22 * @since 1.0.0 */ public class BaiduFaceFactory { private static Map<String, BaiduFaceService> baiduFaceMap = new HashMap<>(); private BaiduFaceFactory() { } private static final BaiduFaceService EMPTY = new EmptyBaiduFace(); /** * @param * @return cn.thinkjoy.springboot.rest.business.service.BaiduFaceService * @auther leichunhong * @desc * @date 2020-09-22 19:23 */ public static BaiduFaceService getBaiduFace(String state) {BaiduFaceService result = baiduFaceMap.get(state); return result == null ? EMPTY : result; } /** * @param * @return * @auther leichunhong * @desc * @date 2020-09-22 19:22 */ public static void registerBaiduFace(String state, BaiduFaceService o) { baiduFaceMap.put(state, o); } /** * @param * @auther leichunhong * @desc null object * @date 2020-09-22 19:22 * @return */ private static class EmptyBaiduFace implements BaiduFaceService { @Override public void operation(String phone, String schoolCode, String uid, String name) { // Empty class } } }Copy the code
Enumeration utility class for key
public enum UtilEnumCode { ENUM_A_VSAFECODE("A", "add"), ENUM_U_VSAFECODE("U", "update"), ENUM_D_VSAFECODE("D", "delete"), SCHOOL_PRO_TYPE("test","test"); /** The code. */ private final String code; /** The message. */ private final String message; /** * Instantiates a new error type. * * @param code * the code * @param message * the message */ private UtilEnumCode(String code, String message) { this.code = code; this.message = message; } /** * Gets the code. * * @return the code */ public String getCode() { return code; } /** * Gets the message. * * @return the message */ public String getMessage() { return message; }}Copy the code
Policy pattern – Interface invocation after the policy pattern is applied
@getMapping (value = "/new") public String test(String state) {add/update /delete BaiduFaceService baiduFaceService = BaiduFaceFactory.getBaiduFace(state); BaiduFaceService. Operation (" * * * 153 * 7719 ", "123456", "98989897", "teachers"); return "succ"; }Copy the code
Note: Without the if judgment, the code is only two lines.
conclusion
The number of lines of business code is reduced, but the actual business code is put in the implementation class. The actual code volume is actually increased, and the logic and reading of the code is increased. You win some, you lose some.