Van333
2022-10-26 f7debb464a2d49b6e66b014cf2beef2a9c4bf98d
参数调整
已添加5个文件
445 ■■■■■ 文件已修改
src/main/java/api/bean/PoleLightBatchEntity.java 31 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/api/controller/PoleController.java 141 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/api/service/PoleService.java 25 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/api/utils/CommonHeader.java 31 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/api/utils/HttpUtil.java 217 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/api/bean/PoleLightBatchEntity.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,31 @@
package api.bean;
import lombok.Data;
import java.io.Serializable;
/**
 * @author van
 * @version 1.0
 * msg:
 * @date 2022/6/6 14:37
 */
@Data
public class PoleLightBatchEntity implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long[] streetlightIds;
    private Integer operate;
    private Long programId;
    private Integer scheduleId;
    private Integer lightLevel;
    private Integer lightNumber;
    private Long[] adIds;
}
src/main/java/api/controller/PoleController.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,141 @@
package api.controller;
import api.bean.PoleLightBatchEntity;
import api.bean.ReqParams;
import api.result.Msg;
import api.service.AccessService;
import api.service.PoleService;
import api.utils.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.util.concurrent.RateLimiter;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
 * @author van
 * @version 1.0
 * msg:单灯控制层
 * @date 2021/11/2 15:04
 */
@RestController
@RequestMapping("/pole")
public class PoleController {
    @Autowired
    private AccessService accessService;
    RateLimiter rateLimiter = RateLimiter.create(10.0);
    @RequestMapping(value = "polestreetlight/listWithNotStatus",method = RequestMethod.POST)
    public Msg listWithNotStatus(@RequestBody ReqParams reqParams){
        rateLimiter.acquire(1);
        if (reqParams.getLimit()>50){
            return Msg.error("limit exception!!!");
        }
        Long userId = accessService.getUserId(reqParams.getAccessToken());
        if(userId == null){
            return Msg.error("accessToken exception!!!");
        }
        reqParams.setApiKey(reqParams.getApiKey());
        reqParams.setUserId(userId);
        String result = HttpUtil.Post(
                "http://127.0.0.1:8888/machine-fast/serv/api/pole/polestreetlight/listWithNotStatus",
                new Gson().toJson(reqParams)
        );
        Map msg = JSON.parseObject(result, HashMap.class);
        if (msg.get("msg").equals("success")){
            return Msg.ok().put("data",msg.get("data"));
        }
        else {
            return Msg.error(msg.get("msg").toString());
        }
    }
    @RequestMapping(value = "polestreetlight/getStatusById",method = RequestMethod.POST)
    public Msg getStatusById(@RequestBody ReqParams reqParams){
        rateLimiter.acquire(1);
        Long userId = accessService.getUserId(reqParams.getAccessToken());
        if(userId == null){
            return Msg.error("accessToken exception!!!");
        }
        reqParams.setApiKey(reqParams.getApiKey());
        reqParams.setUserId(userId);
        String result = HttpUtil.Post(
                "http://127.0.0.1:8888/machine-fast/serv/api/pole/polestreetlight/getStatusById",
                new Gson().toJson(reqParams)
        );
        Map msg = JSON.parseObject(result, HashMap.class);
        if (msg.get("msg").equals("success")){
            return Msg.ok().put("data",msg.get("data"));
        }
        else {
            return Msg.error(msg.get("msg").toString());
        }
    }
    @RequestMapping(value = "polestreetlight/lightBatch",method = RequestMethod.POST)
    public Msg list(@RequestBody ReqParams reqParams){
        rateLimiter.acquire(1);
        Long userId = accessService.getUserId(reqParams.getAccessToken());
        if(userId == null){
            return Msg.error("accessToken exception!!!");
        }
        reqParams.setApiKey(reqParams.getApiKey());
        reqParams.setUserId(userId);
        PoleLightBatchEntity poleLightBatch = new PoleLightBatchEntity();
        poleLightBatch.setAdIds(reqParams.getPoleLightBatch().getStreetlightIds());
        poleLightBatch.setLightNumber(reqParams.getPoleLightBatch().getLightNumber());
        poleLightBatch.setLightLevel(reqParams.getPoleLightBatch().getLightLevel());
        reqParams.setPoleLightBatch(poleLightBatch);
        String result = HttpUtil.Post(
                "http://127.0.0.1:8888/machine-fast/serv/api/pole/polestreetlight/lightBatch",
                new Gson().toJson(reqParams)
        );
        Map msg = JSON.parseObject(result, HashMap.class);
        assert msg != null;
        if (msg.get("msg").equals("success")){
            return Msg.ok().put("data",msg.get("data"));
        }
        else {
            return Msg.error(msg.get("msg").toString());
        }
    }
}
src/main/java/api/service/PoleService.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,25 @@
package api.service;
import api.bean.LampEntity;
import api.bean.ReqParams;
import api.bean.WeatherEntity;
import api.dao.LampDao;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
 * @author van
 * @version 1.0
 * msg:单灯控制
 * @date 2021/11/2 10:24
 */
@Service("lampService")
public class PoleService {
    @Autowired
    private AccessService accessService;
}
src/main/java/api/utils/CommonHeader.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,31 @@
package api.utils;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
/**
 * @author van
 * @version 1.0
 * msg:
 * @date 2022/6/6 15:01
 */
@Data
public class CommonHeader extends HashMap<String, String> {
    private static Logger logger = LoggerFactory.getLogger(CommonHeader.class);
    public static final String FORM = "form";
    public static final String JSON = "json";
    public CommonHeader(String type,boolean hasToken){
        if(type.equals(FORM)) {
            super.put("Content-Type","application/x-www-form-urlencoded");
        } else if(type.equals(JSON)) {
            super.put("Content-Type","application/json");
        }
        }
}
src/main/java/api/utils/HttpUtil.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,217 @@
package api.utils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
/**
 * @author  van
 * @date  2022/6/6 11:59
 * @version 1.0
 * msg:
 */public class HttpUtil {
    private static final String UTF8 = "utf-8";
    public static String get(String url){
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        String result = null;
        try {
            HttpResponse httpResponse = client.execute(get);
            InputStream inStream = httpResponse.getEntity().getContent();
            result = streamToString(inStream,UTF8);
            inStream.close();
        } catch (Exception e) {
            return null;
        }
        return result;
    }
    public static String GetWithHeader (String url, List<NameValuePair> urlParameters, Map<String, String> header) throws URISyntaxException {
        URI finalURI = new URIBuilder(url).setParameters(urlParameters).build();
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet get = new HttpGet(finalURI);
        for(String key: header.keySet()) {
            get.setHeader(key, header.get(key));
        }
        String result = null;
        try {
            HttpResponse httpResponse = client.execute(get);
            InputStream inStream = httpResponse.getEntity().getContent();
            result = streamToString(inStream, UTF8);
            inStream.close();
        } catch (Exception e) {
            return null;
        }
        return result;
    }
    public static String PostWithHeader (String URL, String json, Map<String, String> header) {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(URL);
        for(String key: header.keySet()) {
            post.setHeader(key, header.get(key));
        }
        String result = null;
        try {
            StringEntity s = new StringEntity(json, UTF8);
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            post.setEntity(s);
            HttpResponse httpResponse = client.execute(post);
            InputStream inStream = httpResponse.getEntity().getContent();
            result = streamToString(inStream,UTF8);
            inStream.close();
        } catch (Exception e) {
            return null;
        }
        return result;
    }
    public static String Post (String URL, String json) {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(URL);
        String result = null;
        try {
            StringEntity s = new StringEntity(json, UTF8);
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            s.setContentType("application/json");
            post.setEntity(s);
            HttpResponse httpResponse = client.execute(post);
            InputStream inStream = httpResponse.getEntity().getContent();
            result = streamToString(inStream,UTF8);
            inStream.close();
        } catch (Exception e) {
            return null;
        }
        return result;
    }
    public static String streamToString(InputStream in, String encoding){
        // å°†æµè½¬æ¢ä¸ºå­—符串
        try {
            StringBuffer sb = new StringBuffer();
            byte[] b = new byte[1024];
            for (int n; (n = in.read(b)) != -1;) {
                sb.append(new String(b, 0, n, encoding));
            }
            return sb.toString();
        }  catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("提取 requestBody å¼‚常", e);
        }
    }
    /**
     * <pre>
     * æ–¹æ³•体说明:向远程接口发起请求,返回字符串类型结果
     * @param url æŽ¥å£åœ°å€
     * @param requestMethod è¯·æ±‚类型
     * @param params ä¼ é€’参数
     * @return String è¿”回结果
     * </pre>
     */
    public static String httpRequestToString(String url, String requestMethod, Map<String, String> params){
        //接口返回结果
        String methodResult = null;
        try {
            String parameters = "";
            boolean hasParams = false;
            //将参数集合拼接成特定格式,如name=zhangsan&age=24
            for(String key : params.keySet()){
                String value = URLEncoder.encode(params.get(key), "UTF-8");
                parameters += key +"="+ value +"&";
                hasParams = true;
            }
            if(hasParams){
                parameters = parameters.substring(0, parameters.length()-1);
            }
            //是否为GET方式请求
            boolean isGet = "get".equalsIgnoreCase(requestMethod);
            boolean isPost = "post".equalsIgnoreCase(requestMethod);
            boolean isPut = "put".equalsIgnoreCase(requestMethod);
            boolean isDelete = "delete".equalsIgnoreCase(requestMethod);
            //创建HttpClient连接对象
            DefaultHttpClient client = new DefaultHttpClient();
            HttpRequestBase method = null;
            if(isGet){
                url += "?" + parameters;
                method = new HttpGet(url);
            }else if(isPost){
                method = new HttpPost(url);
                HttpPost postMethod = (HttpPost) method;
                StringEntity entity = new StringEntity(parameters);
                postMethod.setEntity(entity);
            }else if(isPut){
                method = new HttpPut(url);
                HttpPut putMethod = (HttpPut) method;
                StringEntity entity = new StringEntity(parameters);
                putMethod.setEntity(entity);
            }else if(isDelete){
                url += "?" + parameters;
                method = new HttpDelete(url);
            }
            method.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);
            //设置参数内容类型
            method.addHeader("Content-Type","application/x-www-form-urlencoded");
            //httpClient本地上下文
            HttpClientContext context = null;
            context = HttpClientContext.create();
            //访问接口,返回状态码
            HttpResponse response = client.execute(method, context);
            //返回状态码200,则访问接口成功
            if(response.getStatusLine().getStatusCode()==200){
                methodResult = EntityUtils.toString(response.getEntity());
            }
            client.close();
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return methodResult;
    }
}