zoukankan      html  css  js  c++  java
  • 工具类

    public class CommonUtils {
    	
    	private static final Logger log = LogManager.getLogger(CommonUtils.class);
    
    	private static final String[] HEADERS = { "J-Forwarded-For", "x-forwarded-for", "Proxy-Client-IP",
    			"WL-Proxy-Client-IP" };
    
    	public static final String LOCAL_ADDRESS;
    	static {
    		String localAddress = null;
    
    		try {
    			localAddress = InetAddress.getLocalHost().getHostAddress();
    			if (StringUtils.isBlank(localAddress)) {
    				localAddress= InetAddress.getLocalHost().getHostName();
    			}
    		} catch (UnknownHostException e) {
    			log.error("InetAddress.getLocalHost().getHostAddress() exception. {}, {}.", e.getClass().getSimpleName(), e.getMessage());
    		}
    
    		LOCAL_ADDRESS = localAddress;
    	}
    
    	public static String getUserIp(HttpServletRequest request) {
    		for (String key : HEADERS) {
    			String ip = request.getHeader(key);
    			ip = chooseFirst(ip);
    			if (ip != null) {
    				return ip;
    			}
    		}
    		return "";
    	}
    
    	private static String chooseFirst(String ipList) {
    		if (isBlank(ipList)) {
    			return null;
    		}
    		String[] ipArray = ipList.split(",");
    		for (String ip : ipArray) {
    			if (isBlank(ip) || "unknown".equalsIgnoreCase(ip.trim())) {
    				continue;
    			}
    			return ip.trim();
    		}
    		return null;
    	}
    
    	public static int IP2Integer(String netId) {
    		String[] array = netId.split("\.");
    		int part0 = Integer.parseInt(array[0]) << 24;
    		int part1 = Integer.parseInt(array[1]) << 16;
    		int part2 = Integer.parseInt(array[2]) << 8;
    		int part3 = Integer.parseInt(array[3]);
    		return part0 + part1 + part2 + part3;
    	}
    
    	public static boolean isBlank(String str) {
    		int strLen;
    		if (str == null || (strLen = str.length()) == 0) {
    			return true;
    		}
    		for (int i = 0; i < strLen; i++) {
    			if ((Character.isWhitespace(str.charAt(i)) == false)) {
    				return false;
    			}
    		}
    		return true;
    	}
    	
    	
    	
    	private static ObjectMapper mapper = new ObjectMapper();
    	
    	static {
    		mapper.setSerializationInclusion(Include.NON_NULL);
    		mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    	}
    
    	public static String write2JsonStr(Object o) {
    		String jsonStr = "";
    		try {
    			jsonStr = mapper.writeValueAsString(o);
    		} catch (JsonProcessingException e) {
    			log.error("write2JsonStr() exception: " + e.getMessage());
    		}
    		return jsonStr;
    	}
    
    	public static Object json2Object(String json, Class<?> clazz) {
    		try {
    			return mapper.readValue(json, clazz);
    		} catch (JsonParseException e) {
    			log.error("json2Object() parseException: " + e.getMessage());
    		} catch (JsonMappingException e) {
    			log.error("json2Object() mappingException: " + e.getMessage());
    		} catch (IOException e) {
    			log.error("json2Object() IOException: " + e.getMessage());
    		}
    		return null;
    	}
    
    	@SuppressWarnings("unchecked")
    	public static Map<String, Object> json2Map(String json) {
    		try {
    			if (StringUtils.isBlank(json)) {
    				return new HashMap<String, Object>();
    			}
    			return mapper.readValue(json, Map.class);
    		} catch (JsonParseException e) {
    			log.error("json2Map(), 出错的json内容:" + json + " ,JsonParseException: " + e.getMessage());
    		} catch (JsonMappingException e) {
    			log.error("json2Map(), 出错的json内容:" + json + " ,JsonMappingException: " + e.getMessage());
    		} catch (IOException e) {
    			log.error("json2Map(), 出错的json内容为:" + json + " ,IOException: " + e.getMessage());
    		}
    		return new HashMap<String, Object>();
    	}
    
    	@SuppressWarnings("unchecked")
    	public static List<Map<String, Object>> jsonArray2List(String jsonArray) {
    		try {
    			return mapper.readValue(jsonArray, List.class);
    		} catch (JsonParseException e) {
    			log.error("jsonArray2List() exception, 异常字符串: " + jsonArray, e);
    		} catch (JsonMappingException e) {
    			log.error("jsonArray2List() exception, 异常字符串: " + jsonArray, e);
    		} catch (IOException e) {
    			log.error("jsonArray2List() exception", e);
    		}
    		return new ArrayList<Map<String, Object>>();
    	}
    	
    	
    	public static String getMatchedCookieValue(Cookie[] cookies, String cookieName) {
    		if (cookieName == null || cookies == null || cookies.length == 0) {
    			return null;
    		}
    
    		for (Cookie cookie : cookies) {
    			String currentName = cookie.getName();
    			if (cookieName.equals(currentName)) {
    				return cookie.getValue();
    			}
    		}
    
    		return null;
    	}

        

    protected void sendEmail(String subject, String content, Set<String> toEmails, Set<String> bccEmails) {
    if (StringUtils.isBlank(content)) {
    return;
    }


    Properties properties = new Properties();
    properties.put("mail.smtp.host", smtpHost);
    properties.put("mail.smtp.auth", "true");
    Session session = Session.getInstance(properties, new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(username, pwd);
    }
    });
    MimeMessage message = new MimeMessage(session);
    InternetAddress fromAddress;

    try {
    fromAddress = new InternetAddress(email);
    } catch (AddressException e) {
    logger.error("init from address exception, ", e);

    return;
    }

    try {
    message.setFrom(fromAddress);
    } catch (MessagingException e) {
    logger.error("message set from exception, ", e);

    return;
    }
    if (toEmails != null && toEmails.size() > 0) {
    InternetAddress[] toAddresses = new InternetAddress[toEmails.size()];
    int index = 0;
    for (String email : toEmails) {
    try {
    toAddresses[index] = new InternetAddress(email);
    ++index;
    } catch (AddressException e) {
    logger.error("init to address exception, address: " + email, e);

    }
    }
    try {
    message.addRecipients(Message.RecipientType.TO, toAddresses);
    } catch (MessagingException e) {
    logger.error("addRecipients exception, toEmails: " + toEmails, e);

    }
    }
    if (bccEmails != null && bccEmails.size() > 0) {
    InternetAddress[] bccAddresses = new InternetAddress[bccEmails.size()];
    int index = 0;
    for (String email : bccEmails) {
    try {
    bccAddresses[index] = new InternetAddress(email);
    ++index;
    } catch (AddressException e) {
    logger.error("init to address exception, address: " + email, e);

    }
    }
    try {
    message.addRecipients(Message.RecipientType.BCC, bccAddresses);
    } catch (MessagingException e) {
    logger.error("addRecipients exception, bccEmails: " + bccEmails, e);

    }
    }
    try {
    message.setSubject(subject);
    message.setContent(content, "text/html;charset=utf-8");
    } catch (MessagingException e) {
    logger.error("message set content exception, subject: " + subject + ", content: " + content, e);

    return;
    }
    try {
    javaMailSender.send(message);
    } catch (MailException e) {
    logger.error("javaMailSender send mail exception, content:{}, toEmails:{}, {}, {}. ", content, toEmails, e.getClass().getSimpleName(), e.getMessage());

    }
    Profiler.registerInfoEnd(callerInfo);
    }

    private String readVm(String vmPath) {
    SAXReader reader = new SAXReader();
    String content = null;
    String path = null;
    try {
    String classesPath = getClass().getClassLoader().getResource("").toString();
    path = classesPath.substring("file:".length(), classesPath.length() - "classes/".length()) + vmPath;
    Document document = reader.read(new File(path));
    Element element = document.getRootElement();
    Element elementHtml = element.element("html");
    content = elementHtml.asXML();
    } catch (DocumentException e) {
    logger.error("read mail template exception, path: " + path, e);
    }
    return content;
    }

    protected String getBatchVipUpdateNotice(List<Map<String, NewDnsOperInfo>> list) {
    String vmPath = "vm/mailtemplate/emai.vm";
    String content = generatorEmailContent(list, vmPath);
    return content;
    }

    private String generatorEmailContent(List<Map<String, NewDnsOperInfo>> list, String vmPath) {
    String result = "";
    try {
    VelocityEngine ve = new VelocityEngine();

    String classesPath = getClass().getClassLoader().getResource("").toString();
    String path = classesPath.substring("file:".length(), classesPath.length() - "classes/".length());
    ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, path);
    ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    ve.init();

    Template t = ve.getTemplate(vmPath ,"utf-8");
    VelocityContext ctx = new VelocityContext();

    ctx.put("result", list);
    StringWriter sw = new StringWriter();
    t.merge(ctx, sw);
    result = sw.toString();
    }catch(Exception e) {
    logger.error("generator email templete error !",e);
    }
    return result;
    }

    }
    

      

  • 相关阅读:
    pandas 移动列的方法
    D-Link 路由器新漏洞,黑客可远程执行任意命令
    世界第一黑客:未来云安全的威胁
    黑客针对参与Covid-19疫苗分发的公司
    iPhone为盲人自动识别并标记按钮和UI功能
    小心!基于UEFI引导的病毒,重装系统也清除不了
    美国禁用面部识别技术,到底是什么原因?
    Apple的双向无线充电器现已上市,预计最快在本周发货
    警惕黑客通过打印机侵入你的系统
    为什么未来没有密码?黑客还能破解吗?网友:同样危险
  • 原文地址:https://www.cnblogs.com/gstsyyb/p/6164975.html
Copyright © 2011-2022 走看看