Green line and a validation framework hand, API parameter calibrating no fear!

 

High probability of you have learned to copy the code, paste the code invincible magic farmers, in fact, doing a long time business development function, he learned that two invincible magic, that sooner or later thing. Today the first to throw a small problem to get through your Renduermai, is very curious to ask: business development function, the input parameters checking account how much time do you? Have you considered how to verify modular, universal?

 

We still another question is asked, a look-membered aromatic how to see. "In the end how to ensure API robustness of the business," Yuan Fang how you look like?

 

Concerned about "a small ape stresses" the long-membered aromatic, more or less a little progress, so to answer without thinking: first of all to ensure that the calibration API input parameters; then ......

 

Hear "first of all to ensure that the calibration API input parameters", it is necessary to Yuan Fang play out, because he forced open our topic today.

 

Well, prepare a small bench, let's look at how to Fun, raw line and a framework API parameter check.

1. 

Conventional writing.

 

640?wx_fmt=png

 

Note: The code above screenshot I only used to give Li explained, the information in the temporary return to write the dead, should dynamically set the return code and return the package as described JSON return.

 

The figure code chestnuts, but also many newcomers favorite way to use, after all, in the eyes of the program ape entering the workplace, wrong to think that "the amount of code is money", it may be in SVN or Git you want to retain more than updating records because update records is to reflect the amount of code and labor ah (Wuzui laughs).

 

But often a simple API interface only two input parameters, as many as dozens of parameters, it would mean that a lot of code space, are conducting parameter check, is it will spend a lot of time and effort, the parameter checking in.

 

In fact, the API interface parameters into the check steps, we can be divided into: get interface input parameters; check will pass parameters are passed; verify that the parameters conform to the rules.

 

In fact, once the law is found, the machine can be handed over to do it, then we can certainly create an efficient wheels API parameter check.

 

2. 

What should be the composition of the wheels?

 

A. Configuration parameters into the interface;

B. Configuration parameter validation rules;

C. Packaging parameter verification error code on failure and abnormality information;

 

Thinking combination of the above, let's draw a simple flow chart it on a map just seconds to understand.

640?wx_fmt=png

 

3. 

Wheels ye should achieve?

 

A. Definitions API interface parameters into the configuration file param.properties

######## business functions robustness parameter rule configuration ############################	 
# = Param group Interface parameters (according | division parameter set parameter, each separated by a comma in accordance)	 
################################### #######################	 
Interface system configuration parameters required # (PARAMS.apiURL = parameter list)	 
PARAMS./sys/login.do=username,password

  

B. Definitions API interface parameters of the regular check regex.properties

######## business functions robustness rules configuration parameters ############################	 
# interface parameters of the regular expression (PARAMS. Interface URL. .regex = regular expression parameter)	 
PARAMS./sys/login.do.username.regex=\\w{1,32}	 
# global parameters of the regular expression (regex parameters .regex = )	 
password.regex \\ W = {1,32}

  

Students start line and Code C.

STEP 1: How to obtain an interface corresponding to the parameter configuration request according to api.

 

640?wx_fmt=png

 

Step two: Verify the value of the parameter passed in compliance with the rules. Since each API supports multiple sets of parameters passed in the case, it is possible to follow | division multiple sets of parameters "."

 

640?wx_fmt=png

 

The third step: verifying whether the value of the parameter passed in accordance with the rules, the real validation logic.

 

640?wx_fmt=png

 

Step 4: According to our flowchart, the above method string together into a package-Service, like where used, where a, So Easy! ! ! Wherein the method doService parameters, apiUrl interface is url, json parameter is passed.

 

640?wx_fmt=png

 

Or should the main code share to you, so you better progress.

com.alibaba.fastjson.JSONObject Import; 
Import org.apache.commons.lang3.ArrayUtils; 
Import org.apache.commons.lang3.StringUtils; 

/ ** 
 * check service request parameter 
 * desc: 
 *. 1, by passing the apiUrl find the data <b> (param.properties) </ b> to be verified, 
 * 2, Key parameters passed to find the corresponding regular expression <B> (regex.properties) </ B>, 
 *. 3 , data to be verified for the regular expression <B> 
 *. 4, optional support required field validation 
 * / 
public class RequestParamCheckService { 

    public static REGKEY Final String = "PARAMS."; 
    public static String REGEX = Final " .regex "; 

    public void the doService (String apiUrl, JSONObject json) { 
        . 1 // API URL check whether incoming 
        iF (StringUtils.isEmpty (apiUrl)) {
        } 
            System.out.println("Miss api url");
            return; 
        // 2 The configuration API URL acquisition parameters. 
        String paramKeyConf = StringUtils.trim (getKeyByApiUrl (apiUrl)); 
        IF (StringUtils.isEmpty (paramKeyConf)) { 
            System.out.println (String.format ( "% S found check info NO ", apiUrl)); 
            return; 
        } 
        // parameter passed verification value. 3 meets the configuration rule definition. 
        Boolean [] = validateAry the validate (apiUrl, paramKeyConf, JSON); 
        .. 4 // check calibration parameters experimental results 
        IF {(ArrayUtils.contains (validateAry, to true)!) 
            System.out.println (String.format ( "% S param the validate Fail", apiUrl)); 
            // needs to acquire the TODO here according to a corresponding return code field and return information may be expanded to achieve about themselves, this hard-coded 
            throw new ValidateException ( "99999999", " parameter verification fails");
        } 
    } 
 
    / ** 
     * the parameter value passed validation rule meets the configuration definition
     * 
     * @Param apiUrl Interface 
     * @param paramKeyConf configuration parameters Key 
     * @param json json incoming packet content 
     * @return verification result 
     * / 
    Private Boolean [] the validate (apiUrl String, String paramKeyConf, the JSONObject json) { 
        // the partition KEY 
        String [] chkKeys = paramKeyConf.split ( " \\ |"); 
        if the parameter is determined split combination arrangement // 
        // verify for each set of parameters passed, the conclusion that parameters passed the correct 
        Boolean [] = validateAry new new Boolean [chkKeys.length]; 
        for (int I = 0; I <chkKeys.length; I ++) {// for each set of parameters for authentication 
            String [] unitKeyAry = chkKeys [i ] .split ( ","); // in accordance with the configuration parameters of each split key comma 
            validateAry [i] = check (apiUrl , json, unitKeyAry); // check whether the parameters meet the rules 
        }
        validateAry return; 
    } 

    / ** 
     * check whether the rule parameter passed 
     * 
     * @param apiUrl check apiUrl 
     * @param json json incoming message data 
     * @param keyAry parameter array 
     * @return check result 
     * / 
    Private Boolean Check (String apiUrl, the JSONObject JSON, String [] keyAry) { 
        // verify by default is true by 
        Boolean = true isCheckSucc; 
        for (String unitKey: keyAry) { 
            // split in parentheses, is necessary to distinguish between fill or optional, will be carried out to verify the parameters passed in the regular 
            // get "(" the first occurrence of 
            boolean isOptional = isOptionalParam (unitKey); 
                unitKey = removBrackets (unitKey); 
            } 
            // pass non-essential
            IF (isOptional) { 
            // for each set of parameters necessary for the transmission check, format check for each set of parameters 
            IF (Check (apiUrl, unitKey, JSON, isOptional)!!) { 
                // validation fails 
                isCheckSucc = to false; 
                BREAK ; 
            } 
        } 
        return isCheckSucc; 
    } 

    / ** 
     * apiUrl key read from the configuration file according to the 
     * 
     * @param apiUrl 
     * @return apiUrl corresponding to the configuration parameters 
     * / 
    public String getKeyByApiUrl (String apiUrl) { 
        // example: apiUrl request the key is to /sys/login.do PARAMS./sys/login.do 
        // wherein the value of a parameter corresponding apiUrl username, password 
        return ConfigUtils.getConfig (apiUrl REGKEY +); 
    } 

    / ** 
     * reads the parameters corresponding to n from the profile according to the apiUrl 
     * 
     * @param apiUrl 
     * @return 
     * / 
    public String getKeyRegex (apiUrl String, String paramKey) { 
        // The priority PARAMS. Interface URL. .Regex acquisition parameters corresponding to the regular key validation rules 
        String key = REGKEY + "." apiUrl + + + paramKey REGEX; 
        // Get the TODO n the key profile reading regex.properties expression 
        String keyRegex = StringUtils.trim (ConfigUtils.getConfig (key)); 
        IF (StringUtils.isEmpty (keyRegex)) { 
            // If the Interface URL. .regex is a key parameter does not correspond to regular validation rules according PARAMS 
            // configured to obtain the key directly .regex the parameter regular validation rules 
            keyRegex = ConfigUtils.getConfig (paramKey + REGEX) ; 
        } 
        return keyRegex; 
    }

    / ** 
        } else {
     * The real validation logic, configured by a positive expressions check field for compliance 
     * 
     * @param apiUrl interface to be verified the URL of 
     * @param paramKey parameters Key 
     * @param json json incoming message string 
     * @param whether mUST will pass parameters 
     * @return verification result 
     * / 
    protected Boolean Check (apiUrl String, String paramKey, the JSONObject JSON, Boolean mUST) { 
        String value = StringUtils.trim (json.getString (paramKey)); 
        iF (StringUtils.isEmpty ( value)) { 
            // must pass field is empty, the verification Fail 
            IF (mUST) { 
                System.out.println (String.format ( "% S iS empty the Request the Parameter", paramKey)); 
                return to false; 
            }
            GetKeyRegex REGEX = String (apiUrl, paramKey); 
            IF (StringUtils.isEmpty (REGEX)) { 
                System.out.println (String.format ( "% S found the Request the Parameter NO REGEX info", paramKey)); 
                return to true; 
            } 
            / / remove the space character 
            value = value.replaceAll ( "\\ S *", ""); 
            // do not meet the regular expression 
            (! value.matches (regex)) IF { 
                System.out.println (String.format ( " the Parameter% S the Request [% S] the CAN Not match REGEX [% S] ", paramKey, value, REGEX)); 
                return to false; 
            } 
        } 
        return to true; 
    } 

    / ** 
     * remove the brackets
     *
     * @Param key to be verified Key 
     * @return string removed in parentheses 
     * / 
    Private removBrackets String (String Key) { 
        return key.substring (. 1, key.length () -. 1); 
    } 

    / ** 
     * Are is required field 
     * 
     * @param be verified Key Key 
     * @return field must return <tt> true </ tt> , otherwise <TT> to false </ TT> 
     * / 
    Private Boolean isOptionalParam (String Key) { 
        return key.startsWith ( "[") && key.endsWith ( "]"); 
    } 
}

  

Well, time is not late, life line and validation framework to share here, in fact, there are many details to say no in-depth, but generally speaking the idea, but the code has been written comments is very clear. If you can ever understand, and apply in the actual project, it will certainly greatly enhance the development efficiency, freeing up more time to make coffee.

 

After reading this article hardcore, understand and do not understand, are like him thumbs up, collection, sharing, because every casual operation thy God, I seriously as a favorite.

 

 

Guess you like

Origin www.cnblogs.com/socoool/p/12629777.html