From 8fa8df4fbb39e4ca98d5dee69cf4f334f4bde057 Mon Sep 17 00:00:00 2001 From: 13693261870 <252740454@qq.com> Date: 星期四, 05 十月 2023 11:06:37 +0800 Subject: [PATCH] 添加web工具类 --- src/main/java/com/smartearth/poiexcel/entity/StaticData.java | 330 +++++++++++++++++ src/main/java/com/smartearth/poiexcel/service/EntService.java | 64 +++ src/main/java/com/smartearth/poiexcel/config/RestTemplateConfig.java | 100 +++++ src/main/java/com/smartearth/poiexcel/utils/HttpHelper.java | 273 ++++++++++++++ src/main/java/com/smartearth/poiexcel/utils/SpringContextHelper.java | 86 ++++ src/main/java/com/smartearth/poiexcel/utils/RestHelper.java | 267 ++++++++++++++ pom.xml | 6 7 files changed, 1,125 insertions(+), 1 deletions(-) diff --git a/pom.xml b/pom.xml index cc6dc14..9f562fe 100644 --- a/pom.xml +++ b/pom.xml @@ -116,6 +116,7 @@ <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> + <!--mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> @@ -143,6 +144,11 @@ <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> + <!--httpclient--> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + </dependency> </dependencies> <build> diff --git a/src/main/java/com/smartearth/poiexcel/config/RestTemplateConfig.java b/src/main/java/com/smartearth/poiexcel/config/RestTemplateConfig.java new file mode 100644 index 0000000..241b3c2 --- /dev/null +++ b/src/main/java/com/smartearth/poiexcel/config/RestTemplateConfig.java @@ -0,0 +1,100 @@ +package com.smartearth.poiexcel.config; + +import org.apache.http.client.HttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.ClientHttpRequestFactory; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.http.client.SimpleClientHttpRequestFactory; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.StringHttpMessageConverter; +import org.springframework.web.client.RestTemplate; + +import java.nio.charset.StandardCharsets; +import java.util.List; + +/** + * Rest妯℃澘閰嶇疆绫� + * @author WWW + */ +@Configuration +@ConditionalOnClass(value = {RestTemplate.class, HttpClient.class}) +public class RestTemplateConfig { + /** + * 杩炴帴姹犵殑鏈�澶ц繛鎺ユ暟榛樿涓�0锛屼笉闄愬埗 + */ + @Value("${remote.maxTotalConnect:0}") + private int maxTotalConnect; + + /** + * 鍗曚釜涓绘満鐨勬渶澶ц繛鎺ユ暟 + */ + @Value("${remote.maxConnectPerRoute:1000}") + private int maxConnectPerRoute; + + /** + * 杩炴帴瓒呮椂榛樿5s锛�-1涓轰笉闄愬埗 + */ + @Value("${remote.connectTimeout:5000}") + private int connectTimeout; + + /** + * 璇诲彇瓒呮椂榛樿30s锛�-1涓轰笉闄愬埗 + */ + @Value("${remote.readTimeout:30000}") + private int readTimeout; + + /** + * 鍒涘缓HTTP瀹㈡埛绔伐鍘� + * + * @return 瀹㈡埛绔伐鍘� + */ + private ClientHttpRequestFactory createFactory() { + if (this.maxTotalConnect <= 0) { + SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); + factory.setConnectTimeout(this.connectTimeout); + factory.setReadTimeout(this.readTimeout); + return factory; + } + + HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(this.maxTotalConnect).setMaxConnPerRoute(this.maxConnectPerRoute).build(); + + HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); + factory.setConnectTimeout(this.connectTimeout); + factory.setReadTimeout(this.readTimeout); + + return factory; + } + + /** + * 鍒濆鍖朢estTemplate,骞跺姞鍏pring鐨凚ean宸ュ巶锛岀敱spring缁熶竴绠$悊 + * 蹇呴』鍔犳敞瑙LoadBalanced + * + * @return + */ + @Bean + @ConditionalOnMissingBean(RestTemplate.class) + public RestTemplate getRestTemplate() { + RestTemplate restTemplate = new RestTemplate(this.createFactory()); + List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters(); + + // 閲嶆柊璁剧疆StringHttpMessageConverter瀛楃闆嗕负UTF-8锛岃В鍐充腑鏂囦贡鐮侀棶棰� + HttpMessageConverter<?> converterTarget = null; + for (HttpMessageConverter<?> item : converterList) { + if (StringHttpMessageConverter.class == item.getClass()) { + converterTarget = item; + break; + } + } + if (null != converterTarget) { + converterList.remove(converterTarget); + } + converterList.add(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); + + return restTemplate; + } +} diff --git a/src/main/java/com/smartearth/poiexcel/entity/StaticData.java b/src/main/java/com/smartearth/poiexcel/entity/StaticData.java new file mode 100644 index 0000000..6f977bd --- /dev/null +++ b/src/main/java/com/smartearth/poiexcel/entity/StaticData.java @@ -0,0 +1,330 @@ +package com.smartearth.poiexcel.entity; + +import com.alibaba.fastjson.JSON; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * 闈欐�佹暟鎹被 + * @author WWW + */ +public class StaticData { + /** + * 鏉冮檺鎺掗櫎璺緞锛�/proxy锛岃姹傚叏閮ㄥ皬鍐� + */ + public static String[] EXCLUDE_PATH = new String[]{"/sign/", "/perms/", "/floatserver/", "/proxy/", "/swagger", "/error"}; + + public final static int I0 = 0; + + public final static int I1 = 1; + + public final static int I2 = 2; + + public final static int I3 = 3; + + public final static int I4 = 4; + + public final static int I5 = 5; + + public final static int I6 = 6; + + public final static int I8 = 8; + + public final static int NINE = 9; + + public final static int TEN = 10; + + public final static int SIXTEEN = 16; + + public final static int ONE_HUNDRED = 100; + + public final static int TWO_HUNDRED = 200; + + public final static int ONE_HUNDRED_THOUSAND = 100000; + + public static final double D05 = 0.05; + + public static final double D90 = 90.0; + + public static final double D100 = 100.0; + + public static final double D1024 = 1024.0; + + public static final double D1050 = 1050.0; + + public static final int I12 = 12; + + public static final int I23 = 23; + + public static final int I24 = 24; + + public static final int I31 = 31; + + public static final int I50 = 50; + + public static final int I60 = 60; + + public static final int I64 = 64; + + public static final int I90 = 90; + + public static final int I90_NEG = -90; + + public final static int I100 = 100; + + public static final int I120 = 120; + + public static final int I180 = 180; + + public static final int I180_NEG = -180; + + public static final int I200 = 200; + + public static final int I500 = 500; + + public static final int I1000 = 1000; + + public static final int I1024 = 1024; + + public static final int I2050 = 2050; + + public static final int I4326 = 4326; + + public static final int I4490 = 4490; + + public static final int I104903 = 104903; + + public final static String S1 = "1"; + + public final static String EQ = "="; + + public final static String POINT = "."; + + public final static String COMMA = ","; + + public final static String TILDE = "~"; + + public final static String QUESTION = "?"; + + public final static String BACKSLASH = "\\\\"; + + public final static String SINGLE_QUOTES = "'"; + + public final static String BBOREHOLE = "bborehole"; + + public final static String AK = "?ak="; + + public final static String REST_LAYER = "/v6/rest/"; + + public final static String TEXT_XML = "text/xml"; + + public final static String SLASH = "/"; + + public final static String IN = "in"; + + public final static String ZIP = ".zip"; + + public final static String XLS = ".xls"; + + public final static String XLSX = ".xlsx"; + + public final static String MDB = ".mdb"; + + public final static String SHP = ".shp"; + + public final static String NGDB = "gdb"; + + public final static String GDB = ".gdb"; + + public final static String JPG = ".jpg"; + + public final static String JP2 = ".jp2"; + + public final static String IMG = ".img"; + + public final static String MPT = ".mpt"; + + public final static String D3DML = ".3dml"; + + public final static String TIF = ".tif"; + + public final static String TIFF = ".tiff"; + + public final static String LAS = ".las"; + + public final static String OSGB = ".osgb"; + + public final static String NULL = "null"; + + public static String ADMIN = "admin"; + + public final static String SYS_META = "sysmeta"; + + public final static String VERSION = "1.0.0"; + + public final static String TOKEN_KEY = "token"; + + public final static String TOKEN_COOKIE_KEY = "token"; + + public final static String TEXT_ENCODER = "UTF-8"; + + public final static String CHECK_MAIN = "checkMain"; + + public final static String OBJECT = "java.lang.Object"; + + public final static String DRUID_COOKIE_KEY = "JSESSIONID"; + + public final static String YES = "YES"; + + public final static String NO = "NO"; + + public final static String DOM = "DOM"; + + public final static String LAYERS = "layers"; + + public final static String REQUEST = "request"; + + public final static String SERVICE = "service"; + + public final static String GET_CAPABILITIES = "GetCapabilities"; + + public final static String SUCCESS = "$SUCCESS"; + + public final static String LINESTRING = "LINESTRING"; + + public final static String MULTILINESTRING = "MULTILINESTRING"; + + public final static String POLYGON = "POLYGON"; + + public final static String MULTIPOLYGON = "MULTIPOLYGON"; + + public final static String MULTICURVE = "MULTICURVE"; + + public final static String COMPOUNDCURVE = "COMPOUNDCURVE"; + + public final static String QUERYABLE = "<Layer queryable=\"1\" opaque=\"0\">"; + + public static final String NO_FILE = JSON.toJSONString(new ResponseMsg<String>(HttpStatus.NOT_FOUND, "鏂囦欢鎵句笉鍒�")); + + /** + * 鏈堢悆2000鍧愭爣绯荤殑WKT + */ + public static final String MOON_2000_WKT = "GEOGCS[\"GCS_Moon_2000\",\r\n" + + " DATUM[\"D_Moon_2000\",\r\n" + + " SPHEROID[\"Moon_2000_IAU_IAG\",1737400,0,\r\n" + + " AUTHORITY[\"ESRI\",\"107903\"]],\r\n" + + " AUTHORITY[\"ESRI\",\"106903\"]],\r\n" + + " PRIMEM[\"Reference_Meridian\",0,\r\n" + + " AUTHORITY[\"ESRI\",\"108900\"]],\r\n" + + " UNIT[\"degree\",0.0174532925199433,\r\n" + + " AUTHORITY[\"EPSG\",\"9122\"]],\r\n" + + " AUTHORITY[\"ESRI\",\"104903\"]]"; + + public final static String CGCS2000 = "CGCS2000"; + + public final static String MOON200 = "GCS_Moon_2000"; + + public final static List<String> EPSGS = new ArrayList<>(Arrays.asList("EPSG:4326", "EPSG:4490", "ESRI:104903")); + + /** + * 16杩涘埗 + */ + public static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + + /** + * 瀵嗙爜姝e垯琛ㄨ揪寮� + */ + public final static String PWD_REG = "^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W!@#$%^&*`~()\\-_+=,.?;<>]+$)(?![a-z0-9]+$)(?![a-z\\W!@#$%^&*`~()\\-_+=,.?;<>]+$)(?![0-9\\W!@#$%^&*`~()\\-_+=,.?;<>]+$)[a-zA-Z0-9\\W!@#$%^&*`~()\\-_+=,.?;<>]{12,20}$"; + + /** + * 鏍呮牸鏁版嵁鎵╁睍鍚� + */ + public final static List<String> RASTER_EXT = new ArrayList<>(Arrays.asList(".img", ".tif", ".tiff", ".jpg", ".jp2")); + + /** + * MPT鏂囦欢鎵╁睍鍚� + */ + public final static List<String> MPT_EXT = new ArrayList<>(Arrays.asList(".midx", ".strmi", ".ei.midx", ".ei.mpt", ".ei.strmi")); + + /** + * JPG鏂囦欢鎵╁睍鍚� + */ + public final static List<String> JPG_EXT = new ArrayList<>(Arrays.asList(".jpg.aux.xml", ".jpg.ovr", ".jpg.xml", ".jgw", ".prj")); + + /** + * JP2鏂囦欢鎵╁睍鍚� + */ + public final static List<String> JP2_EXT = new ArrayList<>(Arrays.asList(".jp2.aux.xml", ".jp2.ovr", ".jp2.xml", ".jgw", ".prj", ".jp2.html", ".jp2.txt")); + + /** + * IMG鏂囦欢鎵╁睍鍚� + */ + public final static List<String> IMG_EXT = new ArrayList<>(Arrays.asList(".rrd", ".img.aux.xml", ".hdr", ".img.enp", ".img.xml")); + + /** + * TIF鏂囦欢鎵╁睍鍚� + */ + public final static List<String> TIF_EXT = new ArrayList<>(Arrays.asList(".prj", ".tfw", ".aux", ".tif.ovr", ".tif.aux.xml", ".tif.xml")); + + /** + * TIFF鏂囦欢鎵╁睍鍚� + */ + public final static List<String> TIFF_EXT = new ArrayList<>(Arrays.asList(".prj", ".tfw", ".aux", ".tiff.ovr", ".tiff.aux.xml", ".tiff.xml")); + + /** + * SHP鏂囦欢鎵╁睍鍚� + */ + public final static List<String> SHP_EXT = new ArrayList<>(Arrays.asList(".shx", ".dbf", ".prj", ".cpg")); + + /** + * Mapper鎺掗櫎鎵╁睍鍚� + */ + public final static List<String> MAPPER_EXCLUDE_EXT = new ArrayList<>(Arrays.asList(".jpg.aux.xml", ".jpg.xml", ".jp2.aux.xml", ".jp2.xml", ".jp2.html", ".jp2.txt", ".img.aux.xml", ".img.xml", ".tif.aux.xml", ".tif.xml", ".tiff.aux.xml", ".tiff.xml", ".shp.xml", ".ecw.xml", "ecw.aux.xml")); + + /** + * 鎵�鏈夋枃浠舵墿灞曞悕 + */ + public final static List<String> ALL_EXTENSION = new ArrayList<>(Arrays.asList(".txt", ".xml", ".pdf", ".xls", ".xlsx", ".doc", ".docx", ".ppt", ".pptx", ".shp", ".gdb", ".mdb", ".dwg", ".las", ".laz", ".cpt", ".mpt", ".ei.mpt", ".fly", ".efb", ".g3d", ".fbx", ".obj", ".3dm", ".3dml", ".osgb", ".rvt", ".ifc", ".jpg", ".jp2", ".png", ".img", ".tif", ".tiff", ".dem", ".bmp", ".gif", ".rmvb", ".rm", ".mp3", ".mp4", ".avi", ".wma", ".wmv", ".7z", ".rar", ".zip", ".csv")); + + /** + * 鎻掑叆鎺掗櫎瀛楁 + */ + public final static List<String> INSERT_EXCLUDE_FIELDS = new ArrayList<>(Arrays.asList("gid", "objectid", "updateuser", "updatetime", "shape_leng", "shape_area", "serialVersionUID", "dirName", "depName", "verName", "createName", "updateName")); + + /** + * 鏇存柊鎺掗櫎瀛楁 + */ + public final static List<String> UPDATE_EXCLUDE_FIELDS = new ArrayList<>(Arrays.asList("objectid", "createuser", "createtime", "shape_leng", "shape_area", "serialVersionUID", "dirName", "depName", "verName", "createName", "updateName")); + + /** + * 璇诲彇鎺掗櫎瀛楁 + */ + public final static List<String> READ_EXCLUDE_FIELDS = new ArrayList<>(Arrays.asList("gid", "eventid", "parentid", "objectid", "dirid", "depid", "verid", "createtime", "createuser", "updateuser", "updatetime", "shape_leng", "shape_area", "serialversionuid", "dirname", "depname", "vername", "createname", "updatename")); + + /** + * MDB鎺掗櫎瀛楁 + */ + public final static List<String> MDB_EXCLUDE_FIELDS = new ArrayList<>(Arrays.asList("Shape", "SHAPE_LENG", "Shape_Length", "Shape_Area", "OBJECTID_1")); + + /** + * 鏍囩粯Shp鎺掗櫎瀛楁 + */ + public final static List<String> MARK_EXCLUDE_FIELDS = new ArrayList<>(Arrays.asList("wkt", "geom", "objectid", "shape_leng", "shape_area", "serialVersionUID", "dirName", "depName", "verName", "createName", "updateName")); + + /** + * GDB鎺掗櫎瀛楁 + */ + public final static List<String> GDB_EXCLUDE_FIELDS = new ArrayList<>(Arrays.asList("geom", "objectid", "shape_leng", "shape_area", "serialVersionUID", "dirName", "depName", "verName", "createName", "updateName")); + + /** + * 绠$嚎鍒嗘瀽琛ㄥ悕闆嗗悎 + */ + public final static List<String> PIPE_ANALYSIS_TABS = new ArrayList<>(Arrays.asList("bd.dlg_25w_hydl", "bd.dlg_25w_lrdl", "bd.dlg_25w_lrrl", "bd.dlg_25w_hyda")); + + /** + * 绠$嚎鎺掗櫎瀛楁 + */ + public final static List<String> PIPE_EXCLUDE_FIELDS = new ArrayList<>(Arrays.asList("serialVersionUID", "tabs", "pwd", "gid", "wkt")); +} diff --git a/src/main/java/com/smartearth/poiexcel/service/EntService.java b/src/main/java/com/smartearth/poiexcel/service/EntService.java index 3315d09..9461693 100644 --- a/src/main/java/com/smartearth/poiexcel/service/EntService.java +++ b/src/main/java/com/smartearth/poiexcel/service/EntService.java @@ -1,9 +1,18 @@ package com.smartearth.poiexcel.service; import com.smartearth.poiexcel.mapper.EntMapper; +import com.smartearth.poiexcel.utils.RestHelper; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.*; import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; /** * 浼佷笟鏈嶅姟绫� @@ -15,5 +24,58 @@ @Resource EntMapper entMapper; - // + @Value("${qylweb.url}") + String qylwebUrl; + + private final static Log log = LogFactory.getLog(EntService.class); + + + /** + * post璇锋眰锛圧est锛� + */ + public <T> T postForRest(String url, Map<String, Object> map, Class<T> clazz) { + RestTemplate rest = RestHelper.getRestTemplate(); + + return rest.postForObject(url, map, clazz); + } + + /** + * delete璇锋眰锛圧est锛� + */ + public Object deleteForRest(String url, Map<String, Object> map) { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + + HttpEntity<?> entity = new HttpEntity<>(map, headers); + + RestTemplate rest = RestHelper.getRestTemplate(); + ResponseEntity<Object> rs = rest.exchange(url, HttpMethod.DELETE, entity, Object.class); + + return rs.getBody(); + } + + /** + * 鑾峰彇Map鏁版嵁 + */ + public <T> Map<String, Object> getMapData(T t) { + Map<String, Object> map = new HashMap<>(1); + + Field[] fields = t.getClass().getDeclaredFields(); + for (Field field : fields) { + try { + if ("serialVersionUID".equals(field.getName())) { + continue; + } + + field.setAccessible(true); + Object obj = field.get(t); + + map.put(field.getName(), obj); + } catch (Exception ex) { + // + } + } + + return map; + } } diff --git a/src/main/java/com/smartearth/poiexcel/utils/HttpHelper.java b/src/main/java/com/smartearth/poiexcel/utils/HttpHelper.java new file mode 100644 index 0000000..cc6c64d --- /dev/null +++ b/src/main/java/com/smartearth/poiexcel/utils/HttpHelper.java @@ -0,0 +1,273 @@ +package com.smartearth.poiexcel.utils; + +import org.apache.http.*; +import org.apache.http.client.config.CookieSpecs; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.utils.URIUtils; +import org.apache.http.entity.InputStreamEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicHeader; +import org.apache.http.message.BasicHttpEntityEnclosingRequest; +import org.apache.http.message.BasicHttpRequest; +import org.apache.http.message.HeaderGroup; +import org.apache.http.util.EntityUtils; + +import javax.servlet.ServletException; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.net.HttpCookie; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Enumeration; + +/** + * Http甯姪绫� + * @author WWW + */ +public class HttpHelper { + private final static String HTTP_SLASH2 = "://"; + + private final static String HTTP_SLASH = "/"; + + private final static Integer THREE = 3; + + protected static final HeaderGroup HOP_HEADERS; + + static { + HOP_HEADERS = new HeaderGroup(); + + String[] headers = new String[]{ + "Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization", + "TE", "Trailers", "Transfer-Encoding", "Upgrade", + //"X-RateLimit-Burst-Capacity", "X-RateLimit-Remaining", "X-RateLimit-Replenish-Rate", + "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials", "Access-Control-Allow-Headers"}; + + for (String header : headers) { + HOP_HEADERS.addHeader(new BasicHeader(header, null)); + } + } + + public void service(HttpServletRequest request, HttpServletResponse response, String url) throws ServletException, IOException { + HttpRequest proxyRequest; + if (request.getHeader(HttpHeaders.CONTENT_LENGTH) != null || request.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { + proxyRequest = newProxyRequestWithEntity(request, url); + } else { + proxyRequest = new BasicHttpRequest(request.getMethod(), url); + } + + HttpHost host = this.getTargetHost(url); + // copyRequestHeaders(request, proxyRequest, host); + //setXrForwardedForHeader(request, proxyRequest); + + // if (!StringHelper.isEmpty(cookie)) proxyRequest.addHeader("Cookie", cookie + "; ") + + CloseableHttpClient client = null; + HttpResponse proxyResponse = null; + try { + client = this.createHttpClient(); + proxyResponse = client.execute(host, proxyRequest); + + int statusCode = proxyResponse.getStatusLine().getStatusCode(); + // response.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()) + response.setStatus(statusCode); + + copyResponseHeaders(proxyResponse, request, response, url); + + if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) { + response.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0); + } else { + copyResponseEntity(proxyResponse, request, response); + } + } catch (Exception ex) { + throw new ServletException(ex.getMessage()); + } finally { + if (proxyResponse != null) { + EntityUtils.consumeQuietly(proxyResponse.getEntity()); + } + if (client != null) { + client.close(); + } + } + } + + protected HttpRequest newProxyRequestWithEntity(HttpServletRequest request, String url) throws IOException { + String method = request.getMethod(); + HttpEntityEnclosingRequest proxyRequest = new BasicHttpEntityEnclosingRequest(method, url); + proxyRequest.setEntity(new InputStreamEntity(request.getInputStream(), getContentLength(request))); + //String str = EntityUtils.toString(proxyRequest.getEntity(), "UTF-8") + + return proxyRequest; + } + + private long getContentLength(HttpServletRequest request) { + String contentLengthHeader = request.getHeader("Content-Length"); + if (contentLengthHeader != null) { + return Long.parseLong(contentLengthHeader); + } + + return -1L; + } + + protected void copyRequestHeaders(HttpServletRequest request, HttpRequest proxyRequest, HttpHost host) { + @SuppressWarnings("unchecked") + Enumeration<String> enumerationOfHeaderNames = request.getHeaderNames(); + + while (enumerationOfHeaderNames.hasMoreElements()) { + String headerName = enumerationOfHeaderNames.nextElement(); + copyRequestHeader(request, proxyRequest, host, headerName); + } + } + + protected void copyRequestHeader(HttpServletRequest request, HttpRequest proxyRequest, HttpHost host, String headerName) { + if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH) || HOP_HEADERS.containsHeader(headerName)) { + return; + } + + @SuppressWarnings("unchecked") + Enumeration<String> headers = request.getHeaders(headerName); + while (headers.hasMoreElements()) { + String headerValue = headers.nextElement(); + if (headerName.equalsIgnoreCase(HttpHeaders.HOST)) { + headerValue = host.getHostName(); + if (host.getPort() != -1) { + headerValue += ":" + host.getPort(); + } + } else if (headerName.equalsIgnoreCase(org.apache.http.cookie.SM.COOKIE)) { + headerValue = getRealCookie(headerValue); + } + + proxyRequest.addHeader(headerName, headerValue); + } + } + + protected HttpHost getTargetHost(String url) throws ServletException { + try { + URI uri = new URI(url); + + return URIUtils.extractHost(uri); + } catch (URISyntaxException ex) { + throw new ServletException(ex.getMessage()); + } + } + + protected String getRealCookie(String cookieValue) { + StringBuilder escapedCookie = new StringBuilder(); + String[] cookies = cookieValue.split("[;,]"); + for (String cookie : cookies) { + String[] cookieSplit = cookie.split("="); + if (cookieSplit.length == 2) { + String cookieName = cookieSplit[0].trim(); + if (cookieName.startsWith(cookieName)) { + cookieName = cookieName.substring(cookieName.length()); + if (escapedCookie.length() > 0) { + escapedCookie.append("; "); + } + escapedCookie.append(cookieName).append("=").append(cookieSplit[1].trim()); + } + } + } + + return escapedCookie.toString(); + } + + private void setXrForwardedForHeader(HttpServletRequest request, HttpRequest proxyRequest) { + String forHeaderName = "X-Forwarded-For"; + String forHeader = request.getRemoteAddr(); + String existingForHeader = request.getHeader(forHeaderName); + if (existingForHeader != null) { + forHeader = existingForHeader + ", " + forHeader; + } + proxyRequest.setHeader(forHeaderName, forHeader); + + String protoHeaderName = "X-Forwarded-Proto"; + String protoHeader = request.getScheme(); + proxyRequest.setHeader(protoHeaderName, protoHeader); + } + + protected CloseableHttpClient createHttpClient() { + RequestConfig requestConfig = RequestConfig.custom() + .setRedirectsEnabled(false) + .setCookieSpec(CookieSpecs.IGNORE_COOKIES) + .setConnectTimeout(-1) + .setSocketTimeout(-1) + .build(); + + // return HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build() + return HttpClients.custom() + .setDefaultRequestConfig(requestConfig) + .build(); + } + + protected void copyResponseHeaders(HttpResponse proxyResponse, HttpServletRequest request, HttpServletResponse response, String url) { + for (Header header : proxyResponse.getAllHeaders()) { + copyResponseHeader(request, response, header, url); + } + } + + protected void copyResponseHeader(HttpServletRequest request, HttpServletResponse response, Header header, String url) { + String headerName = header.getName(); + if (HOP_HEADERS.containsHeader(headerName)) { + return; + } + + String headerValue = header.getValue(); + if (headerName.equalsIgnoreCase(org.apache.http.cookie.SM.SET_COOKIE) || headerName.equalsIgnoreCase(org.apache.http.cookie.SM.SET_COOKIE2)) { + copyProxyCookie(request, response, headerValue); + } else if (headerName.equalsIgnoreCase(HttpHeaders.LOCATION)) { + response.addHeader(headerName, rewriteUrlFromResponse(request, url, headerValue)); + } else { + response.addHeader(headerName, headerValue); + } + } + + protected void copyProxyCookie(HttpServletRequest request, HttpServletResponse response, String headerValue) { + String path = request.getContextPath() + request.getServletPath(); + if (path.isEmpty()) { + path = "/"; + } + + for (HttpCookie cookie : HttpCookie.parse(headerValue)) { + Cookie servletCookie = new Cookie(cookie.getName(), cookie.getValue()); + servletCookie.setComment(cookie.getComment()); + servletCookie.setMaxAge((int) cookie.getMaxAge()); + servletCookie.setPath(path); + + servletCookie.setSecure(cookie.getSecure()); + servletCookie.setVersion(cookie.getVersion()); + response.addCookie(servletCookie); + } + } + + protected String rewriteUrlFromResponse(HttpServletRequest request, String targetUri, String theUrl) { + if (theUrl.startsWith(targetUri)) { + StringBuffer curUrl = request.getRequestURL(); + + int pos; + if ((pos = curUrl.indexOf(HTTP_SLASH2)) >= 0) { + if ((pos = curUrl.indexOf(HTTP_SLASH, pos + THREE)) >= 0) { + curUrl.setLength(pos); + } + } + + curUrl.append(request.getContextPath()); + curUrl.append(request.getServletPath()); + curUrl.append(theUrl, targetUri.length(), theUrl.length()); + + return curUrl.toString(); + } + + return theUrl; + } + + protected void copyResponseEntity(HttpResponse proxyResponse, HttpServletRequest request, HttpServletResponse response) throws IOException { + HttpEntity entity = proxyResponse.getEntity(); + if (null == entity) { + return; + } + + entity.writeTo(response.getOutputStream()); + } +} diff --git a/src/main/java/com/smartearth/poiexcel/utils/RestHelper.java b/src/main/java/com/smartearth/poiexcel/utils/RestHelper.java new file mode 100644 index 0000000..39234ed --- /dev/null +++ b/src/main/java/com/smartearth/poiexcel/utils/RestHelper.java @@ -0,0 +1,267 @@ +package com.smartearth.poiexcel.utils; + +import com.smartearth.poiexcel.entity.StaticData; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpEntity; +import org.apache.http.NameValuePair; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.springframework.web.client.RestTemplate; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Rest鏈嶅姟甯姪绫� + * @author WWW + */ +public class RestHelper { + private static RestTemplate restTemplate; + + private final static Log log = LogFactory.getLog(RestHelper.class); + + /** + * 鑾峰彇RestTemplate + * + * @return RestTemplate + */ + public static RestTemplate getRestTemplate() { + if (restTemplate == null) { + restTemplate = SpringContextHelper.getBean(RestTemplate.class); + } + + return restTemplate; + } + + /** + * Get璇锋眰-HttpURLConnection + * + * @param url URL鍦板潃 + * @return 瀛楃涓� + * @throws IOException IO寮傚父 + */ + public static String getForConn(String url) throws IOException { + BufferedReader br = null; + HttpURLConnection conn = null; + + try { + URL restUrl = new URL(url); + + conn = (HttpURLConnection) restUrl.openConnection(); + // POST,GET,PUT,DELETE + conn.setRequestMethod("GET"); + conn.setRequestProperty("Accept", "application/json"); + + br = new BufferedReader(new InputStreamReader(conn.getInputStream())); + + String line; + StringBuilder sb = new StringBuilder(); + while ((line = br.readLine()) != null) { + sb.append(line); + } + + return sb.toString(); + } finally { + if (br != null) { + br.close(); + } + if (conn != null) { + conn.disconnect(); + } + } + } + + /** + * Post璇锋眰-HttpURLConnection + * + * @param url URL鍦板潃 + * @param query 鏌ヨ鏉′欢 + * @return 瀛楃涓� + * @throws IOException IO寮傚父 + */ + public static String postForConn(String url, String query) throws IOException { + BufferedReader br = null; + HttpURLConnection conn = null; + + try { + URL restUrl = new URL(url); + + conn = (HttpURLConnection) restUrl.openConnection(); + // POST,GET,PUT,DELETE + conn.setRequestMethod("POST"); + conn.setRequestProperty("Content-Type", "application/json"); + conn.setDoOutput(true); + + PrintStream ps = new PrintStream(conn.getOutputStream()); + ps.print(query); + ps.close(); + + // OutputStream out = conn.getOutputStream() + // out.write(query.getBytes()) + // out.close() + + br = new BufferedReader(new InputStreamReader(conn.getInputStream())); + + String line; + StringBuilder sb = new StringBuilder(); + while ((line = br.readLine()) != null) { + sb.append(line); + } + + return sb.toString(); + } finally { + if (br != null) { + br.close(); + } + if (conn != null) { + conn.disconnect(); + } + } + } + + /** + * Get璇锋眰-CloseableHttpClient + * + * @param uri Uri鍦板潃 + * @return 鍝嶅簲瀛楃涓� + */ + public static String get(String uri) { + try { + CloseableHttpClient httpClient = HttpClients.custom().build(); + + HttpGet httpGet = new HttpGet(uri); + + CloseableHttpResponse closeResponse = httpClient.execute(httpGet); + // 鍙栧嚭杩斿洖浣� + HttpEntity entity = closeResponse.getEntity(); + + return EntityUtils.toString(entity, StaticData.TEXT_ENCODER); + } catch (Exception ex) { + log.error(ex.getMessage(), ex); + + return getErrorInfo(uri, ex); + } + } + + /** + * Post璇锋眰-CloseableHttpClient + * + * @param uri Uri鍦板潃 + * @param postData 寰呭彂閫佹暟鎹� + * @return 鍝嶅簲瀛楃涓� + */ + public static String post(String uri, List<NameValuePair> postData) { + try { + CloseableHttpClient httpClient = HttpClients.custom().build(); + + UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(postData, StaticData.TEXT_ENCODER); + HttpPost httpPost = new HttpPost(uri); + httpPost.setEntity(postEntity); + + CloseableHttpResponse closeResponse = httpClient.execute(httpPost); + + // 鍙栧嚭杩斿洖浣� + HttpEntity entity = closeResponse.getEntity(); + + return EntityUtils.toString(entity, StaticData.TEXT_ENCODER); + } catch (Exception ex) { + log.error(ex.getMessage(), ex); + + return getErrorInfo(uri, ex); + } + } + + /** + * 鑾峰彇閿欒淇℃伅 + * + * @param uri Uri鍦板潃 + * @param ex 寮傚父 + * @return 閿欒淇℃伅 + */ + public static String getErrorInfo(String uri, Exception ex) { + Map<String, Object> map = new LinkedHashMap<>(); + map.put("result", null); + map.put("message", ex.getMessage()); + map.put("code", 400); + map.put("uri", uri); + //map.put("tag", StaticData.CACHE_PREFIX) + + return map.toString(); + } + + /** + * GET璇锋眰锛圧EST锛� + */ + public static String getForRest(String uri) { + RestTemplate rest = getRestTemplate(); + + return rest.getForObject(uri, String.class); + } + + /** + * GET璇锋眰锛圧EST锛� + */ + public static <T> T getForRest(String uri, Class<T> clazz) { + RestTemplate rest = getRestTemplate(); + + return rest.getForObject(uri, clazz); + } + + /** + * POST璇锋眰锛圧EST锛� + */ + public static String postForRest(String uri, Map<String, Object> map) { + RestTemplate rest = getRestTemplate(); + + return rest.postForObject(uri, map, String.class); + } + + /** + * POST璇锋眰锛圧EST锛� + */ + public static <T> String postForRest(String uri, List<T> list) { + RestTemplate rest = getRestTemplate(); + + return rest.postForObject(uri, list, String.class); + } + + /** + * POST璇锋眰锛圧EST锛� + */ + public static <T> String postForRest(String uri, T t) { + RestTemplate rest = getRestTemplate(); + + return rest.postForObject(uri, t, String.class); + } + + /** + * DELETE璇锋眰锛圧EST锛� + */ + public static void deleteForRest(String uri) { + RestTemplate rest = getRestTemplate(); + + rest.delete(uri); + } + + /** + * DELETE璇锋眰锛圧EST锛� + */ + public static void deleteForRest(String uri, Map<String, Object> map) { + RestTemplate rest = getRestTemplate(); + + rest.delete(uri, map); + } +} diff --git a/src/main/java/com/smartearth/poiexcel/utils/SpringContextHelper.java b/src/main/java/com/smartearth/poiexcel/utils/SpringContextHelper.java new file mode 100644 index 0000000..2f5d11c --- /dev/null +++ b/src/main/java/com/smartearth/poiexcel/utils/SpringContextHelper.java @@ -0,0 +1,86 @@ +package com.smartearth.poiexcel.utils; + +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; + +/** + * Spring涓婁笅鏂囧府鍔╃被 + * @author WWW + */ +@Component +public class SpringContextHelper implements ApplicationContextAware { + private static ApplicationContext context = null; + + /** + * 璁剧疆搴旂敤绋嬪簭涓婁笅鏂� + * + * @param applicationContext + * @throws BeansException + */ + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + context = applicationContext; + } + + /** + * 鏍规嵁鍚嶇О鑾峰彇Bean + * + * @param name 绫诲悕绉� + * @return + */ + public static <T> T getBean(String name) { + return (T) context.getBean(name); + } + + /** + * 鏍规嵁绫诲瀷鑾峰彇Bean + * + * @param clazz 绫� + * @param <T> 娉涘瀷 + * @return + */ + public static <T> T getBean(Class<T> clazz) { + return context.getBean(clazz); + } + + /** + * 鍒ゆ柇鏄惁鍖呭惈瀵瑰簲鍚嶇О鐨凚ean瀵硅薄 + * + * @param name Bean鍚嶇О + * @return 鍖呭惈锛氳繑鍥瀟rue锛屽惁鍒欒繑鍥瀎alse銆� + */ + public static boolean containsBean(String name) { + return context.containsBean(name); + } + + /** + * 鑾峰彇瀵瑰簲Bean鍚嶇О鐨勭被鍨� + * + * @param name Bean鍚嶇О + * @return 杩斿洖瀵瑰簲鐨凚ean绫诲瀷 + */ + public static Class<?> getType(String name) { + return context.getType(name); + } + + /** + * 鑾峰彇涓婁笅鏂囧璞★紝鍙繘琛屽悇绉峉pring鐨勪笂涓嬫枃鎿嶄綔 + * + * @return Spring涓婁笅鏂囧璞� + */ + public static ApplicationContext getContext() { + return context; + } + + + /** + * 鑾峰彇褰撳墠鐜 + * + * @return Profile + */ + public static String getActiveProfile() { + return context.getEnvironment().getActiveProfiles()[0]; + } +} -- Gitblit v1.9.3