fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. import java.util.logging.Level;
  9. import java.util.logging.Logger;
  10.  
  11. class Main {
  12.  
  13. public static final String AUSTIN_POWERS = "Austin Powers";
  14. public static final String WEAPONS = "weapons";
  15. public static final String BANNED_SUBSTANCE = "banned substance";
  16.  
  17. //Stepik code: start
  18.  
  19. public static class UntrustworthyMailWorker implements MailService {
  20. private RealMailService innerRealMailService = new RealMailService();
  21. private final MailService[] mailServices;
  22. UntrustworthyMailWorker(MailService[] mailServices) {
  23. this.mailServices = mailServices;
  24. }
  25. public Sendable processMail(Sendable mail) {
  26. Sendable temp = mail;
  27. for (MailService mailService: mailServices) {
  28. temp = mailService.processMail(temp);
  29. }
  30. return innerRealMailService.processMail(temp);
  31. }
  32. public RealMailService getRealMailService() {
  33. return innerRealMailService;
  34. }
  35. }
  36.  
  37. public static class Spy implements MailService{
  38. public Logger logger;
  39. Spy(Logger logger) {
  40. this.logger = logger;
  41. }
  42. public Sendable processMail(Sendable anMail) {
  43. if (anMail instanceof MailMessage) {
  44. MailMessage mail = (MailMessage) anMail;
  45. if (mail.getFrom().equals(AUSTIN_POWERS) || mail.getTo().equals(AUSTIN_POWERS)) {
  46. logger.log(Level.WARNING, "Detected target mail correspondence: from {0} to {1} \"{2}\")", new Object[] {mail.getFrom(), mail.getTo(), mail.getMessage()});
  47. } else {
  48. logger.log(Level.INFO, "Usual correspondence: from {0} to {1}", new Object[] {mail.getFrom(), mail.getTo()});
  49. }
  50. }
  51. return anMail;
  52. }
  53. }
  54.  
  55. public static class Thief implements MailService {
  56. private int minimal, summary = 0;
  57. Thief(int minimal) {
  58. this.minimal = minimal;
  59. }
  60. public int getStolenValue() {
  61. return summary;
  62. }
  63. public Sendable processMail(Sendable anMail) {
  64. if (anMail instanceof MailPackage) {
  65. MailPackage mail = (MailPackage) anMail;
  66. if (mail.getContent().getPrice() >= minimal) {
  67. summary += mail.getContent().getPrice();
  68. return new MailPackage(anMail.getFrom(), anMail.getTo(), new Package("stones instead of " + mail.getContent().getContent(), 0));
  69. }
  70. }
  71. return anMail;
  72. }
  73. }
  74. public static class IllegalPackageException extends RuntimeException {
  75. public IllegalPackageException(String message) {
  76. super(message);
  77. }
  78. public IllegalPackageException(String message, Throwable cause) {
  79. super(message, cause);
  80. }
  81. }
  82.  
  83. public static class StolenPackageException extends RuntimeException {
  84. public StolenPackageException(String message) {
  85. super(message);
  86. }
  87. public StolenPackageException(String message, Throwable cause) {
  88. super(message, cause);
  89. }
  90. }
  91.  
  92. public static class Inspector implements MailService {
  93. public Sendable processMail(Sendable anMail) {
  94. if (anMail instanceof MailPackage) {
  95. MailPackage mail = (MailPackage) anMail;
  96. if (mail.getContent().getContent().contains(WEAPONS) || mail.getContent().getContent().contains(BANNED_SUBSTANCE)) {
  97. throw new IllegalPackageException(mail.getContent().getContent());
  98. }
  99. if (mail.getContent().getContent().contains("stones")) {
  100. throw new StolenPackageException(mail.getContent().getContent());
  101. }
  102. } else if (anMail instanceof MailMessage) {
  103. MailMessage mail = (MailMessage) anMail;
  104. if (mail.getMessage().contains(WEAPONS) || mail.getMessage().contains(BANNED_SUBSTANCE)) {
  105. throw new IllegalPackageException(mail.getMessage());
  106. }
  107. if (mail.getMessage().contains("stones")) {
  108. throw new StolenPackageException(mail.getMessage());
  109. }
  110. }
  111. return anMail;
  112. }
  113. }
  114.  
  115. //Тут Писать свой КОД
  116.  
  117. //Stepik code: end
  118.  
  119. public static void main(String[] args) {
  120. Logger logger = Logger.getLogger(Main.class.getName());
  121. Inspector inspector = new Inspector();
  122. Spy spy = new Spy(logger);
  123. Thief thief = new Thief(10000);
  124. UntrustworthyMailWorker worker = new UntrustworthyMailWorker(new MailService[]{spy, thief, inspector});
  125. AbstractSendable[] correspondence = {
  126. new MailMessage("Oxxxymiron", "Гнойный", " Я здесь чисто по фану, поглумиться над слабым\n" +
  127. "Ты же вылез из мамы под мой дисс на Бабана...."),
  128. new MailMessage("Гнойный", "Oxxxymiron", "....Что? Так болел за Россию, что на нервах терял ганглии.\n" +
  129. "Но когда тут проходили митинги, где ты сидел? В Англии!...."),
  130. new MailMessage("Жириновский", AUSTIN_POWERS, "Бери пацанов, и несите меня к воде."),
  131. new MailMessage(AUSTIN_POWERS, "Пацаны", "Го, потаскаем Вольфовича как Клеопатру"),
  132. new MailPackage("берег", "море", new Package("ВВЖ", 32)),
  133. new MailMessage("NASA", AUSTIN_POWERS, "Найди в России ракетные двигатели и лунные stones"),
  134. new MailPackage(AUSTIN_POWERS, "NASA", new Package("ракетный двигатель ", 2500000)),
  135. new MailPackage(AUSTIN_POWERS, "NASA", new Package("stones ", 1000)),
  136. new MailPackage("Китай", "КНДР", new Package("banned substance ", 10000)),
  137. new MailPackage(AUSTIN_POWERS, "Жопа запрещенная группировка", new Package("tiny bomb", 9000)),
  138. new MailMessage(AUSTIN_POWERS, "Психиатр", "Помогите"),
  139. };
  140.  
  141. for (AbstractSendable p : correspondence) {
  142. try {
  143. print("До: ", p);
  144. Sendable sendable = worker.processMail(p);
  145. print("После: ", sendable);
  146. } catch (StolenPackageException | IllegalPackageException e) {
  147. logger.log(Level.WARNING, "из: " + p.getFrom() + " куда: " + p.getTo() + " Содержимое: "
  148. + (p instanceof MailMessage ? ((MailMessage) p).getMessage() : ((MailPackage) p).getContent().getContent()
  149. + " Цена=" + ((MailPackage) p).getContent().getPrice()) + " Exceptions: " + e);
  150. }
  151. }
  152. }
  153.  
  154. public static void print(String prefix, Sendable p) {
  155. System.out.println(prefix + "из: " + p.getFrom() + " куда: " + p.getTo() + " Содержимое: "
  156. + (p instanceof MailMessage ? ((MailMessage) p).getMessage() : ((MailPackage) p).getContent().getContent()
  157. + " Цена=" + ((MailPackage) p).getContent().getPrice()));
  158. }
  159. /*
  160.   Интерфейс: сущность, которую можно отправить по почте.
  161.   У такой сущности можно получить от кого и кому направляется письмо.
  162.   */
  163. public static interface Sendable {
  164. String getFrom();
  165. String getTo();
  166. }
  167. /*
  168.   Абстрактный класс,который позволяет абстрагировать логику хранения
  169.   источника и получателя письма в соответствующих полях класса.
  170.   */
  171. public static abstract class AbstractSendable implements Sendable {
  172. protected final String from;
  173. protected final String to;
  174.  
  175. public AbstractSendable(String from, String to) {
  176. this.from = from;
  177. this.to = to;
  178. }
  179.  
  180. @Override
  181. public String getFrom() {
  182. return from;
  183. }
  184.  
  185. @Override
  186. public String getTo() {
  187. return to;
  188. }
  189.  
  190. @Override
  191. public boolean equals(Object o) {
  192. if (this == o) return true;
  193. if (o == null || getClass() != o.getClass()) return false;
  194. AbstractSendable that = (AbstractSendable) o;
  195. if (!from.equals(that.from)) return false;
  196. if (!to.equals(that.to)) return false;
  197. return true;
  198. }
  199. }
  200. /*
  201.   Письмо, у которого есть текст, который можно получить с помощью метода `getMessage`
  202.   */
  203. public static class MailMessage extends AbstractSendable {
  204. private final String message;
  205.  
  206. public MailMessage(String from, String to, String message) {
  207. super(from, to);
  208. this.message = message;
  209. }
  210.  
  211. public String getMessage() {
  212. return message;
  213. }
  214.  
  215. @Override
  216. public boolean equals(Object o) {
  217. if (this == o) return true;
  218. if (o == null || getClass() != o.getClass()) return false;
  219. if (!super.equals(o)) return false;
  220. MailMessage that = (MailMessage) o;
  221. if (message != null ? !message.equals(that.message) : that.message != null) return false;
  222. return true;
  223. }
  224. }
  225. /*
  226.   Посылка, содержимое которой можно получить с помощью метода `getContent`
  227.   */
  228. public static class MailPackage extends AbstractSendable {
  229. private final Package content;
  230.  
  231. public MailPackage(String from, String to, Package content) {
  232. super(from, to);
  233. this.content = content;
  234. }
  235.  
  236. public Package getContent() {
  237. return content;
  238. }
  239.  
  240. @Override
  241. public boolean equals(Object o) {
  242. if (this == o) return true;
  243. if (o == null || getClass() != o.getClass()) return false;
  244. if (!super.equals(o)) return false;
  245. MailPackage that = (MailPackage) o;
  246. if (!content.equals(that.content)) return false;
  247. return true;
  248. }
  249. }
  250. /*
  251.   Класс, который задает посылку. У посылки есть текстовое описание содержимого и целочисленная ценность.
  252.   */
  253. public static class Package {
  254. private final String content;
  255. private final int price;
  256.  
  257. public Package(String content, int price) {
  258. this.content = content;
  259. this.price = price;
  260. }
  261.  
  262. public String getContent() {
  263. return content;
  264. }
  265.  
  266. public int getPrice() {
  267. return price;
  268. }
  269.  
  270. @Override
  271. public boolean equals(Object o) {
  272. if (this == o) return true;
  273. if (o == null || getClass() != o.getClass()) return false;
  274.  
  275. Package aPackage = (Package) o;
  276.  
  277. if (price != aPackage.price) return false;
  278. if (!content.equals(aPackage.content)) return false;
  279.  
  280. return true;
  281. }
  282. }
  283.  
  284. /*
  285.   Интерфейс, который задает класс, который может каким-либо образом обработать почтовый объект.
  286.   */
  287. public static interface MailService {
  288. Sendable processMail(Sendable mail);
  289. }
  290.  
  291. /*
  292.   Класс, в котором скрыта логика настоящей почты
  293.   */
  294. public static class RealMailService implements MailService {
  295.  
  296. @Override
  297. public Sendable processMail(Sendable mail) {
  298. // Здесь описан код настоящей системы отправки почты.
  299. return mail;
  300. }
  301. }
  302. }
Success #stdin #stdout #stderr 0.27s 43068KB
stdin
Standard input is empty
stdout
До:  из: Oxxxymiron куда: Гнойный Содержимое:  Я здесь чисто по фану, поглумиться над слабым
Ты же вылез из мамы под мой дисс на Бабана....
После:  из: Oxxxymiron куда: Гнойный Содержимое:  Я здесь чисто по фану, поглумиться над слабым
Ты же вылез из мамы под мой дисс на Бабана....
До:  из: Гнойный куда: Oxxxymiron Содержимое: ....Что? Так болел за Россию, что на нервах терял ганглии.
Но когда тут проходили митинги, где ты сидел? В Англии!....
После:  из: Гнойный куда: Oxxxymiron Содержимое: ....Что? Так болел за Россию, что на нервах терял ганглии.
Но когда тут проходили митинги, где ты сидел? В Англии!....
До:  из: Жириновский куда: Austin Powers Содержимое: Бери пацанов, и несите меня к воде.
После:  из: Жириновский куда: Austin Powers Содержимое: Бери пацанов, и несите меня к воде.
До:  из: Austin Powers куда: Пацаны Содержимое: Го, потаскаем Вольфовича как Клеопатру
После:  из: Austin Powers куда: Пацаны Содержимое: Го, потаскаем Вольфовича как Клеопатру
До:  из: берег куда: море Содержимое: ВВЖ Цена=32
После:  из: берег куда: море Содержимое: ВВЖ Цена=32
До:  из: NASA куда: Austin Powers Содержимое: Найди в России ракетные двигатели и лунные stones
До:  из: Austin Powers куда: NASA Содержимое: ракетный двигатель  Цена=2500000
До:  из: Austin Powers куда: NASA Содержимое: stones  Цена=1000
До:  из: Китай куда: КНДР Содержимое: banned substance  Цена=10000
До:  из: Austin Powers куда: Жопа запрещенная группировка Содержимое: tiny bomb Цена=9000
После:  из: Austin Powers куда: Жопа запрещенная группировка Содержимое: tiny bomb Цена=9000
До:  из: Austin Powers куда: Психиатр Содержимое: Помогите
После:  из: Austin Powers куда: Психиатр Содержимое: Помогите
stderr
Jan 02, 2020 12:41:42 AM Main$Spy processMail
INFO: Usual correspondence: from Oxxxymiron to Гнойный
Jan 02, 2020 12:41:42 AM Main$Spy processMail
INFO: Usual correspondence: from Гнойный to Oxxxymiron
Jan 02, 2020 12:41:42 AM Main$Spy processMail
WARNING: Detected target mail correspondence: from Жириновский to Austin Powers "Бери пацанов, и несите меня к воде.")
Jan 02, 2020 12:41:42 AM Main$Spy processMail
WARNING: Detected target mail correspondence: from Austin Powers to Пацаны "Го, потаскаем Вольфовича как Клеопатру")
Jan 02, 2020 12:41:42 AM Main$Spy processMail
WARNING: Detected target mail correspondence: from NASA to Austin Powers "Найди в России ракетные двигатели и лунные stones")
Jan 02, 2020 12:41:42 AM Main main
WARNING: из: NASA куда: Austin Powers Содержимое: Найди в России ракетные двигатели и лунные stones Exceptions: Main$StolenPackageException: Найди в России ракетные двигатели и лунные stones
Jan 02, 2020 12:41:42 AM Main main
WARNING: из: Austin Powers куда: NASA Содержимое: ракетный двигатель  Цена=2500000 Exceptions: Main$StolenPackageException: stones instead of ракетный двигатель 
Jan 02, 2020 12:41:42 AM Main main
WARNING: из: Austin Powers куда: NASA Содержимое: stones  Цена=1000 Exceptions: Main$StolenPackageException: stones 
Jan 02, 2020 12:41:42 AM Main main
WARNING: из: Китай куда: КНДР Содержимое: banned substance  Цена=10000 Exceptions: Main$IllegalPackageException: stones instead of banned substance 
Jan 02, 2020 12:41:42 AM Main$Spy processMail
WARNING: Detected target mail correspondence: from Austin Powers to Психиатр "Помогите")