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;
    }

    }
    

      

  • 相关阅读:
    BZOJ 3205 [Apio2013]机器人 ——斯坦纳树
    BZOJ 3782 上学路线 ——动态规划 Lucas定理 中国剩余定理
    HDU 1423 Greatest Common Increasing Subsequence ——动态规划
    BZOJ 3309 DZY Loves Math ——莫比乌斯反演
    POJ 1038 Bugs Integrated, Inc. ——状压DP
    POJ 3693 Maximum repetition substring ——后缀数组
    POJ 2699 The Maximum Number of Strong Kings ——网络流
    POJ 2396 Budget ——有上下界的网络流
    BZOJ 4650 [Noi2016]优秀的拆分 ——后缀数组
    源码安装python
  • 原文地址:https://www.cnblogs.com/gstsyyb/p/6164975.html
Copyright © 2011-2022 走看看