diff --git a/JSD-9268需求确认书.docx b/JSD-9268需求确认书.docx new file mode 100644 index 0000000..432120b Binary files /dev/null and b/JSD-9268需求确认书.docx differ diff --git a/README.md b/README.md index 421fa5b..3de0e90 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,6 @@ # open-JSD-9268 -JSD-9268 统一单点(类OAuth) \ No newline at end of file +JSD-9268 统一单点(类OAuth)\ +免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\ +仅作为开发者学习参考使用!禁止用于任何商业用途!\ +为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系hugh处理。 \ No newline at end of file diff --git a/plugin.xml b/plugin.xml new file mode 100644 index 0000000..52905ed --- /dev/null +++ b/plugin.xml @@ -0,0 +1,21 @@ + + com.eco.plugin.xxxx.xxxx + + yes + 1.0.7 + 10.0 + 2018-07-31 + fr.open + + + com.eco.plugin.xxxx.xxxx + + + + + + + + + \ No newline at end of file diff --git a/src/main/java/com/eco/plugin/xxxx/xxxx/config/InitializeMonitor.java b/src/main/java/com/eco/plugin/xxxx/xxxx/config/InitializeMonitor.java new file mode 100644 index 0000000..946a369 --- /dev/null +++ b/src/main/java/com/eco/plugin/xxxx/xxxx/config/InitializeMonitor.java @@ -0,0 +1,21 @@ +package com.eco.plugin.xxxx.xxxx.config; + +import com.fr.plugin.context.PluginContext; +import com.fr.plugin.observer.inner.AbstractPluginLifecycleMonitor; + +/** + * @author fr.open + * @version 10.0 + * Created by fr.open on 2018-12-04 + */ +public class InitializeMonitor extends AbstractPluginLifecycleMonitor { + @Override + public void afterRun(PluginContext pluginContext) { + PluginSimpleConfig.getInstance(); + } + + @Override + public void beforeStop(PluginContext pluginContext) { + + } +} diff --git a/src/main/java/com/eco/plugin/xxxx/xxxx/config/PluginSimpleConfig.java b/src/main/java/com/eco/plugin/xxxx/xxxx/config/PluginSimpleConfig.java new file mode 100644 index 0000000..a32bd69 --- /dev/null +++ b/src/main/java/com/eco/plugin/xxxx/xxxx/config/PluginSimpleConfig.java @@ -0,0 +1,80 @@ +package com.eco.plugin.xxxx.xxxx.config; + +import com.fr.config.*; +import com.fr.config.holder.Conf; +import com.fr.config.holder.factory.Holders; +import com.fr.intelli.record.Focus; +import com.fr.intelli.record.Original; +import com.fr.record.analyzer.EnableMetrics; + +@Visualization(category = "单点登录配置") +@EnableMetrics +public class PluginSimpleConfig extends DefaultConfiguration { + + private static volatile PluginSimpleConfig config = null; + + @Focus(id="com.eco.plugin.xxxx.xxxx.config", text = "单点登录配置", source = Original.PLUGIN) + public static PluginSimpleConfig getInstance() { + if (config == null) { + config = ConfigContext.getConfigInstance(PluginSimpleConfig.class); + } + return config; + } + + @Identifier(value = "appName", name = "appName", description = "appName", status = Status.SHOW) + private Conf appName = Holders.simple("xxxx"); + + @Identifier(value = "privatekey", name = "密钥", description = "密钥", status = Status.SHOW) + private Conf privatekey = Holders.simple(""); + + @Identifier(value = "index", name = "帆软首页", description = "帆软首页", status = Status.SHOW) + private Conf index = Holders.simple("http://localhost:8075/webroot/decision"); + + @Identifier(value = "authUrl", name = "统一域用户认证请求地址", description = "统一域用户认证请求地址", status = Status.SHOW) + private Conf authUrl = Holders.simple("http://xxxx"); + + + public String getAppName() { + return appName.get(); + } + + public void setAppName(String url) { + this.appName.set(url); + } + + public String getPrivatekey() { + return privatekey.get(); + } + + public void setPrivatekey(String url) { + this.privatekey.set(url); + } + + public String getAuthUrl() { + return authUrl.get(); + } + + public void setAuthUrl(String url) { + this.authUrl.set(url); + } + + public String getIndex() { + return index.get(); + } + + public void setIndex(String url) { + this.index.set(url); + } + + @Override + public Object clone() throws CloneNotSupportedException { + PluginSimpleConfig cloned = (PluginSimpleConfig) super.clone(); +// cloned.text = (Conf) text.clone(); +// cloned.count = (Conf) count.clone(); +// cloned.price = (Conf) price.clone(); +// cloned.time = (Conf) time.clone(); +// cloned.student = (Conf) student.clone(); + return cloned; + } + +} diff --git a/src/main/java/com/eco/plugin/xxxx/xxxx/filter/SSOFilter.java b/src/main/java/com/eco/plugin/xxxx/xxxx/filter/SSOFilter.java new file mode 100644 index 0000000..dfd2424 --- /dev/null +++ b/src/main/java/com/eco/plugin/xxxx/xxxx/filter/SSOFilter.java @@ -0,0 +1,108 @@ +package com.eco.plugin.xxxx.xxxx.filter; + +import com.eco.plugin.xxxx.xxxx.config.PluginSimpleConfig; +import com.eco.plugin.xxxx.xxxx.utils.EncryUtils; +import com.eco.plugin.xxxx.xxxx.utils.FRUtils; +import com.eco.plugin.xxxx.xxxx.utils.Utils; +import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider; +import com.fr.plugin.context.PluginContexts; +import com.fr.record.analyzer.EnableMetrics; +import com.fr.stable.fun.Authorize; + +import javax.servlet.FilterChain; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@EnableMetrics +@Authorize(callSignKey = "com.eco.plugin.xxxx.xxxx") +public class SSOFilter extends AbstractGlobalRequestFilterProvider { + @Override + public String filterName() { + return "xxxx Filter"; + } + + @Override + public String[] urlPatterns() { + return new String[]{"/*"}; + } + + @Override + public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain ){ + + if(PluginContexts.currentContext().isAvailable()){ + //是否放行 + boolean release = isRelease(req); + + if(release){ + release(req,res,chain); + return; + } + + //code + String code = req.getParameter("userInfoGwamcc"); + + PluginSimpleConfig psc = PluginSimpleConfig.getInstance(); + + + if(Utils.isNullStr(code)){ + //跳转认证中心 + redirect(req,res,psc); + return; + } + + FRUtils.FRLogInfo("url:"+FRUtils.getAllUrl(req)); + //获取userInfo + String username = getUsername(code,psc); + + //登录 + FRUtils.login(req,res,username,""); + } + + release(req,res,chain); + } + + private String getUsername(String code, PluginSimpleConfig psc) { + try { + return EncryUtils.getStr(code); + } catch (Exception e) { + FRUtils.FRLogError("解密异常:"+e.getMessage()); + return ""; + } + } + + private boolean isRelease(HttpServletRequest req) { + String url = FRUtils.getAllUrl(req); +// FRUtils.FRLogInfo("requestUrl:"+url); + String reft = req.getParameter("ref_t"); + + boolean isLogin = FRUtils.isLogin(req); + boolean isRemote = url.contains("remote"); + boolean isLoginPage = url.contains("login")||url.contains("decision/file")||url.contains("decision/resource")||url.contains("decision/system")||url.contains("query/ip"); + boolean isMobile = Utils.isMobile(req); + + return isLogin || isRemote || isLoginPage || isMobile; + } + + //跳转认证中心 + private void redirect(HttpServletRequest req,HttpServletResponse res, PluginSimpleConfig psc) { + String url = FRUtils.getAllUrl(req); + String authurl = psc.getAuthUrl()+"?appName="+psc.getAppName()+"&redirectURL="+url; + + try { + res.sendRedirect(authurl); + } catch (IOException e) { + FRUtils.FRLogInfo("跳转认证中心异常:"+e.getMessage()); + } + } + + //放行拦截器 + private void release(HttpServletRequest req, HttpServletResponse res, FilterChain chain) { + try{ + chain.doFilter(req,res); + }catch (Exception e){ + FRUtils.FRLogInfo("拦截失败"); + } + } +} + diff --git a/src/main/java/com/eco/plugin/xxxx/xxxx/logout/Logout.java b/src/main/java/com/eco/plugin/xxxx/xxxx/logout/Logout.java new file mode 100644 index 0000000..5f167d8 --- /dev/null +++ b/src/main/java/com/eco/plugin/xxxx/xxxx/logout/Logout.java @@ -0,0 +1,20 @@ +package com.eco.plugin.xxxx.xxxx.logout; + +import com.eco.plugin.xxxx.xxxx.config.PluginSimpleConfig; +import com.fr.decision.fun.impl.AbstractLogInOutEventProvider; +import com.fr.decision.webservice.login.LogInOutResultInfo; +import com.fr.decision.webservice.v10.login.LoginService; + +import javax.servlet.http.HttpSession; + +public class Logout extends AbstractLogInOutEventProvider { + + @Override + public String logoutAction(LogInOutResultInfo result) { + HttpSession session = result.getRequest().getSession(true); + LoginService.getInstance().crossDomainLogout(result.getRequest(),result.getResponse(),""); + session.invalidate(); + return PluginSimpleConfig.getInstance().getIndex()+"/login"; + } +} + diff --git a/src/main/java/com/eco/plugin/xxxx/xxxx/utils/EncryUtils.java b/src/main/java/com/eco/plugin/xxxx/xxxx/utils/EncryUtils.java new file mode 100644 index 0000000..d90fa22 --- /dev/null +++ b/src/main/java/com/eco/plugin/xxxx/xxxx/utils/EncryUtils.java @@ -0,0 +1,179 @@ +package com.eco.plugin.xxxx.xxxx.utils; + +import com.eco.plugin.xxxx.xxxx.config.PluginSimpleConfig; +import com.fr.json.JSONObject; +import sun.misc.BASE64Decoder; +import sun.misc.BASE64Encoder; +import javax.crypto.Mac; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import java.io.IOException; +import java.security.InvalidKeyException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * 解密类 + */ +public class EncryUtils { + /*** + * Base64转码 + */ + private static byte[] Base64UrlDecode(String input) throws IOException,Exception { + String output = input; + output = output.replace('-', '+'); // 62nd char of encoding + output = output.replace('_', '/'); // 63rd char of encoding + switch (output.length() % 4) // Pad with trailing '='s + { + case 0: + break; // No pad chars in this case + case 2: + output += "=="; + break; // Two pad chars + case 3: + output += "="; + break; // One pad char + default: + throw new Exception("Illegal base64url string!"); + } + BASE64Decoder decoder = new BASE64Decoder();// Standard base64 decoder + byte[] decodedBytes = decoder.decodeBuffer(output); + return decodedBytes; + } + + /*** + * MD5加码 生成md5码 + */ + public static String string2MD5(String inStr){ + MessageDigest md5 = null; + try{ + md5 = MessageDigest.getInstance("MD5"); + }catch (Exception e){ + System.out.println(e.toString()); + e.printStackTrace(); + return ""; + } + char[] charArray = inStr.toCharArray(); + byte[] byteArray = new byte[charArray.length]; + + for (int i = 0; i < charArray.length; i++) + byteArray[i] = (byte) charArray[i]; + byte[] md5Bytes = md5.digest(byteArray); + StringBuffer hexValue = new StringBuffer(); + for (int i = 0; i < md5Bytes.length; i++){ + int val = ((int) md5Bytes[i]) & 0xff; + if (val < 16) + hexValue.append("0"); + hexValue.append(Integer.toHexString(val)); + } + return hexValue.toString(); + + } + + public static List getStrMD5PrivateKeyNew(String userid) { + List list = new ArrayList(); + String strSourceA = ""; + String strSourceB = ""; + String strSourceC = ""; + //账号 + String accountNo = userid; + //当前时间 + Date nowDate = new Date(); + Date laterDate = new Date(nowDate.getTime() + 60000); + Date earlyDate = new Date(nowDate.getTime() - 60000); + + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm"); + String strMinutes = sdf.format(nowDate); + String laterMinutes = sdf.format(laterDate); + String earlyMinutes = sdf.format(earlyDate); + + //获取系统握手密钥的方法,需要自己实现 + + String strMD5PrivateKey = PluginSimpleConfig.getInstance().getPrivatekey(); + //密码与GwamccSSO中分配密码一致 + + strSourceA = accountNo + strMinutes + strMD5PrivateKey; + strSourceA = string2MD5(strSourceA); + strSourceB = accountNo + laterMinutes + strMD5PrivateKey; + strSourceB = string2MD5(strSourceB); + strSourceC = accountNo + earlyMinutes + strMD5PrivateKey; + strSourceC = string2MD5(strSourceC); + list.add(strSourceA.toLowerCase()); + list.add(strSourceB.toLowerCase()); + list.add(strSourceC.toLowerCase()); + return list; + } + + private static byte[] HmacSHA256Signer(byte[] keyBytes, byte[] source) + throws InvalidKeyException { + String HMAC_SHA256_ALG = "HmacSHA256"; + Mac hmac; + SecretKey signingKey = new SecretKeySpec(keyBytes, HMAC_SHA256_ALG); + try { + hmac = Mac.getInstance(HMAC_SHA256_ALG); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException( + "cannot use Hmac256Signer on system without HmacSHA256 alg", + e); + } + hmac.init(signingKey); + return hmac.doFinal(source); + } + + public static String getStr(String token)throws IOException, InvalidKeyException, Exception{ + + String[] parts = token.split("\\."); + String header = parts[0]; + String payload = parts[1]; + + byte[] crypto = Base64UrlDecode(parts[2]); + + String headerJson = new String(Base64UrlDecode(header), "UTF-8"); + String payloadJson = new String(Base64UrlDecode(payload), "UTF-8"); + + // verify + JSONObject headerData = new JSONObject(headerJson); + JSONObject payloadData = new JSONObject(payloadJson); + + String userName = payloadData.getString("userName"); + String challenge = payloadData.getString("challenge"); + + //验证握手信息,必须做校验!!! + List list = new ArrayList(); + list = getStrMD5PrivateKeyNew(userName); + String resultStr = ""; + for(int i=0;i header){ + FineLoggerFactory.getLogger().info("FRLOG:HttpUtils.get--url:"+url); + + //创建httpClient + CloseableHttpClient httpclient = createHttpClient(cookies); + + HttpGet getMethod = new HttpGet(url); + + if(header != null && header.size() > 0){ + Set keySet = header.keySet(); + + for(String key : keySet){ + getMethod.setHeader(key,header.get(key)); + } + } + + try { + HttpResponse response = httpclient.execute(getMethod); + int status =response.getStatusLine().getStatusCode(); + HttpEntity entity = response.getEntity(); + String returnResult = EntityUtils.toString(entity, "utf-8"); + + FineLoggerFactory.getLogger().info("FRLOG:HttpUtils.get--status:"+status); + FineLoggerFactory.getLogger().info("FRLOG:HttpUtils.get--returnResult:"+returnResult); + + httpclient.close(); + + if (status == HttpStatus.SC_OK) { + return returnResult; + } + } catch (Exception e) { + FineLoggerFactory.getLogger().info("FRLOG:HttpUtils.get--exception:"+e.getMessage()); + } + + try { + httpclient.close(); + } catch (Exception e) { + FineLoggerFactory.getLogger().info("FRLOG:http关闭异常:"+e.getMessage()); + } + + return ""; + } + + /** + * HttpPost请求 + * @param postMethod + * @return + */ + private static String HttpPost(HttpPost postMethod){ + CloseableHttpClient httpclient = createHttpClient(null); + + try { + HttpResponse response = httpclient.execute(postMethod); + int status = response.getStatusLine().getStatusCode(); + HttpEntity entity = response.getEntity(); + String returnResult = EntityUtils.toString(entity, "utf-8"); + FineLoggerFactory.getLogger().info("FRLOG:HttpPost:status:"+status); + FineLoggerFactory.getLogger().info("FRLOG:HttpPost:returnResult:"+returnResult); + httpclient.close(); + + if (status == HttpStatus.SC_OK) { + return returnResult; + } + } catch (Exception e) { + FineLoggerFactory.getLogger().info("FRLOG:HttpPost:exception:"+e.getMessage()); + } + + try { + httpclient.close(); + } catch (Exception e) { + FineLoggerFactory.getLogger().info("FRLOG:http关闭异常:"+e.getMessage()); + } + + return ""; + } + + public static String HttpPostXML(String url, String xmlParam){ + FineLoggerFactory.getLogger().info("FRLOG:HttpPostXML:url:"+url); + + HttpPost postMethod = new HttpPost(url); + + postMethod.setHeader("Content-type", "text/html"); + HttpEntity entity2 = null; + try { + entity2 = new StringEntity(xmlParam); + } catch (UnsupportedEncodingException e) { + FineLoggerFactory.getLogger().info("FRLOG:HttpPostXML:参数异常:"+e.getMessage()); + return ""; + } + + postMethod.setEntity(entity2); + + return HttpPost(postMethod); + } + + public static String HttpPostJson(String url, String param,Map header){ + FineLoggerFactory.getLogger().info("FRLOG:HttpPostJSON:url:"+url); + + HttpPost postMethod = new HttpPost(url); + + postMethod.setHeader("Content-Type","application/json"); + + if(header != null && header.size() > 0){ + Set keySet = header.keySet(); + + for(String key : keySet){ + postMethod.setHeader(key,header.get(key)); + } + } + + if(!Utils.isNullStr(param)){ + HttpEntity entity2 = null; + try { + entity2 = new StringEntity(param); + } catch (UnsupportedEncodingException e) { + FineLoggerFactory.getLogger().info("FRLOG:HttpPostJSON:参数异常:"+e.getMessage()); + return ""; + } + + postMethod.setEntity(entity2); + } + + return HttpPost(postMethod); + } + + public static String HttpPostWWWForm(String url, Map header,Map param){ + FineLoggerFactory.getLogger().info("FRLOG:HttpWWWForm:url:"+url); + + HttpPost postMethod = new HttpPost(url); + + if(header != null && header.size() > 0){ + Set keySet = header.keySet(); + + for(String key : keySet){ + postMethod.setHeader(key,header.get(key)); + } + } + + if(param != null && param.size() > 0){ + List params = new ArrayList(param.size()); + + for(Map.Entry map : param.entrySet()){ + params.add(new BasicNameValuePair(map.getKey(), map.getValue())); + } + + try { + postMethod.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); + } catch (UnsupportedEncodingException e) { + FineLoggerFactory.getLogger().info("FRLOG:HttpWWWForm:异常:"+e.getMessage()); + return ""; + } + } + + return HttpPost(postMethod); + } + + private static CloseableHttpClient createHttpClient(Cookie[] cookies){ + + SSLContext sslContext = null; + try { + sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { + @Override + public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { + return true; + } + }).build(); + } catch (Exception e) { + FRUtils.FRLogInfo("exception:"+e.getMessage()); + } + + CloseableHttpClient httpclient = null; + + if(cookies != null && cookies.length > 0){ + CookieStore cookieStore = cookieToCookieStore(cookies); + + httpclient = HttpClients.custom().setSslcontext(sslContext). + setSSLHostnameVerifier(new NoopHostnameVerifier()).setDefaultCookieStore(cookieStore).build(); + } + else{ + httpclient = HttpClients.custom().setSslcontext(sslContext). + setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); + } + + return httpclient; + } + + /** + * cookies转cookieStore + * @param cookies + * @return + */ + public static CookieStore cookieToCookieStore(Cookie[] cookies){ + CookieStore cookieStore = new BasicCookieStore(); + + if(cookies != null && cookies.length>0){ + for(Cookie cookie : cookies){ + BasicClientCookie cookie1 = new BasicClientCookie(cookie.getName(), cookie.getValue()); + cookieStore.addCookie(cookie1); + } + } + + return cookieStore; + } +} diff --git a/src/main/java/com/eco/plugin/xxxx/xxxx/utils/ResponseUtils.java b/src/main/java/com/eco/plugin/xxxx/xxxx/utils/ResponseUtils.java new file mode 100644 index 0000000..c89cf29 --- /dev/null +++ b/src/main/java/com/eco/plugin/xxxx/xxxx/utils/ResponseUtils.java @@ -0,0 +1,94 @@ +package com.eco.plugin.xxxx.xxxx.utils; + +import com.fr.json.JSONObject; +import com.fr.log.FineLoggerFactory; +import com.fr.web.utils.WebUtils; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.PrintWriter; + +public class ResponseUtils { + private static final int SUCCESS = 200; + private static final int FAILED = -1; + + public static void successResponse(HttpServletResponse res, String body) { + response(res, body, SUCCESS); + } + + public static void failedResponse(HttpServletResponse res, String body) { + response(res, body, FAILED); + } + + private static void response(HttpServletResponse res, String body, int code) { + JSONObject object = new JSONObject(); + PrintWriter pw; + try { + object.put("code", code); + object.put("data", body); + pw = WebUtils.createPrintWriter(res); + } catch (Exception e) { + FineLoggerFactory.getLogger().info(e.getMessage()); + return; + } + res.setContentType("application/json;charset=utf-8"); + String result = object.toString(); + pw.println(result); + pw.flush(); + pw.close(); + } + + public static void response(HttpServletResponse res,JSONObject json){ + PrintWriter pw; + try { + pw = WebUtils.createPrintWriter(res); + } catch (Exception e) { + FineLoggerFactory.getLogger().info(e.getMessage()); + return; + } + res.setContentType("application/json;charset=utf-8"); + String result = json.toString(); + pw.println(result); + pw.flush(); + pw.close(); + } + + public static void responseXml(HttpServletResponse res,String xml){ + PrintWriter pw; + try { + pw = WebUtils.createPrintWriter(res); + } catch (Exception e) { + FineLoggerFactory.getLogger().info(e.getMessage()); + return; + } + res.setContentType("text/xml;charset=utf-8"); + pw.println(xml); + pw.flush(); + pw.close(); + } + + public static void setCSRFHeader(HttpServletResponse httpServletResponse){ + httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); + httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,HEAD,PUT,PATCH"); + httpServletResponse.setHeader("Access-Control-Max-Age", "36000"); + httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Authorization,authorization"); + } + + public static void responseJsonp(HttpServletRequest req, HttpServletResponse res, JSONObject json){ + PrintWriter pw; + try { + pw = WebUtils.createPrintWriter(res); + } catch (Exception e) { + FineLoggerFactory.getLogger().info(e.getMessage()); + return; + } + res.setContentType("text/javascript;charset=utf-8;charset=utf-8"); + String result = json.toString(); + + String jsonp=req.getParameter("callback"); + + pw.println(jsonp+"("+result+")"); + pw.flush(); + pw.close(); + } +} diff --git a/src/main/java/com/eco/plugin/xxxx/xxxx/utils/Utils.java b/src/main/java/com/eco/plugin/xxxx/xxxx/utils/Utils.java new file mode 100644 index 0000000..bca2b65 --- /dev/null +++ b/src/main/java/com/eco/plugin/xxxx/xxxx/utils/Utils.java @@ -0,0 +1,226 @@ +package com.eco.plugin.xxxx.xxxx.utils; + +import com.fr.base.TemplateUtils; +import com.fr.data.NetworkHelper; +import com.fr.io.utils.ResourceIOUtils; +import com.fr.json.JSONObject; +import com.fr.stable.CodeUtils; +import com.fr.stable.StringUtils; +import com.fr.third.org.apache.commons.codec.digest.DigestUtils; +import com.fr.web.utils.WebUtils; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.BufferedReader; +import java.io.InputStream; +import java.net.URLEncoder; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class Utils { + + /** + * 判断字符串是否为空 + * @param str + * @return true 空字符串 false 非空字符串 + */ + public static boolean isNullStr(String str){ + return !(str != null && !str.isEmpty() && !"null".equals(str)); + } + + /** + * 判断字符串是否非空 + * @param str + * @return + */ + public static boolean isNotNullStr(String str){ + return !isNullStr(str); + } + + /** + * MD5加密 + * @param str + * @return + */ + public static String getMd5Str(String str) + { + return DigestUtils.md5Hex(str); + } + + /** + * 帆软shaEncode加密 + */ + + public static String shaEncode(String str){ + return CodeUtils.sha256Encode(str); + } + + /** + * 获取uuid + */ + public static String uuid(){ + return UUID.randomUUID().toString(); + } + + /** + * 替换空字符串 + * @param str + * @param replace + * @return + */ + public static String replaceNullStr(String str,String replace){ + if(isNullStr(str)){ + return replace; + } + + return str; + } + + /** + * 获取请求体 + * @param req + * @return + */ + public static JSONObject getRequestBody(HttpServletRequest req){ + StringBuffer sb = new StringBuffer(); + String line = null; + try { + BufferedReader reader = req.getReader(); + while ((line = reader.readLine()) != null) + sb.append(line); + } catch (Exception e) { + FRUtils.FRLogInfo("getRequestBody:exception:"+e.getMessage()); + } + //将空格和换行符替换掉避免使用反序列化工具解析对象时失败 + String jsonString = sb.toString().replaceAll("\\s","").replaceAll("\n",""); + + JSONObject json = new JSONObject(jsonString); + + return json; + } + + /** + * 获取ip + * @return + */ + public static String getIp(HttpServletRequest req){ + String realIp = req.getHeader("X-Real-IP"); + String fw = req.getHeader("X-Forwarded-For"); + if (StringUtils.isNotEmpty(fw) && !"unKnown".equalsIgnoreCase(fw)) { + int var3 = fw.indexOf(","); + return var3 != -1 ? fw.substring(0, var3) : fw; + } else { + fw = realIp; + if (StringUtils.isNotEmpty(realIp) && !"unKnown".equalsIgnoreCase(realIp)) { + return realIp; + } else { + if (StringUtils.isBlank(realIp) || "unknown".equalsIgnoreCase(realIp)) { + fw = req.getHeader("Proxy-Client-IP"); + } + + if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) { + fw = req.getHeader("WL-Proxy-Client-IP"); + } + + if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) { + fw = req.getHeader("HTTP_CLIENT_IP"); + } + + if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) { + fw = req.getHeader("HTTP_X_FORWARDED_FOR"); + } + + if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) { + fw = req.getRemoteAddr(); + } + + return fw; + } + } + } + + /** + * 根据key获取cookie + * @param req + * @return + */ + public static String getCookieByKey(HttpServletRequest req,String key){ + Cookie[] cookies = req.getCookies(); + String cookie = ""; + + if(cookies == null || cookies.length <=0){ + return ""; + } + + for(int i = 0; i < cookies.length; i++) { + Cookie item = cookies[i]; + if (item.getName().equalsIgnoreCase(key)) { + cookie = item.getValue(); + } + } + + FRUtils.FRLogInfo("cookie:"+cookie); + + return cookie; + } + + /** + * 判断是否是手机端的链接 + * @param req + * @return + */ + public static boolean isMobile(HttpServletRequest req) { + String[] mobileArray = {"iPhone", "iPad", "android", "windows phone", "xiaomi"}; + String userAgent = req.getHeader("user-agent"); + if (userAgent != null && userAgent.toUpperCase().contains("MOBILE")) { + for(String mobile : mobileArray) { + if(userAgent.toUpperCase().contains(mobile.toUpperCase())) { + return true; + } + } + } + return NetworkHelper.getDevice(req).isMobile(); + } + + /** + * 只编码中文 + * @param url + * @return + */ + public static String encodeCH(String url ){ + Matcher matcher = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(url); + + while(matcher.find()){ + String chn = matcher.group(); + url = url.replaceAll(chn, URLEncoder.encode(chn)); + } + + return url; + } + + /** + * 获取web-inf文件夹下的文件 + * filename /resources/ip4enc.properties + */ + public static InputStream getResourcesFile(String filename){ + return ResourceIOUtils.read(filename); + } + + public static void toErrorPage(HttpServletResponse res,String path,Map parameterMap){ + if(parameterMap == null){ + parameterMap = new HashMap(); + } + + try { + String macPage = TemplateUtils.renderTemplate(path, parameterMap); + WebUtils.printAsString(res, macPage); + }catch (Exception e){ + FRUtils.FRLogError("跳转页面异常"); + } + + } +}