java 发邮件,发短信,发送iosPush,

发邮件

package com.jt.xiaoyang.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.template.Template;
import freemarker.template.TemplateException;

@Component
public class MailSender {
	
	@Resource(name = "javaMailSender")
	private JavaMailSender javaMailSender;
	
//	@Resource(name = "configuration")
//	private Configuration configuration = new Configuration();
	
	@Resource(name = "freeMarkerConfig")
	private FreeMarkerConfigurer freeMarkerConfigurer;
	
	private static Logger _log = Logger.getLogger("email");
	
	public boolean senderTxt(String to, String cc, String content) {
		return true;
	}
	
	@Async
	public void senderHtml(String to, String[] cc, String title, String content, String account) {
		_log.info("send mail::" + to + "|" + cc + "|" + title + "|" + content);
		MimeMessage mailMessage = javaMailSender.createMimeMessage();
		try {
			MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");
			messageHelper.setTo(to);//接受者
			if (cc != null && cc.length > 0) {
				messageHelper.setCc(cc);
			}
			
			Template template = freeMarkerConfigurer.getConfiguration().getTemplate("tpls/mail_common.ftl");// = configuration.getTemplate("tpls/mail_common.ftl");
//			StringWriter sw = new StringWriter();
			Map<String,Object> param = new HashMap<String, Object>();
			param.put("catpcha", content);
			String finalContent = FreeMarkerTemplateUtils.processTemplateIntoString(template, param);
			
//			template.process(param, sw);
			
			InternetAddress address = new InternetAddress("message@demodemo.cc", "小样儿");
			messageHelper.setFrom(address);//发送者
			messageHelper.setSubject(title);//主题 
			messageHelper.setText(finalContent, true);
			javaMailSender.send(mailMessage);  
			_log.info("发送完毕");
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
发短信

package com.jt.xiaoyang.util;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.jt.core4.log.MyLogger;

@Component
public class SmsSender {
	
	static MyLogger logger = MyLogger.getMyLogger(SmsSender.class);
	
	@Async
	public void sender(String mobile, String content) {
		sender(mobile, content, 3);
	}
	
	private void sender(String mobile, String content, int times) {
		if (!content.endsWith("【小样儿】")) {
			content = content + "【小样儿】";
		}
		
		String httpPath = "http://58.68.247.137:9053/communication/sendSms.ashx";//提供服务的第三方
		StringBuffer params = new StringBuffer();
		//客户端ID
		String cid="8175";
		//客户端密码
		String pwd="rzcj123";
		//通道组id
		String productid="20760601";
		//子号码
		String lcode="";
		//短信唯一标识,用于匹配状态报告
//		String ssid="100000";
		String ssid = System.currentTimeMillis()+"";
		//短信类型:15普通短信,32长短信
		String format="32";
		//客户自定义签名,可以不填
		String sign="";
		//客户自定义内容,目前没有用到,不用填写
		String custom="";

		params = new StringBuffer();
		//content=content+a;
		
		//mobile=mobile+1;
		try {
			params.append("cid=").append(CodingUtils.encodeBase64URL(cid))
			.append("&").append("pwd=").append(CodingUtils.encodeBase64URL(pwd))
			.append("&").append("productid=").append(CodingUtils.encodeURL(productid))
			.append("&").append("mobile=").append(CodingUtils.encodeBase64URL(mobile+""))
			.append("&").append("content=").append(CodingUtils.encodeBase64URL(content))
			.append("&").append("lcode=").append(lcode)
			.append("&").append("ssid=").append(ssid)
			.append("&").append("format=").append(format)
			.append("&").append("sign=").append(CodingUtils.encodeBase64URL(sign))
			.append("&").append("custom=").append(CodingUtils.encodeURL(custom));
			
			logger.info("开始发送:mobile=" + mobile + ",content=" + content);
			logger.info("URL:" + httpPath + params.toString());
			String result=HttpUtil.sendPostRequestByParam(httpPath,params.toString());
			System.out.println("1发送结果:"+result);
			logger.info("发送结果:"+result);
		} catch(Exception ex) {
			ex.printStackTrace();
			
			times--;
			if (times > 0) {
				logger.info(mobile+"发送失败,重发:" + times);
				sender(mobile, content, times);
			}
			
		}
	}

}
HttpUtil工具类,为上面的类提供服务

package com.jt.xiaoyang.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtil {
	
	public static String sendPostRequestByParam(String path, String params)
			throws Exception {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		conn.setRequestMethod("POST");// 提交模式
		conn.setDoOutput(true);// 是否输入参数
		byte[] bypes = params.toString().getBytes();
		conn.getOutputStream().write(bypes);// 输入参数
		InputStream inStream = conn.getInputStream();
		return new String(readInputStream(inStream));
	}
	
	/**
	 * 从输入流中读取数据
	 * 
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	public static byte[] readInputStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();// 网页的二进制数据
		outStream.close();
		inStream.close();
		return data;
	}

}

IOS Push


package com.jt.xiaoyang.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javapns.communication.exceptions.KeystoreException;
import javapns.devices.exceptions.InvalidDeviceTokenFormatException;
import javapns.notification.AppleNotificationServer;
import javapns.notification.AppleNotificationServerBasicImpl;
import javapns.notification.PayloadPerDevice;
import javapns.notification.PushNotificationPayload;
import javapns.notification.transmission.NotificationProgressListener;
import javapns.notification.transmission.NotificationThread;
import javapns.notification.transmission.NotificationThreads;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.json.JSONException;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.jt.core4.authenticator.AuthenticatorHelper;
import com.jt.core4.json.JtObjectMapper;
import com.jt.core4.log.MyLogger;
import com.jt.system.user.dao.XyUserPropertyDaoImpl;
import com.jt.system.user.model.XyUserProperty;
import com.jt.xiaoyang.friend.dao.XyUserFriendDaoImpl;
import com.jt.xiaoyang.friend.model.XyUserFriend;
import com.jt.xiaoyang.message.dao.XyFriendMessageDaoImpl;
import com.jt.xiaoyang.message.dao.XyMessageDaoImpl;
import com.jt.xiaoyang.message.model.XyFriendMessage;
import com.jt.xiaoyang.message.model.XyMessage;
import com.jt.xiaoyang.works.dao.XyWorksCommentDaoImpl;
import com.jt.xiaoyang.works.dao.XyWorksPrivacyDaoImpl;
import com.jt.xiaoyang.works.service.WorksServiceImpl;

@Component
public class IOSPush {
	
	@Resource
	private XyUserPropertyDaoImpl userPropertyDaoImpl;
	
	@Resource
	private XyWorksCommentDaoImpl worksCommentDaoImpl;
	
	@Resource
	private XyWorksPrivacyDaoImpl worksPrivacyDaoImpl;
	
	@Resource
	private XyUserFriendDaoImpl userFriendDaoImpl;
	
	@Resource
	private XyMessageDaoImpl messageDaoImpl;
	
	@Resource
	private XyFriendMessageDaoImpl friendMessageDaoImpl;
	
	String keystore = "";
	String password = CommonUtils.getIOSCertificatePassword();
	int threadThreads = 10; // 线程数
	
	private JtObjectMapper mapper = JtObjectMapper.getInstance();
	
	static MyLogger logger = MyLogger.getMyLogger(IOSPush.class);
	
	public final NotificationProgressListener DEBUGGING_PROGRESS_LISTENER = new NotificationProgressListener() {  
        public void eventThreadStarted(NotificationThread notificationThread) {  
            logger.info("   [EVENT]: thread #" + notificationThread.getThreadNumber() + " started with " + " devices beginning at message id #" + notificationThread.getFirstMessageIdentifier());  
        }  
        public void eventThreadFinished(NotificationThread thread) {  
            logger.info("   [EVENT]: thread #" + thread.getThreadNumber() + " finished: pushed messages #" + thread.getFirstMessageIdentifier() + " to " + thread.getLastMessageIdentifier() + " toward "+ " devices");  
        }  
        public void eventConnectionRestarted(NotificationThread thread) {  
            logger.info("   [EVENT]: connection restarted in thread #" + thread.getThreadNumber() + " because it reached " + thread.getMaxNotificationsPerConnection() + " notifications per connection");  
        }  
        public void eventAllThreadsStarted(NotificationThreads notificationThreads) {  
            logger.info("   [EVENT]: all threads started: " + notificationThreads.getThreads().size());  
        }  
        public void eventAllThreadsFinished(NotificationThreads notificationThreads) {  
            logger.info("   [EVENT]: all threads finished: " + notificationThreads.getThreads().size());  
        }  
        public void eventCriticalException(NotificationThread notificationThread, Exception exception) {  
            logger.info("   [EVENT]: critical exception occurred: " + exception);  
        }  
    };  
	
    @Async
	public void push(String content, String toDeviceToken, Map<String, String> customDict) {
    	logger.info("=============================push::" + content + "-" + toDeviceToken);
    	if (toDeviceToken == null) {
    		return;
    	}
    	toDeviceToken = toDeviceToken.replaceAll(" ", "").replaceAll("<", "").replaceAll(">", "");
    	
//    	keystore = "/home/t_demo/DemoDemo_Production_Push.p12";
    	keystore = CommonUtils.getIOSCertificatePath();
//    	HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
//		keystore = request.getSession().getServletContext().getInitParameter("ios_certificate_path");
		boolean production = true; // 设置true为正式服务地址,false为开发者地址
		// 建立与Apple服务器连接  
        try {
        	logger.info("*****************************开始建立与Apple服务器连接 *********************************");
        	logger.info("----------证书路径是:"+keystore+"------------------------------------------");
			AppleNotificationServer server = new AppleNotificationServerBasicImpl(keystore, password, production);
			List<PayloadPerDevice> list = new ArrayList<PayloadPerDevice>();
			PushNotificationPayload payload = new PushNotificationPayload();
			payload.addAlert(content);
			payload.addSound("default");// 声音 
			payload.addBadge(1);//图标小红圈的数值 
			for (Iterator<Entry<String, String>> iter = customDict.entrySet().iterator(); iter.hasNext();) {
				Entry<String, String> entry = iter.next();
				payload.addCustomDictionary(entry.getKey(), entry.getValue()); // 添加字典 
			}
			
			PayloadPerDevice pay = new PayloadPerDevice(payload, toDeviceToken);// 将要推送的消息和手机唯一标识绑定  
			list.add(pay);
			logger.info("………………………………………………………………list:"+list+"………………………………………………………………");
			NotificationThreads work = new NotificationThreads(server,list,threadThreads);
			work.setListener(DEBUGGING_PROGRESS_LISTENER);// 对线程的监听,一定要加上这个监听
			work.start(); // 启动线程
			work.waitForAllThreads();// 等待所有线程启动完成
			logger.info("============================线程启动完成=======================================");
			
		} catch (KeystoreException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (InvalidDeviceTokenFormatException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}  
	}
    
    public static void main(String[] args) {
    	String token = "<3e0fcce9 3548963a 617a28ad 7451ad1f bedf6dae bf73ba33 37fe361c f4fb4550>";
    	token = token.replaceAll(" ", "").replaceAll("<", "").replaceAll(">", "");
    	IOSPush push = new IOSPush();
    	
    	Map<String, String> customDict = new HashMap<String, String>();
    	customDict.put("a", "a");
    	push.push("主要是先看样式上OK,OK了后,部署到服务器,再测业务流程是否正确,然后就彻底OK了。", token, customDict);
    }



}

CommonsUtil 为上面的类提供服务

package com.jt.xiaoyang.util;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class CommonUtils {
	
	public static String[] banWord = new String[]{"官方", "小样儿demo", "小样儿官方", "demo官方", "官方微博", "官方账号"};
	
	public static String getIOSCertificatePath() {
//		if (1 == 1) {
//			return "D:\\workspace\\xiaoyang\\xiaoyang-server\\DemoDemo_push_services_test.p12";
//		}
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		String path = request.getSession().getServletContext().getInitParameter("ios_certificate_path");
		return path;
	}

	/**
	 * 检查是否为非法昵称
	 * @param nickname
	 * @return
	 */
	public static boolean checkNickname(String nickname) {
		for (String word : banWord) {
			if (nickname.indexOf(word) > -1) {
				return false;
			}
		}
		return true;
	}
	
	public static String getIOSCertificatePassword() {
		return "123456";
	}

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值