001package de.deepamehta.plugins.mail; 002 003import java.util.HashMap; 004import java.util.HashSet; 005import java.util.Map; 006import java.util.Set; 007 008import org.codehaus.jettison.json.JSONArray; 009import org.codehaus.jettison.json.JSONObject; 010 011import de.deepamehta.core.JSONEnabled; 012import de.deepamehta.core.Topic; 013import de.deepamehta.core.util.DeepaMehtaUtils; 014 015public class StatusReport implements JSONEnabled { 016 017 private String message; 018 019 private Topic topic; 020 021 // error code > topic id > topic specific message 022 private Map<MailError, Set<String>> errors = new HashMap<MailError, Set<String>>(); 023 024 public StatusReport(Topic topic) { 025 this.topic = topic; 026 } 027 028 public void addError(MailError error, String message) { 029 Set<String> messages = errors.get(error); 030 if (messages == null) { 031 messages = new HashSet<String>(); 032 errors.put(error, messages); 033 } 034 messages.add(message); 035 } 036 037 public void setMessage(String message) { 038 this.message = message; 039 } 040 041 public void setTopic(Topic topic) { 042 this.topic = topic; 043 } 044 045 public boolean hasErrors() { 046 return errors.isEmpty() ? false : true; 047 } 048 049 @Override 050 public JSONObject toJSON() { 051 try { 052 JSONObject json = new JSONObject()// 053 .put("message", message)// 054 .put("success", hasErrors() ? false : true)// 055 .put("topic_id", topic.getId()); 056 if (errors.isEmpty() == false) { // map error messages 057 JSONArray jsonErrors = new JSONArray(); 058 for (MailError mailError : errors.keySet()) { 059 JSONArray stringsToJson = DeepaMehtaUtils.stringsToJson(errors.get(mailError)); 060 jsonErrors.put(new JSONObject()// 061 .put("message", mailError.getMessage())// 062 .put("topics", stringsToJson)); 063 } 064 json.put("errors", jsonErrors); 065 } 066 return json; 067 } catch (Exception e) { 068 throw new RuntimeException("Serialization failed (" + this + ")", e); 069 } 070 } 071}