com.turt2live.xmail.mail.attachment.MailMessageAttachment.java Source code

Java tutorial

Introduction

Here is the source code for com.turt2live.xmail.mail.attachment.MailMessageAttachment.java

Source

/*******************************************************************************
 * Copyright (C) 2014 Travis Ralston (turt2live)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/

package com.turt2live.xmail.mail.attachment;

import com.turt2live.xmail.XMailMessage;
import com.turt2live.xmail.entity.XMailEntity;
import com.turt2live.xmail.mail.Mail;
import com.turt2live.xmail.utils.General;
import org.bukkit.ChatColor;
import org.json.simple.JSONValue;
import org.json.simple.parser.ContainerFactory;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.util.*;
import java.util.Map.Entry;

/**
 * Represents an attachment for mail messages. With this attachment a whole mail message can be attached.
 *
 * @author turt2live
 */
public class MailMessageAttachment extends Attachment {

    private static final long serialVersionUID = -8787264697552852183L;

    /**
     * An enum to represent what type of message is being attached
     *
     * @author turt2live
     */
    public static enum MessageAttachmentType {
        /**
         * Used when mail is forwarded
         */
        FORWARD,
        /**
         * All other use cases
         */
        OTHER,
        /**
         * Used when mail is replied to
         */
        REPLY;

        public static MessageAttachmentType fromString(String string) {
            for (MessageAttachmentType type : values()) {
                if (type.name().equalsIgnoreCase(string)) {
                    return type;
                }
            }
            return OTHER;
        }
    }

    private Mail mail;

    private MessageAttachmentType mtype;

    /**
     * Creates a new mail message attachment
     *
     * @param mail the mail message to attach
     * @param type the message attachment type
     */
    public MailMessageAttachment(Mail mail, MessageAttachmentType type) {
        if (mail == null) {
            throw new IllegalArgumentException();
        }
        this.mail = mail;
    }

    @Override
    public Attachment clone() {
        return new MailMessageAttachment(mail, mtype);
    }

    @Override
    public Object getContent() {
        return mail;
    }

    /**
     * Gets the mail message attachment type
     *
     * @return the mail message attachment type
     */
    public MessageAttachmentType getMessageAttachmentType() {
        return mtype;
    }

    @Override
    public Object getSerializedContent() {
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("to", mail.getTo());
        map.put("from", mail.getFrom());
        map.put("date", mail.getTimestamp());
        map.put("sent-from", mail.getServerSender());
        map.put("unread", !mail.isRead());
        List<String> tags = mail.getTags();

        // Convert attachments
        List<String> attachments = new ArrayList<String>();
        List<Attachment> lAtt = mail.getAttachments();
        for (Attachment a : lAtt) {
            attachments.add(a.toJson());
        }

        map.put("tags", tags);
        map.put("attachments", attachments);
        map.put("message_type", mtype.name());
        return JSONValue.toJSONString(map);
    }

    @Override
    public AttachmentType getType() {
        return AttachmentType.MAIL;
    }

    @Override
    public boolean giveTo(XMailEntity entity) {
        switch (mtype) {
        case FORWARD:
            XMailMessage.sendMessage(entity, ChatColor.LIGHT_PURPLE + "Forwarded Message:", false);
            break;
        case REPLY:
            XMailMessage.sendMessage(entity, ChatColor.LIGHT_PURPLE + "In Reply To:", false);
        default:
            XMailMessage.sendMessage(entity, ChatColor.LIGHT_PURPLE + "Attached Message:", false);
            break;
        }
        String message = mail.getMessage();
        XMailMessage.sendMessage(entity, ChatColor.DARK_AQUA + "From: " + ChatColor.WHITE + mail.getFrom(), false,
                false);
        XMailMessage.sendMessage(entity, ChatColor.DARK_AQUA + "Message: " + ChatColor.WHITE + message, false,
                false);
        XMailMessage.sendMessage(entity, ChatColor.DARK_AQUA + "Sent: " + ChatColor.WHITE
                + General.getHumanTime(mail.getTimestamp(), plugin.getMailServer().getTimeDiff()), false);
        boolean complex = mail.doesNotHaveAttachmentType(AttachmentType.MESSAGE); // "complex" means "attachments other than message"
        if (complex) {
            XMailMessage.sendMessage(entity,
                    ChatColor.DARK_AQUA + "Attachments: " + ChatColor.YELLOW + mail.getAttachmentSignature(), false,
                    false);
        }
        XMailMessage.sendMessage(entity, ChatColor.LIGHT_PURPLE + "===------===", false);
        return true;
    }

    @Override
    public void onGive(XMailEntity to, Mail mail) {
    }

    /**
     * Sets the message attachment type
     *
     * @param type the new message attachment type
     */
    public void setMessageAttachmentType(MessageAttachmentType type) {
        if (type == null) {
            throw new IllegalArgumentException();
        }
        this.mtype = type;
    }

    @SuppressWarnings("unchecked")
    public static MailMessageAttachment deserializeFromJson(String content) {
        JSONParser parser = new JSONParser();
        ContainerFactory containerFactory = new ContainerFactory() {
            @Override
            public List<Object> creatArrayContainer() {
                return new LinkedList<Object>();
            }

            @Override
            public Map<String, Object> createObjectContainer() {
                return new LinkedHashMap<String, Object>();
            }

        };

        Map<String, Object> map = new HashMap<String, Object>();

        try {
            Map<?, ?> json = (Map<?, ?>) parser.parse(content, containerFactory);
            Iterator<?> iter = json.entrySet().iterator();

            // Type check
            while (iter.hasNext()) {
                Entry<?, ?> entry = (Entry<?, ?>) iter.next();
                if (!(entry.getKey() instanceof String)) {
                    throw new IllegalArgumentException("Not in <String, Object> format");
                }
            }

            map = (Map<String, Object>) json;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return null;
        }
        Mail mail = Mail.fromJSON(map);
        MessageAttachmentType type = MessageAttachmentType.OTHER;
        if (mail != null) {
            Object obj = map.get("message_type");
            if (obj instanceof String) {
                String typestr = (String) obj;
                type = MessageAttachmentType.fromString(typestr);
            }
        }
        return new MailMessageAttachment(mail, type);
    }

}