All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.gitlab.summercattle.addons.wechat.officialaccounts.message.send.AbstractSendMessage Maven / Gradle / Ivy

The newest version!
/*
 * Copyright (C) 2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitlab.summercattle.addons.wechat.officialaccounts.message.send;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.gitlab.summercattle.commons.exception.CommonException;
import com.gitlab.summercattle.commons.utils.auxiliary.Dom4jUtils;

/**
 * 发送消息抽象
 * @author orange
 *
 */
public abstract class AbstractSendMessage {

	private String fromUserName;

	private String toUserName;

	/**
	 * 发送消息类型
	 * @return 发送消息类型
	 */
	public abstract SendMessageType getType();

	/**
	 * 设置Xml
	 * @param element Xml要素
	 * @throws CommonException 异常
	 */
	public abstract void setXml(Element element) throws CommonException;

	/**
	 * 消息检查
	 * @throws CommonException 异常
	 */
	abstract void messageCheck() throws CommonException;

	public AbstractSendMessage(String fromUserName, String toUserName) {
		this.fromUserName = fromUserName;
		this.toUserName = toUserName;
	}

	private void check() throws CommonException {
		if (StringUtils.isBlank(fromUserName)) {
			throw new CommonException("开发者微信号为空");
		}
		if (StringUtils.isBlank(toUserName)) {
			throw new CommonException("接收方帐号为空");
		}
		messageCheck();
	}

	public String toStringData() throws CommonException {
		check();
		Document document = DocumentHelper.createDocument();
		Element rootElement = document.addElement("xml");
		rootElement.addElement("ToUserName").add(DocumentHelper.createCDATA(toUserName));
		rootElement.addElement("FromUserName").add(DocumentHelper.createCDATA(fromUserName));
		long createTime = (new Date()).getTime() / 1000;
		rootElement.addElement("CreateTime").setText(String.valueOf(createTime));
		rootElement.addElement("MsgType").add(DocumentHelper.createCDATA(getType().toString().toLowerCase()));
		setXml(rootElement);
		return Dom4jUtils.asXmlWithoutPretty(rootElement, "UTF-8");
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy