ActiveMQを使用したメール認証コードの送信

7958 ワード

package cn.itcast.bos.web.action;
/**
 * 1.        ,  4     (   ),   session ,            
 * 2.      ,            ,    session      ,    ,   ,  action;
 * 3.      ,   32      (   ),       redis(key          ) ,       24  ,                ;
 * 4.         ,              
 * 5.    :             ,      ,     , customer  type    1(   : null)
 * */
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.utils.MailUtils;
import cn.itcast.crm.domain.Customer;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class CustomerAction extends ActionSupport implements
		ModelDriven {

	private Customer customer = new Customer();

	@Override
	public Customer getModel() {
		return customer;
	}
	//  jmsTemplate
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;

	@Action(value = "customer_sendSms")
	public String sendSms() throws UnsupportedEncodingException {
		//       Customer    
		//        
		String randomNumeric = RandomStringUtils.randomNumeric(4);
		//          session  
		ServletActionContext.getRequest().getSession()
				.setAttribute(customer.getTelephone(), randomNumeric);
		//             
		System.out.println(randomNumeric);

		//        
		final String msg = "hello,your number" + randomNumeric + "    :88888888";
		System.out.println(msg);
		
		//  MQ    (            :bos_sms)
		jmsTemplate.send("bos_sms",new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", customer.getTelephone());
				mapMessage.setString("msg", msg);
				return mapMessage;
				
			}
		});
		return NONE;
		/*
		 * 
		 *		   MQ        
		 *
		//   sms      
		//       ,       
		// String sendSmsByHTTP =
		// SmsUtils.sendSmsByHTTP(customer.getTelephone(), msg);

		String sendSmsByHTTP = "000/***";
		//          "000",       
		if (sendSmsByHTTP.startsWith("000")) {
			//     
			return NONE;
		} else {
			throw new RuntimeException("    " + sendSmsByHTTP);
		}
		 **/
	}
	//     ,         ,        

	// 1.     

	//     
	private String checkcode;

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	@Autowired
	private RedisTemplate redisTemplate;//        (       redis)

	@Action(value = "customer_regist", results = {
			@Result(name = "success", type = "redirect", location = "signup-success.html"),
			@Result(name = "input", type = "redirect", location = "signup.html") })
	public String regist() {
		//       session     ,             
		String checkcodeSession = (String) ServletActionContext.getRequest()
				.getSession().getAttribute(customer.getTelephone());
		if (checkcodeSession == null || !checkcodeSession.equals(checkcode)) {
			System.out.println("           ");
			return INPUT;
		}
		//   webService  CRM      
		WebClient
				.create("http://localhost:9002/crm_management/services"
						+ "/customerService/customer")
				.type(MediaType.APPLICATION_JSON).post(customer);
		System.out.println("     ,    ");

		// 2.      
		//      
		String randomNumeric = RandomStringUtils.randomNumeric(32);
		//        redis  ,     24  
		System.out.println(customer.getTelephone());
		System.out.println(randomNumeric);
		redisTemplate.opsForValue().set(customer.getTelephone(), randomNumeric,
				24, TimeUnit.HOURS);

		//   MailUtils    
		String content = "       ,  24   ,         ,          :
メールアドレス"; MailUtils.sendMail(" ", content, customer.getEmail()); return SUCCESS; } // // activecode( ) private String activecode; public void setActivecode(String activecode) { this.activecode = activecode; } @Action(value = "customer_activeMail") public String activeMail() throws IOException { ServletActionContext.getResponse().setContentType( "text/html;charset=utf-8"); // ( ) String randomNumeric = redisTemplate.opsForValue().get( customer.getTelephone()); if (randomNumeric == null || !randomNumeric.equals(activecode)) { // , --> ServletActionContext.getResponse().getWriter().print(" , "); } else { // , Customer customer2 = WebClient .create("http://localhost:9002/crm_management/services" + "/customerService/customer/telephone/" + customer.getTelephone()) .accept(MediaType.APPLICATION_JSON).get(Customer.class); if(customer2.getType()==null || customer2.getType() != 1){ // , CRM WebClient .create("http://localhost:9002/crm_management/services" + "/customerService/customer/updatetype/" + customer.getTelephone()).get(); ServletActionContext.getResponse().getWriter().print(" "); }else{ ServletActionContext.getResponse().getWriter().print(" , "); } // redisTemplate.delete(customer.getTelephone()); } return NONE; } }

1.ページは「検証コードを取得する」をクリックし、Customerで業務を処理し、検証コードとして4ビットの乱数を取得し、sessionドメインに保存し、登録時に検証コードが正しいかどうかを検証する.
2.メールを送るには電話番号、メール内容を'bos_に渡すだけです.sms′インタフェースで送信(MQを用いる).
package cn.itcast.bos.mq;

import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;

import org.springframework.stereotype.Service;


@Service("smsConsumer")
public class SmsConsumer implements MessageListener {
	
	@Override
	public void onMessage(Message message) {
		MapMessage mapMessage = (MapMessage) message;
		try {
		
			/*
			 * String result = SmsUtils.sendSmsByHTTP(
			 * mapMessage.getString("telephone"), mapMessage.getString("msg"));
			 */

			//       ,       ;
			String result = "000/***";
			if (result.startsWith("000")) {
				System.out.println("    :" + mapMessage.getString("telephone")
						+ "==   :" + mapMessage.getString("msg")
						+ "==============    ");
			} else {
				//     
				throw new RuntimeException("    ");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

3.ショートメッセージ送信に成功すると'000'文字列が返されるので、テストを容易にするために、戻り値を'000/**'と直接書きます.