diff --git a/.gitignore b/.gitignore index f1e9957cfa..a4f6f3d915 100644 --- a/.gitignore +++ b/.gitignore @@ -280,6 +280,22 @@ target liuxin/.DS_Store liuxin/src/.DS_Store +students/1005475328/* +students/1329920463/* +students/1452302762/* +students/14703250/* +students/2842295913/* +students/383117348/* +students/404481481/* +students/406400373/* +students/549739951/* +students/582161208/* +students/592146505/* +students/844620174/* +students/87049319/* +students/183549495/* + + diff --git a/liuxin/data-structure/answer/src/main/java/com/coding/basic/tree/BinarySearchTreeTest.java b/liuxin/data-structure/answer/src/main/java/com/coding/basic/tree/BinarySearchTreeTest.java index 590e60306c..3da4625faf 100644 --- a/liuxin/data-structure/answer/src/main/java/com/coding/basic/tree/BinarySearchTreeTest.java +++ b/liuxin/data-structure/answer/src/main/java/com/coding/basic/tree/BinarySearchTreeTest.java @@ -104,5 +104,7 @@ public void testIsValid() { public void testGetNodesBetween(){ List numbers = this.tree.getNodesBetween(3, 8); Assert.assertEquals("[3, 4, 5, 6, 8]",numbers.toString()); + numbers = this.tree.getNodesBetween(1, 8); + Assert.assertEquals("[1, 2, 3, 4, 5, 6, 8]",numbers.toString()); } } diff --git a/liuxin/knowledge-point/pom.xml b/liuxin/knowledge-point/pom.xml new file mode 100644 index 0000000000..3dc438c7d9 --- /dev/null +++ b/liuxin/knowledge-point/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + knowledge-point + 0.0.1-SNAPSHOT + jar + + knowledge-point + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/liuxin/knowledge-point/src/main/java/cas/CASSequence.java b/liuxin/knowledge-point/src/main/java/cas/CASSequence.java new file mode 100644 index 0000000000..dcff77d9bf --- /dev/null +++ b/liuxin/knowledge-point/src/main/java/cas/CASSequence.java @@ -0,0 +1,18 @@ +package cas; + +import java.util.concurrent.atomic.AtomicInteger; + +public class CASSequence{ + + private AtomicInteger count = new AtomicInteger(0); + + public int next(){ + while(true){ + int current = count.get(); + int next = current +1; + if(count.compareAndSet(current, next)){ + return next; + } + } + } +} \ No newline at end of file diff --git a/liuxin/knowledge-point/src/main/java/cas/NoBlockingStack.java b/liuxin/knowledge-point/src/main/java/cas/NoBlockingStack.java new file mode 100644 index 0000000000..d7be44c69a --- /dev/null +++ b/liuxin/knowledge-point/src/main/java/cas/NoBlockingStack.java @@ -0,0 +1,34 @@ +package cas; + +import java.util.concurrent.atomic.AtomicReference; + +public class NoBlockingStack { + static class Node { + final E item; + Node next; + public Node(E item) { this.item = item; } + } + + AtomicReference> head = new AtomicReference>(); + + public void push(E item) { + Node newHead = new Node(item); + Node oldHead; + do { + oldHead = head.get(); + newHead.next = oldHead; + } while (!head.compareAndSet(oldHead, newHead)); + } + public E pop() { + Node oldHead; + Node newHead; + do { + oldHead = head.get(); + if (oldHead == null) + return null; + newHead = oldHead.next; + } while (!head.compareAndSet(oldHead,newHead)); + return oldHead.item; + } + +} diff --git a/liuxin/knowledge-point/src/main/java/cas/Sequence.java b/liuxin/knowledge-point/src/main/java/cas/Sequence.java new file mode 100644 index 0000000000..688224e251 --- /dev/null +++ b/liuxin/knowledge-point/src/main/java/cas/Sequence.java @@ -0,0 +1,11 @@ +package cas; + +public class Sequence{ + + private int value; + + public int next(){ + return value ++; + } + +} diff --git a/liuxin/knowledge-point/src/main/java/threadlocal/Context.java b/liuxin/knowledge-point/src/main/java/threadlocal/Context.java new file mode 100644 index 0000000000..d84584397b --- /dev/null +++ b/liuxin/knowledge-point/src/main/java/threadlocal/Context.java @@ -0,0 +1,20 @@ +package threadlocal; +import java.util.HashMap; +import java.util.Map; + +public class Context { + + private static final ThreadLocal txThreadLocal + = new ThreadLocal(); + + public static void setTransactionID(String txID) { + txThreadLocal.set(txID); + + } + + public static String getTransactionId() { + return txThreadLocal.get(); + } + +} + diff --git a/liuxin/knowledge-point/src/main/java/threadlocal/TransactionManager.java b/liuxin/knowledge-point/src/main/java/threadlocal/TransactionManager.java new file mode 100644 index 0000000000..8a5283fcab --- /dev/null +++ b/liuxin/knowledge-point/src/main/java/threadlocal/TransactionManager.java @@ -0,0 +1,22 @@ +package threadlocal; + +public class TransactionManager { + private static final ThreadLocal context = new ThreadLocal(); + + public static void startTransaction() { + // logic to start a transaction + // ... + String txID = null; + context.set(txID); + } + + public static String getTransactionId() { + return context.get(); + } + + public static void endTransaction() { + // logic to end a transaction + // … + context.remove(); + } +} diff --git a/liuxin/knowledge-point/src/main/java/threadpool/BlockingQueue.java b/liuxin/knowledge-point/src/main/java/threadpool/BlockingQueue.java new file mode 100644 index 0000000000..faca2d2c70 --- /dev/null +++ b/liuxin/knowledge-point/src/main/java/threadpool/BlockingQueue.java @@ -0,0 +1,35 @@ +package threadpool; +import java.util.LinkedList; +import java.util.List; + +public class BlockingQueue { + + private List queue = new LinkedList(); + private int limit = 10; + + public BlockingQueue(int limit) { + this.limit = limit; + } + + public synchronized void enqueue(Object item) throws InterruptedException { + while (this.queue.size() == this.limit) { + wait(); + } + if (this.queue.size() == 0) { + notifyAll(); + } + this.queue.add(item); + } + + public synchronized Object dequeue() throws InterruptedException { + while (this.queue.size() == 0) { + wait(); + } + if (this.queue.size() == this.limit) { + notifyAll(); + } + + return this.queue.remove(0); + } + +} diff --git a/liuxin/knowledge-point/src/main/java/threadpool/Task.java b/liuxin/knowledge-point/src/main/java/threadpool/Task.java new file mode 100644 index 0000000000..07413d9798 --- /dev/null +++ b/liuxin/knowledge-point/src/main/java/threadpool/Task.java @@ -0,0 +1,5 @@ +package threadpool; + +public interface Task { + public void execute(); +} diff --git a/liuxin/knowledge-point/src/main/java/threadpool/ThreadPool.java b/liuxin/knowledge-point/src/main/java/threadpool/ThreadPool.java new file mode 100644 index 0000000000..f508f76eb5 --- /dev/null +++ b/liuxin/knowledge-point/src/main/java/threadpool/ThreadPool.java @@ -0,0 +1,37 @@ +package threadpool; +import java.util.ArrayList; +import java.util.List; + + +public class ThreadPool { + + private BlockingQueue taskQueue = null; + private List threads = new ArrayList(); + private boolean isStopped = false; + + public ThreadPool(int numOfThreads, int maxNumOfTasks){ + taskQueue = new BlockingQueue(maxNumOfTasks); + + for(int i=0; icom.coderising ood-assignment 0.0.1-SNAPSHOT - jar + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.7 + 1.7 + + + + + jar ood-assignment http://maven.apache.org diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/GraphicLibrary1.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/GraphicLibrary1.java new file mode 100644 index 0000000000..798cfbc7f9 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/GraphicLibrary1.java @@ -0,0 +1,11 @@ +package com.coderising.dp.bridge; + +public class GraphicLibrary1 { + public void draw_a_line(int x1,int y1,int x2,int y2){ + + } + public void draw_a_circle(int x,int y, int r){ + + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/GraphicLibrary2.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/GraphicLibrary2.java new file mode 100644 index 0000000000..2e67a1220b --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/GraphicLibrary2.java @@ -0,0 +1,11 @@ +package com.coderising.dp.bridge; + +public class GraphicLibrary2 { + public void drawLine(int x1,int x2,int y1,int y2){ + + } + public void drawCircle(int x,int y, int r){ + + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/builder/TagBuilder.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/builder/TagBuilder.java new file mode 100644 index 0000000000..daa431f139 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/builder/TagBuilder.java @@ -0,0 +1,37 @@ +package com.coderising.dp.builder; + +public class TagBuilder { + private TagNode rootNode; + private TagNode currentNode; + private TagNode parentNode; + public TagBuilder(String rootTagName){ + rootNode = new TagNode(rootTagName); + currentNode = rootNode; + parentNode = null; + } + + public TagBuilder addChild(String childTagName){ + parentNode = this.currentNode; + this.currentNode = new TagNode(childTagName); + parentNode.add(currentNode); + return this; + } + public TagBuilder addSibling(String siblingTagName){ + + this.currentNode = new TagNode(siblingTagName); + parentNode.add(this.currentNode); + return this; + + } + public TagBuilder setAttribute(String name, String value){ + this.currentNode.setAttribute(name, value); + return this; + } + public TagBuilder setText(String value){ + this.currentNode.setValue(value); + return this; + } + public String toXML(){ + return this.rootNode.toXML(); + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/builder/TagBuilderTest.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/builder/TagBuilderTest.java new file mode 100644 index 0000000000..e30d20285b --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/builder/TagBuilderTest.java @@ -0,0 +1,40 @@ +package com.coderising.dp.builder; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class TagBuilderTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testToXML() { + + TagBuilder builder = new TagBuilder("order"); + + String xml = builder.addChild("line-items") + .addChild("line-item").setAttribute("pid", "P3677").setAttribute("qty", "3") + .addSibling("line-item").setAttribute("pid", "P9877").setAttribute("qty", "10") + .toXML(); + + String expected = "" + + "" + + "" + + "" + + "" + + ""; + + System.out.println(xml); + assertEquals(expected, xml); + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/builder/TagNode.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/builder/TagNode.java new file mode 100644 index 0000000000..2ac26ad7b9 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/builder/TagNode.java @@ -0,0 +1,83 @@ +package com.coderising.dp.builder; + +import java.util.ArrayList; +import java.util.List; + +public class TagNode { + private String tagName; + private String tagValue; + private List children = new ArrayList<>(); + private List attributes = new ArrayList<>(); + + public TagNode(String name){ + this.tagName = name; + } + public void add(TagNode child){ + this.children.add(child); + } + public void setAttribute(String name, String value) { + Attribute attr = findAttribute(name); + if(attr != null){ + attr.value = value; + return; + } + + attributes.add(new Attribute(name,value)); + } + private Attribute findAttribute(String name){ + for(Attribute attr : attributes){ + if(attr.name.equals(name)){ + return attr; + } + } + return null; + } + public void setValue(String value) { + this.tagValue = value; + + } + public String getTagName() { + return tagName; + } + public List getChildren() { + return children; + } + + private static class Attribute{ + public Attribute(String name, String value) { + this.name = name; + this.value = value; + } + String name; + String value; + + } + public String toXML(){ + return toXML(this); + } + private String toXML(TagNode node){ + StringBuilder buffer = new StringBuilder(); + buffer.append("<").append(node.tagName); + if(node.attributes.size()> 0){ + for(int i=0;i"); + return buffer.toString(); + } + buffer.append(">"); + for(TagNode childNode : node.children){ + buffer.append(toXML(childNode)); + } + buffer.append(""); + + + return buffer.toString(); + } + private String toXML(Attribute attr){ + return attr.name+"=\""+attr.value + "\""; + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Line.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Line.java new file mode 100644 index 0000000000..b3c769e63a --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Line.java @@ -0,0 +1,11 @@ +package com.coderising.dp.composite; + +public class Line implements Shape { + + @Override + public void draw() { + + + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Rectangle.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Rectangle.java new file mode 100644 index 0000000000..2960351a35 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Rectangle.java @@ -0,0 +1,11 @@ +package com.coderising.dp.composite; + +public class Rectangle implements Shape { + + @Override + public void draw() { + // TODO Auto-generated method stub + + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Shape.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Shape.java new file mode 100644 index 0000000000..4562f10b12 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Shape.java @@ -0,0 +1,5 @@ +package com.coderising.dp.composite; + +public interface Shape { + public void draw(); +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Square.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Square.java new file mode 100644 index 0000000000..f106d65fd8 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Square.java @@ -0,0 +1,11 @@ +package com.coderising.dp.composite; + +public class Square implements Shape { + + @Override + public void draw() { + // TODO Auto-generated method stub + + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Text.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Text.java new file mode 100644 index 0000000000..3543a08be3 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Text.java @@ -0,0 +1,11 @@ +package com.coderising.dp.composite; + +public class Text implements Shape { + + @Override + public void draw() { + // TODO Auto-generated method stub + + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/Email.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/Email.java new file mode 100644 index 0000000000..064de1e837 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/Email.java @@ -0,0 +1,6 @@ +package com.coderising.dp.decorator; + +public interface Email { + public String getContent(); +} + diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/EmailDecorator.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/EmailDecorator.java new file mode 100644 index 0000000000..d5379b0dd9 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/EmailDecorator.java @@ -0,0 +1,5 @@ +package com.coderising.dp.decorator; + +public abstract class EmailDecorator implements Email{ + +} \ No newline at end of file diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/EmailImpl.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/EmailImpl.java new file mode 100644 index 0000000000..640aef6da3 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/EmailImpl.java @@ -0,0 +1,12 @@ +package com.coderising.dp.decorator; + +public class EmailImpl implements Email { + private String content; + + public EmailImpl(String content) { + this.content = content; + } + public String getContent() { + return content; + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java new file mode 100644 index 0000000000..0d0d01098f --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return null; + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java new file mode 100644 index 0000000000..aca173e665 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java @@ -0,0 +1,38 @@ +package com.coderising.ood.ocp; + +public class Logger { + + public final int RAW_LOG = 1; + public final int RAW_LOG_WITH_DATE = 2; + public final int EMAIL_LOG = 1; + public final int SMS_LOG = 2; + public final int PRINT_LOG = 3; + + int type = 0; + int method = 0; + + public Logger(int logType, int logMethod){ + this.type = logType; + this.method = logMethod; + } + public void log(String msg){ + + String logMsg = msg; + + if(this.type == RAW_LOG){ + logMsg = msg; + } else if(this.type == RAW_LOG_WITH_DATE){ + String txtDate = DateUtil.getCurrentDateAsString(); + logMsg = txtDate + ": " + msg; + } + + if(this.method == EMAIL_LOG){ + MailUtil.send(logMsg); + } else if(this.method == SMS_LOG){ + SMSUtil.send(logMsg); + } else if(this.method == PRINT_LOG){ + System.out.println(logMsg); + } + } +} + diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java new file mode 100644 index 0000000000..59d77649a2 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class MailUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java new file mode 100644 index 0000000000..fab4cd01b7 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class SMSUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Formatter.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Formatter.java new file mode 100644 index 0000000000..b6e2ccbc16 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Formatter.java @@ -0,0 +1,7 @@ +package com.coderising.ood.ocp.good; + +public interface Formatter { + + String format(String msg); + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/FormatterFactory.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/FormatterFactory.java new file mode 100644 index 0000000000..3c2009a674 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/FormatterFactory.java @@ -0,0 +1,13 @@ +package com.coderising.ood.ocp.good; + +public class FormatterFactory { + public static Formatter createFormatter(int type){ + if(type == 1){ + return new RawFormatter(); + } + if (type == 2){ + return new HtmlFormatter(); + } + return null; + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/HtmlFormatter.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/HtmlFormatter.java new file mode 100644 index 0000000000..3d375f5acc --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/HtmlFormatter.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp.good; + +public class HtmlFormatter implements Formatter { + + @Override + public String format(String msg) { + + return null; + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Logger.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Logger.java new file mode 100644 index 0000000000..f206472d0d --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Logger.java @@ -0,0 +1,18 @@ +package com.coderising.ood.ocp.good; + +public class Logger { + + private Formatter formatter; + private Sender sender; + + public Logger(Formatter formatter,Sender sender){ + this.formatter = formatter; + this.sender = sender; + } + public void log(String msg){ + sender.send(formatter.format(msg)) ; + } + + +} + diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/RawFormatter.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/RawFormatter.java new file mode 100644 index 0000000000..7f1cb4ae30 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/RawFormatter.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp.good; + +public class RawFormatter implements Formatter { + + @Override + public String format(String msg) { + + return null; + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Sender.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Sender.java new file mode 100644 index 0000000000..aaa46c1fb7 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Sender.java @@ -0,0 +1,7 @@ +package com.coderising.ood.ocp.good; + +public interface Sender { + + void send(String msg); + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good/template/MailBodyTemplate.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good/template/MailBodyTemplate.java new file mode 100644 index 0000000000..e5df642be9 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good/template/MailBodyTemplate.java @@ -0,0 +1,5 @@ +package com.coderising.ood.srp.good.template; + +public interface MailBodyTemplate { + public String render(); +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good/template/TextMailBodyTemplate.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good/template/TextMailBodyTemplate.java new file mode 100644 index 0000000000..38793717a8 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good/template/TextMailBodyTemplate.java @@ -0,0 +1,19 @@ +package com.coderising.ood.srp.good.template; + +import java.util.Map; + +public class TextMailBodyTemplate implements MailBodyTemplate { + + private MapparamMap ; + + public TextMailBodyTemplate(Map map){ + paramMap = map; + } + + @Override + public String render() { + //使用某种模板技术实现Render + return null; + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/Configuration.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/Configuration.java new file mode 100644 index 0000000000..55f0fad677 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp.good1; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/ConfigurationKeys.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/ConfigurationKeys.java new file mode 100644 index 0000000000..945db9004a --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp.good1; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/Mail.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/Mail.java new file mode 100644 index 0000000000..83099ed16a --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/Mail.java @@ -0,0 +1,29 @@ +package com.coderising.ood.srp.good1; + +import java.util.List; + +import com.coderising.ood.srp.good.template.MailBodyTemplate; + +public class Mail { + + private User user; + + public Mail(User u){ + this.user = u; + } + public String getAddress(){ + return user.getEMailAddress(); + } + public String getSubject(){ + return "您关注的产品降价了"; + } + public String getBody(){ + + return "尊敬的 "+user.getName()+", 您关注的产品 " + this.buildProductDescList() + " 降价了,欢迎购买!" ; + } + private String buildProductDescList() { + List products = user.getSubscribedProducts(); + //.... 实现略... + return null; + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/MailSender.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/MailSender.java new file mode 100644 index 0000000000..ffd0543e22 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/MailSender.java @@ -0,0 +1,36 @@ +package com.coderising.ood.srp.good1; + + +public class MailSender { + + private String fromAddress ; + private String smtpHost; + private String altSmtpHost; + + public MailSender(Configuration config){ + this.fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + this.smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + this.altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + } + + public void sendMail(Mail mail){ + try{ + sendEmail(mail,this.smtpHost); + }catch(Exception e){ + try{ + sendEmail(mail,this.altSmtpHost); + }catch (Exception ex){ + System.out.println("通过备用 SMTP服务器发送邮件失败: " + ex.getMessage()); + } + + } + } + + private void sendEmail(Mail mail, String smtpHost){ + + String toAddress = mail.getAddress(); + String subject = mail.getSubject(); + String msg = mail.getBody(); + //发送邮件 + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/Product.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/Product.java new file mode 100644 index 0000000000..55617461cd --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/Product.java @@ -0,0 +1,14 @@ +package com.coderising.ood.srp.good1; + + + +public class Product { + + private String id; + private String desc; + public String getDescription(){ + return desc; + } + + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/ProductService.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/ProductService.java new file mode 100644 index 0000000000..4109bfa9dc --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/ProductService.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp.good1; + + +public class ProductService { + public Product getPromotionProduct(){ + //从文本文件中读取文件列表 + return null; + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/PromotionJob.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/PromotionJob.java new file mode 100644 index 0000000000..8e41069bd9 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/PromotionJob.java @@ -0,0 +1,24 @@ +package com.coderising.ood.srp.good1; + +import java.util.List; + +public class PromotionJob { + + private ProductService productService = null ; //获取production service + private UserService userService = null ;// 获取UserService + + public void run(){ + + Configuration cfg = new Configuration(); + + Product p = productService.getPromotionProduct(); + + List users = userService.getUsers(p); + + MailSender mailSender = new MailSender(cfg); + + for(User user : users){ + mailSender.sendMail(new Mail(user)); + } + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/User.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/User.java new file mode 100644 index 0000000000..114476bb64 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/User.java @@ -0,0 +1,24 @@ +package com.coderising.ood.srp.good1; + +import java.util.List; + + + +public class User { + + private String name; + private String emailAddress; + + private List subscribedProducts; + + public String getName(){ + return name; + } + public String getEMailAddress() { + return emailAddress; + } + public List getSubscribedProducts(){ + return this.subscribedProducts; + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/UserService.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/UserService.java new file mode 100644 index 0000000000..1e08138cff --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good1/UserService.java @@ -0,0 +1,11 @@ +package com.coderising.ood.srp.good1; + +import java.util.List; + +public class UserService { + + public List getUsers(Product product){ + //调用DAO相关的类从数据库中读取订阅产品的用户列表 + return null; + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good2/ProductService.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good2/ProductService.java new file mode 100644 index 0000000000..5ca5636291 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good2/ProductService.java @@ -0,0 +1,12 @@ +package com.coderising.ood.srp.good2; + +import java.util.List; + +import com.coderising.ood.srp.good1.Product; + +public class ProductService { + public List getPromotionProducts(){ + //从文本文件中读取文件列表 + return null; + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good2/UserService.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good2/UserService.java new file mode 100644 index 0000000000..f86307e701 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/good2/UserService.java @@ -0,0 +1,13 @@ +package com.coderising.ood.srp.good2; + +import java.util.List; + +import com.coderising.ood.srp.good1.Product; +import com.coderising.ood.srp.good1.User; + +public class UserService { + public List getUsers(List products){ + //调用DAO相关的类从数据库中读取订阅产品的用户列表 + return null; + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt index 0c0124cc61..618f02b102 100644 --- a/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -1,3 +1,8 @@ + + + + + P8756 iPhone8 P3946 XiaoMi10 P8904 Oppo_R15 diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/PayrollService.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/PayrollService.java new file mode 100644 index 0000000000..b0b4fec82f --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/PayrollService.java @@ -0,0 +1,49 @@ +package com.coderising.payroll; + +import java.util.List; + +import com.coderising.payroll.classification.CommissionedClassification; +import com.coderising.payroll.classification.HourlyClassification; +import com.coderising.payroll.classification.SalariedClassification; +import com.coderising.payroll.domain.Employee; +import com.coderising.payroll.domain.HoldMethod; +import com.coderising.payroll.domain.Paycheck; +import com.coderising.payroll.schedule.BiweeklySchedule; +import com.coderising.payroll.schedule.MonthlySchedule; +import com.coderising.payroll.schedule.WeeklySchedule; + +public class PayrollService { + public List getAllEmployees(){ + return null; + } + public void savePaycheck(Paycheck pc){ + + } + + public Employee addHourlyEmployee(String name, String address, double hourlyRate){ + Employee e = new Employee(name, address); + e.setClassification(new HourlyClassification(hourlyRate)); + e.setSchedule(new WeeklySchedule()); + e.setPaymentMethod(new HoldMethod()); + //保存员工到数据库.. 略 + return e; + } + + public Employee addSalariedEmployee(String name, String address, double salary){ + Employee e = new Employee(name, address); + e.setClassification(new SalariedClassification(salary)); + e.setSchedule(new MonthlySchedule()); + e.setPaymentMethod(new HoldMethod()); + //保存员工到数据库.. 略 + return e; + } + + public Employee addCommissionedEmployee(String name, String address, double salary, double saleRate){ + Employee e = new Employee(name, address); + e.setClassification(new CommissionedClassification(salary, saleRate)); + e.setSchedule(new BiweeklySchedule()); + e.setPaymentMethod(new HoldMethod()); + //保存员工到数据库.. 略 + return e; + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/affiliation/NonAffiliation.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/affiliation/NonAffiliation.java new file mode 100644 index 0000000000..3cb6228aa4 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/affiliation/NonAffiliation.java @@ -0,0 +1,10 @@ +package com.coderising.payroll.affiliation; + +import com.coderising.payroll.domain.Affiliation; +import com.coderising.payroll.domain.Paycheck; + +public class NonAffiliation implements Affiliation{ + public double calculateDeductions(Paycheck pc){ + return 0.0; + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/affiliation/UnionAffiliation.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/affiliation/UnionAffiliation.java new file mode 100644 index 0000000000..bbce4fa317 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/affiliation/UnionAffiliation.java @@ -0,0 +1,14 @@ +package com.coderising.payroll.affiliation; + +import com.coderising.payroll.domain.Affiliation; +import com.coderising.payroll.domain.Paycheck; + +public class UnionAffiliation implements Affiliation { + + @Override + public double calculateDeductions(Paycheck pc) { + + return 0; + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/classification/CommissionedClassification.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/classification/CommissionedClassification.java new file mode 100644 index 0000000000..f6a7ab4a63 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/classification/CommissionedClassification.java @@ -0,0 +1,31 @@ +package com.coderising.payroll.classification; + +import java.util.Date; +import java.util.Map; + +import com.coderising.payroll.domain.Paycheck; +import com.coderising.payroll.domain.PaymentClassification; +import com.coderising.payroll.domain.SalesReceipt; +import com.coderising.payroll.util.DateUtil; + +public class CommissionedClassification implements PaymentClassification { + double salary; + double rate; + public CommissionedClassification(double salary , double rate){ + this.salary = salary; + this.rate = rate; + } + Map receipts; + @Override + public double calculatePay(Paycheck pc) { + double commission = 0.0; + for(SalesReceipt sr : receipts.values()){ + if(DateUtil.between(sr.getSaleDate(), pc.getPayPeriodStartDate(), + pc.getPayPeriodEndDate())){ + commission += sr.getAmount() * rate; + } + } + return salary + commission; + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/classification/HourlyClassification.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/classification/HourlyClassification.java new file mode 100644 index 0000000000..1238ac84a6 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/classification/HourlyClassification.java @@ -0,0 +1,43 @@ +package com.coderising.payroll.classification; + +import java.util.Date; +import java.util.Map; + +import com.coderising.payroll.domain.Paycheck; +import com.coderising.payroll.domain.PaymentClassification; +import com.coderising.payroll.domain.TimeCard; +import com.coderising.payroll.util.DateUtil; + +public class HourlyClassification implements PaymentClassification { + private double rate; + private Map timeCards; + + public HourlyClassification(double hourlyRate) { + this.rate = hourlyRate; + } + public void addTimeCard(TimeCard tc){ + timeCards.put(tc.getDate(), tc); + } + @Override + public double calculatePay(Paycheck pc) { + double totalPay = 0; + for(TimeCard tc : timeCards.values()){ + if(DateUtil.between(tc.getDate(), pc.getPayPeriodStartDate(), + pc.getPayPeriodEndDate())){ + totalPay += calculatePayForTimeCard(tc); + } + } + return totalPay; + + } + private double calculatePayForTimeCard(TimeCard tc) { + int hours = tc.getHours(); + + if(hours > 8){ + return 8*rate + (hours-8) * rate * 1.5; + } else{ + return 8*rate; + } + } +} + diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/classification/SalariedClassification.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/classification/SalariedClassification.java new file mode 100644 index 0000000000..796aae93f1 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/classification/SalariedClassification.java @@ -0,0 +1,16 @@ +package com.coderising.payroll.classification; + +import com.coderising.payroll.domain.Paycheck; +import com.coderising.payroll.domain.PaymentClassification; + +public class SalariedClassification implements PaymentClassification { + private double salary; + public SalariedClassification(double salary){ + this.salary = salary; + } + @Override + public double calculatePay(Paycheck pc) { + return salary; + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/Affiliation.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/Affiliation.java new file mode 100644 index 0000000000..74a6b404bc --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/Affiliation.java @@ -0,0 +1,5 @@ +package com.coderising.payroll.domain; + +public interface Affiliation { + public double calculateDeductions(Paycheck pc); +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/Employee.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/Employee.java new file mode 100644 index 0000000000..204180a672 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/Employee.java @@ -0,0 +1,48 @@ +package com.coderising.payroll.domain; + +import java.util.Date; + +public class Employee { + private String id; + private String name; + private String address; + private Affiliation affiliation; + + + private PaymentClassification classification; + private PaymentSchedule schedule; + private PaymentMethod paymentMethod; + + public Employee(String name, String address){ + this.name = name; + this.address = address; + } + public boolean isPayDay(Date d) { + return this.schedule.isPayDate(d); + } + + public Date getPayPeriodStartDate(Date d) { + return this.schedule.getPayPeriodStartDate(d); + } + + public void payDay(Paycheck pc){ + double grossPay = classification.calculatePay(pc); + double deductions = affiliation.calculateDeductions(pc); + double netPay = grossPay - deductions; + pc.setGrossPay(grossPay); + pc.setDeductions(deductions); + pc.setNetPay(netPay); + paymentMethod.pay(pc); + } + + public void setClassification(PaymentClassification classification) { + this.classification = classification; + } + public void setSchedule(PaymentSchedule schedule) { + this.schedule = schedule; + } + public void setPaymentMethod(PaymentMethod paymentMethod) { + this.paymentMethod = paymentMethod; + } +} + diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/HoldMethod.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/HoldMethod.java new file mode 100644 index 0000000000..0ce19e2291 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/HoldMethod.java @@ -0,0 +1,11 @@ +package com.coderising.payroll.domain; + +public class HoldMethod implements PaymentMethod { + + @Override + public void pay(Paycheck pc) { + + + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/Paycheck.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/Paycheck.java new file mode 100644 index 0000000000..6f1ff99413 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/Paycheck.java @@ -0,0 +1,35 @@ +package com.coderising.payroll.domain; + +import java.util.Date; +import java.util.Map; + +public class Paycheck { + private Date payPeriodStart; + private Date payPeriodEnd; + private double grossPay; + private double netPay; + private double deductions; + private Map itsFields; + public Paycheck(Date payPeriodStart, Date payPeriodEnd){ + this.payPeriodStart = payPeriodStart; + this.payPeriodEnd = payPeriodEnd; + } + public void setGrossPay(double grossPay) { + this.grossPay = grossPay; + + } + public void setDeductions(double deductions) { + this.deductions = deductions; + } + public void setNetPay(double netPay){ + this.netPay = netPay; + } + public Date getPayPeriodEndDate() { + + return this.payPeriodEnd; + } + public Date getPayPeriodStartDate() { + + return this.payPeriodStart; + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/PaydayTransaction.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/PaydayTransaction.java new file mode 100644 index 0000000000..e066e46263 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/PaydayTransaction.java @@ -0,0 +1,23 @@ +package com.coderising.payroll.domain; + +import java.util.Date; +import java.util.List; + +import com.coderising.payroll.PayrollService; + +public class PaydayTransaction { + private Date date; + private PayrollService payrollService; + + public void execute(){ + List employees = payrollService.getAllEmployees(); + for(Employee e : employees){ + if(e.isPayDay(date)){ + Paycheck pc = new Paycheck(e.getPayPeriodStartDate(date),date); + e.payDay(pc); + payrollService.savePaycheck(pc); + } + } + } +} + diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/PaymentClassification.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/PaymentClassification.java new file mode 100644 index 0000000000..b6f2120bdb --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/PaymentClassification.java @@ -0,0 +1,5 @@ +package com.coderising.payroll.domain; + +public interface PaymentClassification { + public double calculatePay(Paycheck pc); +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/PaymentMethod.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/PaymentMethod.java new file mode 100644 index 0000000000..f07cc5354b --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/PaymentMethod.java @@ -0,0 +1,5 @@ +package com.coderising.payroll.domain; + +public interface PaymentMethod { + public void pay(Paycheck pc); +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/PaymentSchedule.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/PaymentSchedule.java new file mode 100644 index 0000000000..96788f4f80 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/PaymentSchedule.java @@ -0,0 +1,8 @@ +package com.coderising.payroll.domain; + +import java.util.Date; + +public interface PaymentSchedule { + public boolean isPayDate(Date date); + public Date getPayPeriodStartDate( Date payPeriodEndDate); +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/SalesReceipt.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/SalesReceipt.java new file mode 100644 index 0000000000..a7b0ba41ad --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/SalesReceipt.java @@ -0,0 +1,14 @@ +package com.coderising.payroll.domain; + +import java.util.Date; + +public class SalesReceipt { + private Date saleDate; + private double amount; + public Date getSaleDate() { + return saleDate; + } + public double getAmount() { + return amount; + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/TimeCard.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/TimeCard.java new file mode 100644 index 0000000000..ebf6e17a4c --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/domain/TimeCard.java @@ -0,0 +1,15 @@ +package com.coderising.payroll.domain; + +import java.util.Date; + +public class TimeCard { + private Date date; + private int hours; + + public Date getDate() { + return date; + } + public int getHours() { + return hours; + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/schedule/BiweeklySchedule.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/schedule/BiweeklySchedule.java new file mode 100644 index 0000000000..35ec65c49c --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/schedule/BiweeklySchedule.java @@ -0,0 +1,38 @@ +package com.coderising.payroll.schedule; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import com.coderising.payroll.domain.PaymentSchedule; +import com.coderising.payroll.util.DateUtil; + +public class BiweeklySchedule implements PaymentSchedule { + Date firstPayableFriday = DateUtil.parseDate("2017-6-2"); + + @Override + public boolean isPayDate(Date date) { + + long interval = DateUtil.getDaysBetween(firstPayableFriday, date); + return interval % 14 == 0; + } + + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.add(payPeriodEndDate, -13); + + } + + public static void main(String [] args) throws Exception{ + BiweeklySchedule schedule = new BiweeklySchedule(); + + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); + Date d = sdf.parse("2017-06-30"); + + System.out.println(schedule.isPayDate(d)); + + System.out.println(DateUtil.isFriday(d)); + + System.out.println(schedule.getPayPeriodStartDate(d)); + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/schedule/MonthlySchedule.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/schedule/MonthlySchedule.java new file mode 100644 index 0000000000..dbbe732d2f --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/schedule/MonthlySchedule.java @@ -0,0 +1,20 @@ +package com.coderising.payroll.schedule; + +import java.util.Date; + +import com.coderising.payroll.domain.PaymentSchedule; +import com.coderising.payroll.util.DateUtil; + +public class MonthlySchedule implements PaymentSchedule { + + @Override + public boolean isPayDate(Date date) { + return DateUtil.isLastDayOfMonth(date); + } + + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.getFirstDay(payPeriodEndDate); + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/schedule/WeeklySchedule.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/schedule/WeeklySchedule.java new file mode 100644 index 0000000000..54a22ab7db --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/schedule/WeeklySchedule.java @@ -0,0 +1,19 @@ +package com.coderising.payroll.schedule; + +import java.util.Date; + +import com.coderising.payroll.domain.PaymentSchedule; +import com.coderising.payroll.util.DateUtil; + +public class WeeklySchedule implements PaymentSchedule { + + @Override + public boolean isPayDate(Date date) { + return DateUtil.isFriday(date); + } + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.add(payPeriodEndDate, -6); + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/transaction/AddEmployeeTransaction.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/transaction/AddEmployeeTransaction.java new file mode 100644 index 0000000000..39b268486b --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/transaction/AddEmployeeTransaction.java @@ -0,0 +1,29 @@ +package com.coderising.payroll.transaction; + +import com.coderising.payroll.domain.Employee; +import com.coderising.payroll.domain.HoldMethod; +import com.coderising.payroll.domain.PaymentClassification; +import com.coderising.payroll.domain.PaymentMethod; +import com.coderising.payroll.domain.PaymentSchedule; + +public abstract class AddEmployeeTransaction { + private String name; + private String address; + public AddEmployeeTransaction(String name,String address){ + this.name = name; + this.address = address; + } + public abstract PaymentClassification getClassification(); + public abstract PaymentSchedule getSchedule(); + + public void execute(){ + PaymentClassification pc = getClassification(); + PaymentSchedule ps = getSchedule(); + PaymentMethod pm = new HoldMethod(); + Employee e = new Employee(name, address); + e.setClassification(pc); + e.setSchedule(ps); + e.setPaymentMethod(pm); + //保存到数据库, 略 + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/transaction/AddHourlyEmployeeTransaction.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/transaction/AddHourlyEmployeeTransaction.java new file mode 100644 index 0000000000..2039734479 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/transaction/AddHourlyEmployeeTransaction.java @@ -0,0 +1,25 @@ +package com.coderising.payroll.transaction; + +import com.coderising.payroll.classification.HourlyClassification; +import com.coderising.payroll.domain.PaymentClassification; +import com.coderising.payroll.domain.PaymentSchedule; +import com.coderising.payroll.schedule.WeeklySchedule; + +public class AddHourlyEmployeeTransaction extends AddEmployeeTransaction{ + private double rate; + AddHourlyEmployeeTransaction(String name, String address, double hourlyRate) { + super(name, address); + this.rate = hourlyRate; + } + @Override + public PaymentClassification getClassification() { + return new HourlyClassification(rate); + } + + @Override + public PaymentSchedule getSchedule() { + + return new WeeklySchedule(); + } +} + diff --git a/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/util/DateUtil.java b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/util/DateUtil.java new file mode 100644 index 0000000000..ffc26f31a1 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/com/coderising/payroll/util/DateUtil.java @@ -0,0 +1,56 @@ +package com.coderising.payroll.util; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +public class DateUtil { + public static long getDaysBetween(Date d1, Date d2){ + + return (d2.getTime() - d1.getTime())/(24*60*60*1000); + } + + public static Date parseDate(String txtDate){ + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); + try { + return sdf.parse(txtDate); + } catch (ParseException e) { + e.printStackTrace(); + return null; + } + } + public static boolean isFriday(Date d){ + Calendar calendar = Calendar.getInstance(); + return calendar.get(Calendar.DAY_OF_WEEK) == 5; + } + + public static Date add(Date d, int days){ + Calendar calendar = Calendar.getInstance(); + calendar.setTime(d); + calendar.add(Calendar.DATE, days); + return calendar.getTime(); + } + + public static boolean isLastDayOfMonth(Date d){ + Calendar calendar=Calendar.getInstance(); + calendar.setTime(d); + return calendar.get(Calendar.DATE)==calendar.getActualMaximum(Calendar.DAY_OF_MONTH); + } + public static Date getFirstDay(Date d){ + Calendar calendar=Calendar.getInstance(); + calendar.setTime(d); + int day = calendar.get(Calendar.DATE); + calendar.add(Calendar.DATE, -(day-1)); + return calendar.getTime(); + } + public static void main(String [] args) throws Exception{ + System.out.println(DateUtil.isLastDayOfMonth(DateUtil.parseDate("2017-6-29"))); + + System.out.println(DateUtil.getFirstDay(DateUtil.parseDate("2017-6-30"))); + } + + public static boolean between(Date d, Date date1, Date date2){ + return d.after(date1) && d.before(date2); + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/extension/RepeatedTest.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/extension/RepeatedTest.java new file mode 100644 index 0000000000..f6250ee426 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/extension/RepeatedTest.java @@ -0,0 +1,32 @@ +package org.litejunit.extension; + +import org.litejunit.v2.Test; +import org.litejunit.v2.TestResult; + +/** + * A Decorator that runs a test repeatedly. + * + */ +public class RepeatedTest extends TestDecorator { + private int fTimesRepeat; + + public RepeatedTest(Test test, int repeat) { + super(test); + if (repeat < 0) + throw new IllegalArgumentException("Repetition count must be > 0"); + fTimesRepeat= repeat; + } + public int countTestCases() { + return super.countTestCases()*fTimesRepeat; + } + public void run(TestResult result) { + for (int i= 0; i < fTimesRepeat; i++) { + if (result.shouldStop()) + break; + super.run(result); + } + } + public String toString() { + return super.toString()+"(repeated)"; + } +} \ No newline at end of file diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/extension/TestDecorator.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/extension/TestDecorator.java new file mode 100644 index 0000000000..556d05cbbb --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/extension/TestDecorator.java @@ -0,0 +1,40 @@ +package org.litejunit.extension; + +import org.litejunit.v2.Assert; +import org.litejunit.v2.Test; +import org.litejunit.v2.TestResult; + +/** + * A Decorator for Tests. Use TestDecorator as the base class + * for defining new test decorators. Test decorator subclasses + * can be introduced to add behaviour before or after a test + * is run. + * + */ +public class TestDecorator extends Assert implements Test { + protected Test test; + + public TestDecorator(Test test) { + this.test= test; + } + /** + * The basic run behaviour. + */ + public void basicRun(TestResult result) { + test.run(result); + } + public int countTestCases() { + return test.countTestCases(); + } + public void run(TestResult result) { + basicRun(result); + } + + public String toString() { + return test.toString(); + } + + public Test getTest() { + return test; + } +} \ No newline at end of file diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/extension/TestSetup.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/extension/TestSetup.java new file mode 100644 index 0000000000..7a133a798c --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/extension/TestSetup.java @@ -0,0 +1,39 @@ +package org.litejunit.extension; + +import org.litejunit.v2.Protectable; +import org.litejunit.v2.Test; +import org.litejunit.v2.TestResult; + +/** + * A Decorator to set up and tear down additional fixture state. + * Subclass TestSetup and insert it into your tests when you want + * to set up additional state once before the tests are run. + */ +public class TestSetup extends TestDecorator { + + public TestSetup(Test test) { + super(test); + } + public void run(final TestResult result) { + Protectable p= new Protectable() { + public void protect() throws Exception { + setUp(); + basicRun(result); + tearDown(); + } + }; + result.runProtected(this, p); + } + /** + * Sets up the fixture. Override to set up additional fixture + * state. + */ + protected void setUp() throws Exception { + } + /** + * Tears down the fixture. Override to tear down the additional + * fixture state. + */ + protected void tearDown() throws Exception { + } +} \ No newline at end of file diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/sample/AllTest.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/sample/AllTest.java new file mode 100644 index 0000000000..2c4d6b3dca --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/sample/AllTest.java @@ -0,0 +1,43 @@ +package org.litejunit.sample; + +import org.litejunit.extension.RepeatedTest; +import org.litejunit.extension.TestSetup; +import org.litejunit.sample.calculator.CalculatorSuite; +import org.litejunit.v2.Test; +import org.litejunit.v2.TestSuite; + + +public class AllTest { + /*public static Test suite(){ + + TestSuite suite= new TestSuite("All Test"); + suite.addTest(CalculatorSuite.suite()); + suite.addTestSuite(PersonTest.class); + return suite; + + }*/ + + public static Test suite(){ + + TestSuite suite= new TestSuite("All Test"); + suite.addTest(CalculatorSuite.suite()); + suite.addTest(new RepeatedTest(new TestSuite(PersonTest.class), 2)); + return new OverallTestSetup(suite); + } + + + static class OverallTestSetup extends TestSetup{ + + public OverallTestSetup(Test test) { + super(test); + + } + protected void setUp() throws Exception { + System.out.println("this is overall testsetup"); + } + protected void tearDown() throws Exception { + System.out.println("this is overall teardown"); + } + + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/sample/PersonTest.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/sample/PersonTest.java new file mode 100644 index 0000000000..2e76ea26ae --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/sample/PersonTest.java @@ -0,0 +1,38 @@ +package org.litejunit.sample; + +import org.litejunit.v2.TestCase; + +public class PersonTest extends TestCase { + + Person p = null; + protected void setUp() { + p = new Person("andy",30); + } + public PersonTest(String name) { + super(name); + } + public void testAge(){ + this.assertEquals(30, p.getAge()); + } + public void testName(){ + this.assertEquals("andy", p.getName()); + } +} +class Person{ + private String name; + private int age; + + public Person(String name, int age) { + + this.name = name; + this.age = age; + } + public String getName() { + return name; + } + public int getAge() { + return age; + } + + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/sample/calculator/Calculator.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/sample/calculator/Calculator.java new file mode 100644 index 0000000000..ed0a69959a --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/sample/calculator/Calculator.java @@ -0,0 +1,22 @@ +package org.litejunit.sample.calculator; + +public class Calculator { + + private int result = 0; + public void add(int x){ + result += x; + } + public void subtract(int x){ + result -=x; + } + + public int getResult(){ + return this.result; + } + public static void main(String[] args){ + Calculator calculator = new Calculator(); + calculator.add(10); + calculator.subtract(5); + System.out.println(calculator.getResult()); + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/sample/calculator/CalculatorSuite.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/sample/calculator/CalculatorSuite.java new file mode 100644 index 0000000000..1deec69c52 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/sample/calculator/CalculatorSuite.java @@ -0,0 +1,12 @@ +package org.litejunit.sample.calculator; + +import org.litejunit.v2.Test; +import org.litejunit.v2.TestSuite; + +public class CalculatorSuite { + public static Test suite(){ + TestSuite suite= new TestSuite("Calculator All Test"); + suite.addTestSuite(CalculatorTest.class); + return suite; + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/sample/calculator/CalculatorTest.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/sample/calculator/CalculatorTest.java new file mode 100644 index 0000000000..39f1d2433b --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/sample/calculator/CalculatorTest.java @@ -0,0 +1,59 @@ +package org.litejunit.sample.calculator; + +import org.litejunit.v2.TestCase; + +public class CalculatorTest extends TestCase { + public CalculatorTest(String name) { + super(name); + + } + Calculator calculator =null; + public void setUp(){ + calculator = new Calculator(); + } + public void tearDown(){ + calculator = null; + } + public void testAdd(){ + + calculator.add(10); + assertEquals(5,calculator.getResult()); + } + public void testSubtract(){ + calculator.add(10); + calculator.subtract(5); + throw new RuntimeException("this is a test"); + //assertEquals(5,calculator.getResult()); + } + + public static void main(String[] args){ + /*{ + TestCase tc1 = new CalculatorTest("testAdd"){ + protected void runTest() { + testAdd(); + } + }; + + TestCase tc2 = new CalculatorTest("testSubtract"){ + protected void runTest() { + testSubtract(); + } + }; + tc1.run(); + tc2.run(); + } + + + TestSuite ts = new TestSuite(); + ts.addTest(new CalculatorTest("testAdd")); + ts.addTest(new CalculatorTest("testSubtract")); + + + { + TestCase tc1 = new CalculatorTest("test1"); + TestCase tc2 = new CalculatorTest("test2"); + tc1.run(); + tc2.run(); + }*/ + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/Assert.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/Assert.java new file mode 100644 index 0000000000..07a3c1a22b --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/Assert.java @@ -0,0 +1,225 @@ +package org.litejunit.v1; + +/** + * A set of assert methods. + */ + +public class Assert { + /** + * Protect constructor since it is a static only class + */ + protected Assert() { + } + + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError with the given message. + */ + static public void assertTrue(String message, boolean condition) { + if (!condition) + fail(message); + } + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError. + */ + static public void assertTrue(boolean condition) { + assertTrue(null, condition); + } + /** + * Fails a test with the given message. + */ + static public void fail(String message) { + throw new AssertionFailedError(message); + } + /** + * Fails a test with no message. + */ + static public void fail() { + fail(null); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(String message, Object expected, Object actual) { + if (expected == null && actual == null) + return; + if (expected != null && expected.equals(actual)) + return; + failNotEquals(message, expected, actual); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(Object expected, Object actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, double expected, double actual, double delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Double.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Double(expected), new Double(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) // Because comparison with NaN always returns false + failNotEquals(message, new Double(expected), new Double(actual)); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(double expected, double actual, double delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, float expected, float actual, float delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Float.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Float(expected), new Float(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) + failNotEquals(message, new Float(expected), new Float(actual)); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(float expected, float actual, float delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(String message, long expected, long actual) { + assertEquals(message, new Long(expected), new Long(actual)); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(long expected, long actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(String message, boolean expected, boolean actual) { + assertEquals(message, new Boolean(expected), new Boolean(actual)); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(boolean expected, boolean actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(String message, byte expected, byte actual) { + assertEquals(message, new Byte(expected), new Byte(actual)); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(byte expected, byte actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(String message, char expected, char actual) { + assertEquals(message, new Character(expected), new Character(actual)); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(char expected, char actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(String message, short expected, short actual) { + assertEquals(message, new Short(expected), new Short(actual)); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(short expected, short actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(String message, int expected, int actual) { + assertEquals(message, new Integer(expected), new Integer(actual)); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(int expected, int actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(Object object) { + assertNotNull(null, object); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(String message, Object object) { + assertTrue(message, object != null); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(Object object) { + assertNull(null, object); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(String message, Object object) { + assertTrue(message, object == null); + } + /** + * Asserts that two objects refer to the same object. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertSame(String message, Object expected, Object actual) { + if (expected == actual) + return; + failNotSame(message, expected, actual); + } + /** + * Asserts that two objects refer to the same object. If they are not + * the same an AssertionFailedError is thrown. + */ + static public void assertSame(Object expected, Object actual) { + assertSame(null, expected, actual); + } + + static private void failNotEquals(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected:<"+expected+"> but was:<"+actual+">"); + } + + static private void failNotSame(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected same"); + } +} \ No newline at end of file diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/AssertionFailedError.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/AssertionFailedError.java new file mode 100644 index 0000000000..05e786ea47 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/AssertionFailedError.java @@ -0,0 +1,13 @@ +package org.litejunit.v1; + +/** + * Thrown when an assertion failed. + */ +public class AssertionFailedError extends Error { + + public AssertionFailedError () { + } + public AssertionFailedError (String message) { + super (message); + } +} \ No newline at end of file diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/Calculator.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/Calculator.java new file mode 100644 index 0000000000..f1245ff3a6 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/Calculator.java @@ -0,0 +1,22 @@ +package org.litejunit.v1; + +public class Calculator { + + private int result = 0; + public void add(int x){ + result += x; + } + public void subtract(int x){ + result -=x; + } + + public int getResult(){ + return this.result; + } + public static void main(String[] args){ + Calculator calculator = new Calculator(); + calculator.add(10); + calculator.subtract(5); + System.out.println(calculator.getResult()); + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/CalculatorTest.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/CalculatorTest.java new file mode 100644 index 0000000000..3460528043 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/CalculatorTest.java @@ -0,0 +1,65 @@ +package org.litejunit.v1; + + +public class CalculatorTest extends TestCase { + public CalculatorTest(String name) { + super(name); + + } + Calculator calculator =null; + public void setUp(){ + calculator = new Calculator(); + } + public void tearDown(){ + calculator = null; + } + public void testAdd(){ + + calculator.add(10); + assertEquals(10,calculator.getResult()); + } + public void testSubtract(){ + calculator.add(10); + calculator.subtract(5); + assertEquals(4,calculator.getResult()); + } + + public static void main(String[] args){ + TestSuite ts = new TestSuite(CalculatorTest.class); + TestResult tr = new TestResult(); + ts.run(tr); + System.out.println(tr.wasSuccessful()); + for(TestFailure failure : tr.failures){ + System.err.println(failure); + } + + /*{ + TestCase tc1 = new CalculatorTest("testAdd"){ + protected void runTest() { + testAdd(); + } + }; + + TestCase tc2 = new CalculatorTest("testSubtract"){ + protected void runTest() { + testSubtract(); + } + }; + tc1.run(); + tc2.run(); + } + + + TestSuite ts = new TestSuite(); + ts.addTest(new CalculatorTest("testAdd")); + ts.addTest(new CalculatorTest("testSubtract")); + + + { + TestCase tc1 = new CalculatorTest("test1"); + TestCase tc2 = new CalculatorTest("test2"); + tc1.run(); + tc2.run(); + }*/ + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/Test.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/Test.java new file mode 100644 index 0000000000..3d870cf637 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/Test.java @@ -0,0 +1,6 @@ +package org.litejunit.v1; + +public interface Test { + public abstract int countTestCases(); + public void run(TestResult tr); +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/TestCase.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/TestCase.java new file mode 100644 index 0000000000..d9cebd263b --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/TestCase.java @@ -0,0 +1,63 @@ +package org.litejunit.v1; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + + + +public abstract class TestCase extends Assert implements Test { + private String name; + + + public TestCase(String name) { + this.name = name; + } + + public int countTestCases() { + return 1; + } + + protected void runTest() throws Throwable{ + Method runMethod= null; + try { + runMethod= getClass().getMethod(name, null); + } catch (NoSuchMethodException e) { + fail("Method \""+name+"\" not found"); + } + if (!Modifier.isPublic(runMethod.getModifiers())) { + fail("Method \""+name+"\" should be public"); + } + + try { + runMethod.invoke(this, new Class[0]); + } + catch (InvocationTargetException e) { + e.fillInStackTrace(); + throw e.getTargetException(); + } + catch (IllegalAccessException e) { + e.fillInStackTrace(); + throw e; + } + } + + protected void setUp() { + } + + protected void tearDown() { + } + + public void run(TestResult tr) { + tr.run(this); + } + public void doRun() throws Throwable{ + setUp(); + try{ + runTest(); + } + finally{ + tearDown(); + } + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/TestFailure.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/TestFailure.java new file mode 100644 index 0000000000..1ac44256a4 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/TestFailure.java @@ -0,0 +1,39 @@ +package org.litejunit.v1; + +/** + * A TestFailure collects a failed test together with + * the caught exception. + * @see TestResult + */ +public class TestFailure { + protected Test failedTest; + protected Throwable thrownException; + + /** + * Constructs a TestFailure with the given test and exception. + */ + public TestFailure(Test failedTest, Throwable thrownException) { + this.failedTest= failedTest; + this.thrownException= thrownException; + } + /** + * Gets the failed test. + */ + public Test failedTest() { + return failedTest; + } + /** + * Gets the thrown exception. + */ + public Throwable thrownException() { + return thrownException; + } + /** + * Returns a short description of the failure. + */ + public String toString() { + StringBuffer buffer= new StringBuffer(); + buffer.append(failedTest+": "+thrownException.getMessage()); + return buffer.toString(); + } +} \ No newline at end of file diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/TestResult.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/TestResult.java new file mode 100644 index 0000000000..a9e8c2b439 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/TestResult.java @@ -0,0 +1,95 @@ +package org.litejunit.v1; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Vector; + + + + +public class TestResult extends Object { + protected List failures; + protected List errors; + + protected int testCount; + private boolean stop; + + public TestResult() { + failures= new ArrayList<>(); + errors= new ArrayList<>(); + + testCount= 0; + stop= false; + } + + public void addError(Test test, Throwable t) { + errors.add(new TestFailure(test, t)); + } + + public void addFailure(Test test, AssertionFailedError t) { + failures.add(new TestFailure(test, t)); + } + + public void startTest(Test test) { + int count= test.countTestCases(); + testCount+= count; + } + public void endTest(Test test) { + } + + /** + * Runs a TestCase. + */ + protected void run(final TestCase test) { + startTest(test); + try { + test.doRun(); + } + catch (AssertionFailedError e) { + addFailure(test, e); + } + catch (Throwable e) { + addError(test, e); + } + + endTest(test); + } + /** + * Gets the number of run tests. + */ + public int runCount() { + return testCount; + } + + + public boolean shouldStop() { + return stop; + } + + public void stop() { + stop= true; + } + + public int errorCount() { + return errors.size(); + } + + public Iterator errors() { + return errors.iterator(); + } + + public int failureCount() { + return failures.size(); + } + + public Iterator failures() { + return failures.iterator(); + } + /** + * Returns whether the entire test was successful or not. + */ + public boolean wasSuccessful() { + return this.failureCount() == 0 && this.errorCount() == 0; + } +} \ No newline at end of file diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/TestSuite.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/TestSuite.java new file mode 100644 index 0000000000..ad0af20ffd --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v1/TestSuite.java @@ -0,0 +1,130 @@ +package org.litejunit.v1; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; + +import java.util.Iterator; +import java.util.List; +import java.util.Vector; + + + + +public class TestSuite extends Assert implements Test { + private List tests= new ArrayList<>(10); + private String name; + public TestSuite(){ + + } + public TestSuite(final Class theClass) { + this.name= theClass.getName(); + Constructor constructor= null; + try { + constructor= getConstructor(theClass); + } catch (NoSuchMethodException e) { + addTest(warning("Class "+theClass.getName()+" has no public constructor TestCase(String name)")); + return; + } + + if (!Modifier.isPublic(theClass.getModifiers())) { + addTest(warning("Class "+theClass.getName()+" is not public")); + return; + } + + Vector names= new Vector<>(); + Method[] methods= theClass.getDeclaredMethods(); + for (int i= 0; i < methods.length; i++) { + addTestMethod(methods[i], names, constructor); + } + + if (tests.size() == 0) + addTest(warning("No tests found in "+theClass.getName())); + } + + private Constructor getConstructor(Class theClass) throws NoSuchMethodException { + Class[] args= { String.class }; + return theClass.getConstructor(args); + } + private void addTestMethod(Method m, Vector names, Constructor constructor) { + String name= m.getName(); + if (names.contains(name)) + return; + if (isPublicTestMethod(m)) { + names.addElement(name); + + Object[] args= new Object[]{name}; + try { + addTest((Test)constructor.newInstance(args)); + } catch (InstantiationException e) { + addTest(warning("Cannot instantiate test case: "+name+" ("+exceptionToString(e)+")")); + } catch (InvocationTargetException e) { + addTest(warning("Exception in constructor: "+name+" ("+exceptionToString(e.getTargetException())+")")); + } catch (IllegalAccessException e) { + addTest(warning("Cannot access test case: "+name+" ("+exceptionToString(e)+")")); + } + + } else { // almost a test method + if (isTestMethod(m)) + addTest(warning("Test method isn't public: "+m.getName())); + } + } + private boolean isPublicTestMethod(Method m) { + return isTestMethod(m) && Modifier.isPublic(m.getModifiers()); + } + private boolean isTestMethod(Method m) { + String name= m.getName(); + Class[] parameters= m.getParameterTypes(); + Class returnType= m.getReturnType(); + return parameters.length == 0 && name.startsWith("test") && returnType.equals(Void.TYPE); + } + public void addTest(Test test) { + tests.add(test); + } + + private Test warning(final String message) { + return new TestCase("warning") { + public void doRun() { + fail(message); + } + }; + } + private String exceptionToString(Throwable t) { + StringWriter stringWriter= new StringWriter(); + PrintWriter writer= new PrintWriter(stringWriter); + t.printStackTrace(writer); + return stringWriter.toString(); + + } + + + + @Override + public void run(TestResult result) { + for (Iterator e= tests(); e.hasNext(); ) { + if (result.shouldStop() ){ + break; + } + Test test= (Test)e.next(); + test.run(result); + } + + } + + public int countTestCases() { + int count= 0; + + for (Iterator e= tests(); e.hasNext(); ) { + Test test= e.next(); + count= count + test.countTestCases(); + } + return count; + } + public Iterator tests() { + return tests.iterator(); + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/Assert.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/Assert.java new file mode 100644 index 0000000000..4e5a9920bd --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/Assert.java @@ -0,0 +1,243 @@ +package org.litejunit.v2; + +/** + * A set of assert methods. + */ + +public class Assert { + /** + * Protect constructor since it is a static only class + */ + protected Assert() { + } + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError with the given message. + * @deprecated use assertTrue + */ + /*static public void assert(String message, boolean condition) { + if (!condition) + fail(message); + }*/ + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError. + * @deprecated use assertTrue + * + */ + /*static public void assert(boolean condition) { + assert(null, condition); + } +*/ + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError with the given message. + */ + static public void assertTrue(String message, boolean condition) { + if (!condition) + fail(message); + } + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError. + */ + static public void assertTrue(boolean condition) { + assertTrue(null, condition); + } + /** + * Fails a test with the given message. + */ + static public void fail(String message) { + throw new AssertionFailedError(message); + } + /** + * Fails a test with no message. + */ + static public void fail() { + fail(null); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(String message, Object expected, Object actual) { + if (expected == null && actual == null) + return; + if (expected != null && expected.equals(actual)) + return; + failNotEquals(message, expected, actual); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(Object expected, Object actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, double expected, double actual, double delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Double.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Double(expected), new Double(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) // Because comparison with NaN always returns false + failNotEquals(message, new Double(expected), new Double(actual)); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(double expected, double actual, double delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, float expected, float actual, float delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Float.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Float(expected), new Float(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) + failNotEquals(message, new Float(expected), new Float(actual)); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(float expected, float actual, float delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(String message, long expected, long actual) { + assertEquals(message, new Long(expected), new Long(actual)); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(long expected, long actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(String message, boolean expected, boolean actual) { + assertEquals(message, new Boolean(expected), new Boolean(actual)); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(boolean expected, boolean actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(String message, byte expected, byte actual) { + assertEquals(message, new Byte(expected), new Byte(actual)); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(byte expected, byte actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(String message, char expected, char actual) { + assertEquals(message, new Character(expected), new Character(actual)); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(char expected, char actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(String message, short expected, short actual) { + assertEquals(message, new Short(expected), new Short(actual)); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(short expected, short actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(String message, int expected, int actual) { + assertEquals(message, new Integer(expected), new Integer(actual)); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(int expected, int actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(Object object) { + assertNotNull(null, object); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(String message, Object object) { + assertTrue(message, object != null); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(Object object) { + assertNull(null, object); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(String message, Object object) { + assertTrue(message, object == null); + } + /** + * Asserts that two objects refer to the same object. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertSame(String message, Object expected, Object actual) { + if (expected == actual) + return; + failNotSame(message, expected, actual); + } + /** + * Asserts that two objects refer to the same object. If they are not + * the same an AssertionFailedError is thrown. + */ + static public void assertSame(Object expected, Object actual) { + assertSame(null, expected, actual); + } + + static private void failNotEquals(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected:<"+expected+"> but was:<"+actual+">"); + } + + static private void failNotSame(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected same"); + } +} \ No newline at end of file diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/AssertionFailedError.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/AssertionFailedError.java new file mode 100644 index 0000000000..49ebf0955e --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/AssertionFailedError.java @@ -0,0 +1,13 @@ +package org.litejunit.v2; + +/** + * Thrown when an assertion failed. + */ +public class AssertionFailedError extends Error { + + public AssertionFailedError () { + } + public AssertionFailedError (String message) { + super (message); + } +} \ No newline at end of file diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/Protectable.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/Protectable.java new file mode 100644 index 0000000000..f43f7d8e01 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/Protectable.java @@ -0,0 +1,14 @@ +package org.litejunit.v2; + +/** + * A Protectable can be run and can throw a Throwable. + * + * @see TestResult + */ +public interface Protectable { + + /** + * Run the the following method protected. + */ + public abstract void protect() throws Throwable; +} \ No newline at end of file diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/Test.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/Test.java new file mode 100644 index 0000000000..73de6a2e25 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/Test.java @@ -0,0 +1,6 @@ +package org.litejunit.v2; + +public interface Test { + public abstract int countTestCases(); + public void run(TestResult tr); +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/TestCase.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/TestCase.java new file mode 100644 index 0000000000..4f704d2866 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/TestCase.java @@ -0,0 +1,64 @@ +package org.litejunit.v2; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + + + +public abstract class TestCase extends Assert implements Test { + private String name; + + + public TestCase(String name) { + this.name = name; + } + + + public int countTestCases() { + return 1; + } + + protected void runTest() throws Throwable{ + Method runMethod= null; + try { + runMethod= getClass().getMethod(name, null); + } catch (NoSuchMethodException e) { + fail("Method \""+name+"\" not found"); + } + if (!Modifier.isPublic(runMethod.getModifiers())) { + fail("Method \""+name+"\" should be public"); + } + + try { + runMethod.invoke(this, new Class[0]); + } + catch (InvocationTargetException e) { + e.fillInStackTrace(); + throw e.getTargetException(); + } + catch (IllegalAccessException e) { + e.fillInStackTrace(); + throw e; + } + } + + protected void setUp() { + } + + protected void tearDown() { + } + + public void run(TestResult tr) { + tr.run(this); + } + public void doRun() throws Throwable{ + setUp(); + try{ + runTest(); + } + finally{ + tearDown(); + } + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/TestFailure.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/TestFailure.java new file mode 100644 index 0000000000..c40f6f89e0 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/TestFailure.java @@ -0,0 +1,39 @@ +package org.litejunit.v2; + +/** + * A TestFailure collects a failed test together with + * the caught exception. + * @see TestResult + */ +public class TestFailure { + protected Test failedTest; + protected Throwable thrownException; + + /** + * Constructs a TestFailure with the given test and exception. + */ + public TestFailure(Test failedTest, Throwable thrownException) { + this.failedTest= failedTest; + this.thrownException= thrownException; + } + /** + * Gets the failed test. + */ + public Test failedTest() { + return failedTest; + } + /** + * Gets the thrown exception. + */ + public Throwable thrownException() { + return thrownException; + } + /** + * Returns a short description of the failure. + */ + public String toString() { + StringBuffer buffer= new StringBuffer(); + buffer.append(failedTest+": "+thrownException.getMessage()); + return buffer.toString(); + } +} \ No newline at end of file diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/TestListener.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/TestListener.java new file mode 100644 index 0000000000..412febcc55 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/TestListener.java @@ -0,0 +1,15 @@ +package org.litejunit.v2; + +/** + * A Listener for test progress + */ +public interface TestListener { + + public void addError(Test test, Throwable t); + + public void addFailure(Test test, AssertionFailedError t); + + public void endTest(Test test); + + public void startTest(Test test); +} \ No newline at end of file diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/TestResult.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/TestResult.java new file mode 100644 index 0000000000..6fb789a495 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/TestResult.java @@ -0,0 +1,121 @@ +package org.litejunit.v2; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + + +public class TestResult extends Object { + protected List failures; + protected List errors; + protected List listeners; + protected int testCount; + private boolean stop; + + public TestResult() { + failures= new ArrayList<>(); + errors= new ArrayList<>(); + listeners = new ArrayList<>(); + testCount= 0; + stop= false; + } + + public void addError(Test test, Throwable t) { + errors.add(new TestFailure(test, t)); + for(TestListener listener: listeners){ + listener.addError(test, t); + } + } + + public void addFailure(Test test, AssertionFailedError t) { + failures.add(new TestFailure(test, t)); + for(TestListener listener: listeners){ + listener.addFailure(test, t); + } + } + + public void startTest(Test test) { + int count= test.countTestCases(); + testCount+= count; + for(TestListener listener: listeners){ + listener.startTest(test); + } + } + public void endTest(Test test) { + for(TestListener listener: listeners){ + listener.endTest(test); + } + } + + /** + * Runs a TestCase. + */ + protected void run(final TestCase test) { + startTest(test); + try { + test.doRun(); + } + catch (AssertionFailedError e) { + addFailure(test, e); + } + catch (Throwable e) { + addError(test, e); + } + + endTest(test); + } + /** + * Gets the number of run tests. + */ + public int runCount() { + return testCount; + } + public void runProtected(final Test test, Protectable p) { + try { + p.protect(); + } + catch (AssertionFailedError e) { + addFailure(test, e); + } + catch (Throwable e) { + addError(test, e); + } + } + + public boolean shouldStop() { + return stop; + } + + public void stop() { + stop= true; + } + + public int errorCount() { + return errors.size(); + } + + public Iterator errors() { + return errors.iterator(); + } + + public int failureCount() { + return failures.size(); + } + + public Iterator failures() { + return failures.iterator(); + } + /** + * Returns whether the entire test was successful or not. + */ + public boolean wasSuccessful() { + return this.failureCount() == 0 && this.errorCount() == 0; + } + public void addListener(TestListener listener) { + listeners.add(listener); + } + + public void removeListener(TestListener listener) { + listeners.remove(listener); + } +} \ No newline at end of file diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/TestSuite.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/TestSuite.java new file mode 100644 index 0000000000..9ad0a05433 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/TestSuite.java @@ -0,0 +1,137 @@ +package org.litejunit.v2; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; + +import java.util.Iterator; +import java.util.List; +import java.util.Vector; + + + + + + +public class TestSuite extends Assert implements Test { + private List tests= new ArrayList<>(10); + private String name; + public TestSuite(){ + + } + public TestSuite(final Class theClass) { + this.name= theClass.getName(); + Constructor constructor= null; + try { + constructor= getConstructor(theClass); + } catch (NoSuchMethodException e) { + addTest(warning("Class "+theClass.getName()+" has no public constructor TestCase(String name)")); + return; + } + + if (!Modifier.isPublic(theClass.getModifiers())) { + addTest(warning("Class "+theClass.getName()+" is not public")); + return; + } + + Vector names= new Vector<>(); + Method[] methods= theClass.getDeclaredMethods(); + for (int i= 0; i < methods.length; i++) { + addTestMethod(methods[i], names, constructor); + } + + if (tests.size() == 0) + addTest(warning("No tests found in "+theClass.getName())); + } + + public TestSuite(String name) { + this.name = name; + } + private Constructor getConstructor(Class theClass) throws NoSuchMethodException { + Class[] args= { String.class }; + return theClass.getConstructor(args); + } + private void addTestMethod(Method m, Vector names, Constructor constructor) { + String name= m.getName(); + if (names.contains(name)) + return; + if (isPublicTestMethod(m)) { + names.addElement(name); + + Object[] args= new Object[]{name}; + try { + addTest((Test)constructor.newInstance(args)); + } catch (InstantiationException e) { + addTest(warning("Cannot instantiate test case: "+name+" ("+exceptionToString(e)+")")); + } catch (InvocationTargetException e) { + addTest(warning("Exception in constructor: "+name+" ("+exceptionToString(e.getTargetException())+")")); + } catch (IllegalAccessException e) { + addTest(warning("Cannot access test case: "+name+" ("+exceptionToString(e)+")")); + } + + } else { // almost a test method + if (isTestMethod(m)) + addTest(warning("Test method isn't public: "+m.getName())); + } + } + private boolean isPublicTestMethod(Method m) { + return isTestMethod(m) && Modifier.isPublic(m.getModifiers()); + } + private boolean isTestMethod(Method m) { + String name= m.getName(); + Class[] parameters= m.getParameterTypes(); + Class returnType= m.getReturnType(); + return parameters.length == 0 && name.startsWith("test") && returnType.equals(Void.TYPE); + } + public void addTest(Test test) { + tests.add(test); + } + public void addTestSuite(Class testClass) { + addTest(new TestSuite(testClass)); + } + private Test warning(final String message) { + return new TestCase("warning") { + public void doRun() { + fail(message); + } + }; + } + private String exceptionToString(Throwable t) { + StringWriter stringWriter= new StringWriter(); + PrintWriter writer= new PrintWriter(stringWriter); + t.printStackTrace(writer); + return stringWriter.toString(); + + } + + + + @Override + public void run(TestResult result) { + for (Iterator e= tests(); e.hasNext(); ) { + if (result.shouldStop() ){ + break; + } + Test test= (Test)e.next(); + test.run(result); + } + + } + + public int countTestCases() { + int count= 0; + + for (Iterator e= tests(); e.hasNext(); ) { + Test test= e.next(); + count= count + test.countTestCases(); + } + return count; + } + public Iterator tests() { + return tests.iterator(); + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/runner/BaseTestRunner.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/runner/BaseTestRunner.java new file mode 100644 index 0000000000..b6ff184b69 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/runner/BaseTestRunner.java @@ -0,0 +1,85 @@ +package org.litejunit.v2.runner; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.text.NumberFormat; + +import org.litejunit.v2.Test; +import org.litejunit.v2.TestListener; +import org.litejunit.v2.TestSuite; + + +public abstract class BaseTestRunner implements TestListener { + public static final String SUITE_METHODNAME= "suite"; + /** + * Returns a filtered stack trace + */ + public static String getFilteredTrace(Throwable t) { + StringWriter stringWriter= new StringWriter(); + PrintWriter writer= new PrintWriter(stringWriter); + t.printStackTrace(writer); + StringBuffer buffer= stringWriter.getBuffer(); + String trace= buffer.toString(); + return trace; + //return BaseTestRunner.filterStack(trace); + } + + public Test getTest(String suiteClassName) { + if (suiteClassName.length() <= 0) { + return null; + } + Class testClass= null; + try { + testClass= loadSuiteClass(suiteClassName); + } catch (ClassNotFoundException e) { + String clazz= e.getMessage(); + if (clazz == null) + clazz= suiteClassName; + runFailed("Class not found \""+clazz+"\""); + return null; + } catch(Exception e) { + runFailed("Error: "+e.toString()); + return null; + } + Method suiteMethod= null; + try { + suiteMethod= testClass.getMethod(SUITE_METHODNAME, new Class[0]); + } catch(Exception e) { + // try to extract a test suite automatically + //clearStatus(); + return new TestSuite(testClass); + } + Test test= null; + try { + test= (Test)suiteMethod.invoke(null, new Class[0]); // static method + if (test == null) + return test; + } + catch (InvocationTargetException e) { + runFailed("Failed to invoke suite():" + e.getTargetException().toString()); + return null; + } + catch (IllegalAccessException e) { + runFailed("Failed to invoke suite():" + e.toString()); + return null; + } + + //clearStatus(); + return test; + } + protected Class loadSuiteClass(String suiteClassName) throws ClassNotFoundException { + + //TODO + return Class.forName(suiteClassName); + + + //return getLoader().load(suiteClassName); + } + protected abstract void runFailed(String message); + + public String elapsedTimeAsString(long runTime) { + return NumberFormat.getInstance().format((double)runTime/1000); + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/textui/TestRunner.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/textui/TestRunner.java new file mode 100644 index 0000000000..0ffab6b747 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v2/textui/TestRunner.java @@ -0,0 +1,202 @@ +package org.litejunit.v2.textui; + + +import java.lang.reflect.*; +import java.text.NumberFormat; +import java.util.*; + +import org.litejunit.v2.AssertionFailedError; +import org.litejunit.v2.Test; +import org.litejunit.v2.TestFailure; +import org.litejunit.v2.TestResult; +import org.litejunit.v2.TestSuite; +import org.litejunit.v2.runner.BaseTestRunner; + +import java.io.PrintStream; + + +public class TestRunner extends BaseTestRunner { + PrintStream writer= System.out; + int column= 0; + + /** + * Constructs a TestRunner. + */ + public TestRunner() { + } + + + /** + * Always use the StandardTestSuiteLoader. Overridden from + * BaseTestRunner. + */ + /*public TestSuiteLoader getLoader() { + return new StandardTestSuiteLoader(); + }*/ + + public synchronized void addError(Test test, Throwable t) { + writer().print("E"); + } + + public synchronized void addFailure(Test test, AssertionFailedError t) { + writer().print("F"); + } + + + + public TestResult doRun(Test suite) { + TestResult result= new TestResult(); + result.addListener(this); + long startTime= System.currentTimeMillis(); + suite.run(result); + long endTime= System.currentTimeMillis(); + long runTime= endTime-startTime; + writer().println(); + writer().println("Time: "+elapsedTimeAsString(runTime)); + print(result); + + writer().println(); + + + return result; + } + + + + public synchronized void startTest(Test test) { + writer().print("."); + if (column++ >= 40) { + writer().println(); + column= 0; + } + } + + public void endTest(Test test) { + } + + public static void main(String args[]) { + TestRunner testRunner= new TestRunner(); + try { + TestResult r= testRunner.start(args); + if (!r.wasSuccessful()) + System.exit(-1); + System.exit(0); + } catch(Exception e) { + System.err.println(e.getMessage()); + System.exit(-2); + } + } + /** + * Prints failures to the standard output + */ + public synchronized void print(TestResult result) { + printErrors(result); + printFailures(result); + printHeader(result); + } + /** + * Prints the errors to the standard output + */ + public void printErrors(TestResult result) { + if (result.errorCount() != 0) { + if (result.errorCount() == 1) + writer().println("There was "+result.errorCount()+" error:"); + else + writer().println("There were "+result.errorCount()+" errors:"); + + int i= 1; + for (Iterator e= result.errors(); e.hasNext(); i++) { + TestFailure failure= e.next(); + writer().println(i+") "+failure.failedTest()); + writer().print(getFilteredTrace(failure.thrownException())); + } + } + } + /** + * Prints failures to the standard output + */ + public void printFailures(TestResult result) { + if (result.failureCount() != 0) { + if (result.failureCount() == 1) + writer().println("There was " + result.failureCount() + " failure:"); + else + writer().println("There were " + result.failureCount() + " failures:"); + int i = 1; + for (Iterator e= result.failures(); e.hasNext(); i++) { + TestFailure failure= (TestFailure) e.next(); + writer().print(i + ") " + failure.failedTest()); + Throwable t= failure.thrownException(); + writer().print(getFilteredTrace(failure.thrownException())); + } + } + } + /** + * Prints the header of the report + */ + public void printHeader(TestResult result) { + if (result.wasSuccessful()) { + writer().println(); + writer().print("OK"); + writer().println (" (" + result.runCount() + " tests)"); + + } else { + writer().println(); + writer().println("FAILURES!!!"); + writer().println("Tests run: "+result.runCount()+ + ", Failures: "+result.failureCount()+ + ", Errors: "+result.errorCount()); + } + } + + + /** + * Starts a test run. Analyzes the command line arguments + * and runs the given test suite. + */ + protected TestResult start(String args[]) throws Exception { + if(args.length == 0){ + throw new Exception("Usage: TestRunner testCaseName"); + } + String testCase= args[0]; + + try { + Test suite= getTest(testCase); + return doRun(suite); + } + catch(Exception e) { + throw new Exception("Could not create and run test suite: "+e); + } + } + + protected void runFailed(String message) { + System.err.println(message); + System.exit(-1); + } + + /** + * Runs a suite extracted from a TestCase subclass. + */ + static public void run(Class testClass) { + run(new TestSuite(testClass)); + } + /** + * Runs a single test and collects its results. + * This method can be used to start a test run + * from your program. + *
+	 * public static void main (String[] args) {
+	 *     test.textui.TestRunner.run(suite());
+	 * }
+	 * 
+ */ + static public void run(Test suite) { + TestRunner aTestRunner= new TestRunner(); + aTestRunner.doRun(suite); + } + + protected PrintStream writer() { + return writer; + } + + +} \ No newline at end of file diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/After.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/After.java new file mode 100644 index 0000000000..f27496b8e1 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/After.java @@ -0,0 +1,12 @@ +package org.litejunit.v3; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface After { +} + diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/AfterClass.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/AfterClass.java new file mode 100644 index 0000000000..82618d7afc --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/AfterClass.java @@ -0,0 +1,13 @@ +package org.litejunit.v3; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface AfterClass { +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/Assert.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/Assert.java new file mode 100644 index 0000000000..6d1b7689f9 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/Assert.java @@ -0,0 +1,269 @@ +package org.litejunit.v3; + +/** + * A set of assertion methods useful for writing tests. Only failed assertions are recorded. + * These methods can be used directly: Assert.assertEquals(...), however, they + * read better if they are referenced through static import:
+ * + * import static org.junit.Assert.*;
+ * ...
+ *   assertEquals(...);
+ *
+ */ + +public class Assert { + /** + * Protect constructor since it is a static only class + */ + protected Assert() { + } + + /** + * Asserts that a condition is true. If it isn't it throws an + * AssertionError with the given message. + */ + static public void assertTrue(String message, boolean condition) { + if (!condition) + fail(message); + } + + /** + * Asserts that a condition is true. If it isn't it throws an + * AssertionError. + */ + static public void assertTrue(boolean condition) { + assertTrue(null, condition); + } + + /** + * Asserts that a condition is false. If it isn't it throws an + * AssertionError with the given message. + */ + static public void assertFalse(String message, boolean condition) { + assertTrue(message, !condition); + } + + /** + * Asserts that a condition is false. If it isn't it throws an + * AssertionError. + */ + static public void assertFalse(boolean condition) { + assertFalse(null, condition); + } + + /** + * Fails a test with the given message. + */ + static public void fail(String message) { + throw new AssertionError(message); + } + + /** + * Fails a test with no message. + */ + static public void fail() { + fail(null); + } + + /** + * Asserts that two objects are equal. If they are not, an + * AssertionError is thrown with the given message. + */ + static public void assertEquals(String message, Object expected, Object actual) { + if (expected == null && actual == null) + return; + if (expected != null && expected.equals(actual)) + return; + if (expected instanceof String && actual instanceof String) + throw new ComparisonFailure(message, (String)expected, (String)actual); + else + failNotEquals(message, expected, actual); + } + + /** + * Asserts that two objects are equal. If they are not, an + * AssertionError is thrown. + */ + static public void assertEquals(Object expected, Object actual) { + assertEquals(null, expected, actual); + } + + /** + * Asserts that two object arrays are equal. If they are not, an + * AssertionError is thrown with the given message. + */ + public static void assertEquals(String message, Object[] expecteds, Object[] actuals) { + if (expecteds == actuals) + return; + String header = message == null ? "" : message + ": "; + if (expecteds == null) + fail(header + "expected array was null"); + if (actuals == null) + fail(header + "actual array was null"); + if (actuals.length != expecteds.length) + fail(header + "array lengths differed, expected.length=" + expecteds.length + " actual.length=" + actuals.length); + + for (int i= 0; i < expecteds.length; i++) { + Object o1= expecteds[i]; + Object o2= actuals[i]; + if (o1.getClass().isArray() && o2.getClass().isArray()) { + Object[] expected= (Object[]) o1; + Object[] actual= (Object[]) o2; + assertEquals(header + "arrays first differed at element " + i + ";", expected, actual); + } else + assertEquals(header + "arrays first differed at element [" + i + "];", o1, o2); + } + } + + /** + * Asserts that two object arrays are equal. If they are not, an + * AssertionError is thrown. + */ + public static void assertEquals(Object[] expecteds, Object[] actuals) { + assertEquals(null, expecteds, actuals); + } + + /** + * Asserts that two doubles are equal to within a positive delta. If they + * are not, an AssertionError is thrown with the given message. If the + * expected value is infinity then the delta value is ignored. NaNs are + * considered equal: + * assertEquals(Double.NaN, Double.NaN, *) passes + */ + static public void assertEquals(String message, double expected, double actual, double delta) { + if (Double.compare(expected, actual) == 0) + return; + if (!(Math.abs(expected - actual) <= delta)) + failNotEquals(message, new Double(expected), new Double(actual)); + } + + /** + * Asserts that two doubles are equal to within a positive delta. If they + * are not, an AssertionError is thrown. If the + * expected value is infinity then the delta value is ignored.NaNs are + * considered equal: + * assertEquals(Double.NaN, Double.NaN, *) passes + */ + static public void assertEquals(double expected, double actual, double delta) { + assertEquals(null, expected, actual, delta); + } + + /** + * Asserts that two floats are equal to within a positive delta. If they + * are not, an AssertionError is thrown with the given message. If the + * expected value is infinity then the delta value is ignored.NaNs are + * considered equal: + * assertEquals(Float.NaN, Float.NaN, *) passes + */ + static public void assertEquals(String message, float expected, float actual, float delta) { + if (Float.compare(expected, actual) == 0) + return; + if (!(Math.abs(expected - actual) <= delta)) + failNotEquals(message, new Float(expected), new Float(actual)); + } + + /** + * Asserts that two floats are equal to within a positive delta. If they + * are not, an AssertionError is thrown. If the + * expected value is infinity then the delta value is ignored.NaNs are + * considered equal: + * assertEquals(Float.NaN, Float.NaN, *) passes + */ + static public void assertEquals(float expected, float actual, float delta) { + assertEquals(null, expected, actual, delta); + } + + /** + * Asserts that an object isn't null. If it is an AssertionError is + * thrown with the given message. + */ + static public void assertNotNull(String message, Object object) { + assertTrue(message, object != null); + } + + /** + * Asserts that an object isn't null. If it is an AssertionError is + * thrown. + */ + static public void assertNotNull(Object object) { + assertNotNull(null, object); + } + + /** + * Asserts that an object is null. If it is not, an AssertionError is + * thrown with the given message. + */ + static public void assertNull(String message, Object object) { + assertTrue(message, object == null); + } + + /** + * Asserts that an object is null. If it isn't an AssertionError is + * thrown. + */ + static public void assertNull(Object object) { + assertNull(null, object); + } + + /** + * Asserts that two objects refer to the same object. If they are not, an + * AssertionError is thrown with the given message. + */ + static public void assertSame(String message, Object expected, Object actual) { + if (expected == actual) + return; + failNotSame(message, expected, actual); + } + + /** + * Asserts that two objects refer to the same object. If they are not the + * same, an AssertionError is thrown. + */ + static public void assertSame(Object expected, Object actual) { + assertSame(null, expected, actual); + } + + /** + * Asserts that two objects do not refer to the same object. If they do + * refer to the same object, an AssertionError is thrown with the given + * message. + */ + static public void assertNotSame(String message, Object expected, Object actual) { + if (expected == actual) + failSame(message); + } + + /** + * Asserts that two objects do not refer to the same object. If they do + * refer to the same object, an AssertionError is thrown. + */ + static public void assertNotSame(Object expected, Object actual) { + assertNotSame(null, expected, actual); + } + + static private void failSame(String message) { + String formatted= ""; + if (message != null) + formatted= message + " "; + fail(formatted + "expected not same"); + } + + static private void failNotSame(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message + " "; + fail(formatted + "expected same:<" + expected + "> was not:<" + actual + ">"); + } + + static private void failNotEquals(String message, Object expected, Object actual) { + fail(format(message, expected, actual)); + } + + static String format(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message + " "; + return formatted + "expected:<" + expected + "> but was:<" + actual + ">"; + } + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/Before.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/Before.java new file mode 100644 index 0000000000..72e0e3beb2 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/Before.java @@ -0,0 +1,13 @@ +package org.litejunit.v3; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Before { +} + diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/BeforeClass.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/BeforeClass.java new file mode 100644 index 0000000000..6334ab45b2 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/BeforeClass.java @@ -0,0 +1,11 @@ +package org.litejunit.v3; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface BeforeClass { +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/ComparisonFailure.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/ComparisonFailure.java new file mode 100644 index 0000000000..77f9ea6f5f --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/ComparisonFailure.java @@ -0,0 +1,124 @@ +package org.litejunit.v3; + +/** + * Thrown when an assertEquals(String, String) fails. Create and throw + * a ComparisonFailure manually if you want to show users the difference between two complex + * strings. + * + * Inspired by a patch from Alex Chaffee (alex@purpletech.com) + */ +public class ComparisonFailure extends AssertionError { + private static final int MAX_CONTEXT_LENGTH= 20; + private static final long serialVersionUID= 1L; + + private String fExpected; + private String fActual; + + /** + * Constructs a comparison failure. + * @param message the identifying message or null + * @param expected the expected string value + * @param actual the actual string value + */ + public ComparisonFailure (String message, String expected, String actual) { + super (message); + fExpected= expected; + fActual= actual; + } + + /** + * Returns "..." in place of common prefix and "..." in + * place of common suffix between expected and actual. + * + * @see java.lang.Throwable#getMessage() + */ + @Override + public String getMessage() { + return new ComparisonCompactor(MAX_CONTEXT_LENGTH, fExpected, fActual).compact(super.getMessage()); + } + + /** + * Returns the actual value + * @return the actual string value + */ + public String getActual() { + return fActual; + } + /** + * Returns the expected value + * @return the expected string value + */ + public String getExpected() { + return fExpected; + } + + private static class ComparisonCompactor { + private static final String ELLIPSIS= "..."; + private static final String DELTA_END= "]"; + private static final String DELTA_START= "["; + + private int fContextLength; + private String fExpected; + private String fActual; + private int fPrefix; + private int fSuffix; + + public ComparisonCompactor(int contextLength, String expected, String actual) { + fContextLength= contextLength; + fExpected= expected; + fActual= actual; + } + + public String compact(String message) { + if (fExpected == null || fActual == null || areStringsEqual()) + return Assert.format(message, fExpected, fActual); + + findCommonPrefix(); + findCommonSuffix(); + String expected= compactString(fExpected); + String actual= compactString(fActual); + return Assert.format(message, expected, actual); + } + + private String compactString(String source) { + String result= DELTA_START + source.substring(fPrefix, source.length() - fSuffix + 1) + DELTA_END; + if (fPrefix > 0) + result= computeCommonPrefix() + result; + if (fSuffix > 0) + result= result + computeCommonSuffix(); + return result; + } + + private void findCommonPrefix() { + fPrefix= 0; + int end= Math.min(fExpected.length(), fActual.length()); + for (; fPrefix < end; fPrefix++) { + if (fExpected.charAt(fPrefix) != fActual.charAt(fPrefix)) + break; + } + } + + private void findCommonSuffix() { + int expectedSuffix= fExpected.length() - 1; + int actualSuffix= fActual.length() - 1; + for (; actualSuffix >= fPrefix && expectedSuffix >= fPrefix; actualSuffix--, expectedSuffix--) { + if (fExpected.charAt(expectedSuffix) != fActual.charAt(actualSuffix)) + break; + } + fSuffix= fExpected.length() - expectedSuffix; + } + + private String computeCommonPrefix() { + return (fPrefix > fContextLength ? ELLIPSIS : "") + fExpected.substring(Math.max(0, fPrefix - fContextLength), fPrefix); + } + + private String computeCommonSuffix() { + int end= Math.min(fExpected.length() - fSuffix + 1 + fContextLength, fExpected.length()); + return fExpected.substring(fExpected.length() - fSuffix + 1, end) + (fExpected.length() - fSuffix + 1 < fExpected.length() - fContextLength ? ELLIPSIS : ""); + } + + private boolean areStringsEqual() { + return fExpected.equals(fActual); + } + } +} \ No newline at end of file diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/Ignore.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/Ignore.java new file mode 100644 index 0000000000..1652ac2431 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/Ignore.java @@ -0,0 +1,31 @@ +package org.litejunit.v3; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Sometimes you want to temporarily disable a test. Methods annotated with @Test + * that are also annotated with @Ignore will not be executed as tests. Native JUnit 4 test runners + * should report the number of ignored tests along with the number of tests that ran and the + * number of tests that failed. + *

+ * For example:
+ * + *   @Ignore @Test public void something() { ...
+ *
+ * @Ignore takes an optional default parameter if you want to record why a test is being ignored:
+ * + *   @Ignore("not ready yet") @Test public void something() { ...
+ *
+ * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Ignore { + /** + * The optional reason why the test is ignored. + */ + String value() default ""; +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/Test.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/Test.java new file mode 100644 index 0000000000..f390d10671 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/Test.java @@ -0,0 +1,62 @@ +package org.litejunit.v3; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * The Test annotation tells JUnit that the public void method + * to which it is attached can be run as a test case. To run the method, + * JUnit first constructs a fresh instance of the class then invokes the + * annotated method. Any exceptions thrown by the test will be reported + * by JUnit as a failure. If no exceptions are thrown, the test is assumed + * to have succeeded. + *

+ * A simple test looks like this:
+ * + * public class Example {
+ *   @Test public void method() {
+ *     System.out.println("Hello");
+ *   }
+ * } + *
+ *

+ * The Test annotation supports two optional parameters. + * The first, expected, declares that a test method should throw + * an exception. If it doesn't throw an exception or if it throws a different exception + * than the one declared, the test fails. For example, the following test succeeds:
+ * + *   @Test(expected=IndexOutOfBoundsException.class) public void outOfBounds() {
+ *     new ArrayList<Object>().get(1);
+ *   }
+ *
+ *

+ * The second optional parameter, timeout, causes a test to fail if it takes longer than a specified + * amount of clock time (measured in milliseconds). The following test fails:
+ * + *   @Test(timeout=100) public void infinity() {
+ *     for(;;);
+ *   }
+ *
+ */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Test { + static class None extends Throwable { + private static final long serialVersionUID= 1L; + private None() { + } + } + + /** + * Optionally specify expected, a Throwable, to cause a test method to succeed iff + * an exception of the specified class is thrown by the method. + */ + Class expected() default None.class; + + /** + * Optionally specify timeout in milliseconds to cause a test method to fail if it + * takes longer than that number of milliseconds.*/ + long timeout() default 0L; +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/notification/Failure.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/notification/Failure.java new file mode 100644 index 0000000000..2eb516b75f --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/notification/Failure.java @@ -0,0 +1,78 @@ +package org.litejunit.v3.notification; + +import java.io.PrintWriter; +import java.io.StringWriter; + +import org.litejunit.v3.runner.Description; + + +/** + * A Failure holds a description of the failed test and the + * exception that was thrown while running it. In most cases the Description + * will be of a single test. However, if problems are encountered while constructing the + * test (for example, if a @BeforeClass method is not static), it may describe + * something other than a single test. + */ +public class Failure { + private final Description fDescription; + private Throwable fThrownException; + + /** + * Constructs a Failure with the given description and exception. + * @param description a Description of the test that failed + * @param thrownException the exception that was thrown while running the test + */ + public Failure(Description description, Throwable thrownException) { + fThrownException = thrownException; + fDescription= description; + } + + /** + * @return a user-understandable label for the test + */ + public String getTestHeader() { + return fDescription.getDisplayName(); + } + + /** + * @return the raw description of the context of the failure. + */ + public Description getDescription() { + return fDescription; + } + + /** + * @return the exception thrown + */ + + public Throwable getException() { + return fThrownException; + } + + @Override + public String toString() { + StringBuffer buffer= new StringBuffer(); + buffer.append(getTestHeader() + ": "+fThrownException.getMessage()); + return buffer.toString(); + } + + /** + * Convenience method + * @return the printed form of the exception + */ + public String getTrace() { + StringWriter stringWriter= new StringWriter(); + PrintWriter writer= new PrintWriter(stringWriter); + getException().printStackTrace(writer); + StringBuffer buffer= stringWriter.getBuffer(); + return buffer.toString(); + } + + /** + * Convenience method + * @return the message of the thrown exception + */ + public String getMessage() { + return getException().getMessage(); + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/notification/RunListener.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/notification/RunListener.java new file mode 100644 index 0000000000..aa30aa9abf --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/notification/RunListener.java @@ -0,0 +1,53 @@ +package org.litejunit.v3.notification; + +import org.litejunit.v3.runner.Description; +import org.litejunit.v3.runner.Result; + + +public class RunListener { + + /** + * Called before any tests have been run. + * @param description describes the tests to be run + */ + public void testRunStarted(Description description) throws Exception { + } + + /** + * Called when all tests have finished + * @param result the summary of the test run, including all the tests that failed + */ + public void testRunFinished(Result result) throws Exception { + } + + /** + * Called when an atomic test is about to be started. + * @param description the description of the test that is about to be run (generally a class and method name) + */ + public void testStarted(Description description) throws Exception { + } + + /** + * Called when an atomic test has finished, whether the test succeeds or fails. + * @param description the description of the test that just ran + */ + public void testFinished(Description description) throws Exception { + } + + /** + * Called when an atomic test fails. + * @param failure describes the test that failed and the exception that was thrown + */ + public void testFailure(Failure failure) throws Exception { + } + + /** + * Called when a test will not be run, generally because a test method is annotated with @Ignored. + * @param description describes the test that will not be run + */ + public void testIgnored(Description description) throws Exception { + } + +} + + diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/notification/RunNotifier.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/notification/RunNotifier.java new file mode 100644 index 0000000000..d7d16e0677 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/notification/RunNotifier.java @@ -0,0 +1,139 @@ +package org.litejunit.v3.notification; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.litejunit.v3.runner.Description; +import org.litejunit.v3.runner.Result; + + + +/** + * If you write custom runners, you may need to notify JUnit of your progress running tests. + * Do this by invoking the RunNotifier passed to your implementation of + * Runner.run(RunNotifier notifier). Future evolution of this class is likely to + * move fireTestRunStarted() and fireTestRunFinished() + * to a separate class since they should only be called once per run. + */ +public class RunNotifier { + private List fListeners= new ArrayList(); + private boolean fPleaseStop= false; + + /** Internal use only + */ + public void addListener(RunListener listener) { + fListeners.add(listener); + } + + /** Internal use only + */ + public void removeListener(RunListener listener) { + fListeners.remove(listener); + } + + private abstract class SafeNotifier { + void run() { + for (Iterator all= fListeners.iterator(); all.hasNext();) { + try { + notifyListener(all.next()); + } catch (Exception e) { + all.remove(); // Remove the offending listener first to avoid an infinite loop + fireTestFailure(new Failure(Description.TEST_MECHANISM, e)); + } + } + } + + abstract protected void notifyListener(RunListener each) throws Exception; + } + + /** + * Do not invoke. + */ + public void fireTestRunStarted(final Description description) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testRunStarted(description); + }; + }.run(); + } + + /** + * Do not invoke. + */ + public void fireTestRunFinished(final Result result) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testRunFinished(result); + }; + }.run(); + } + + /** + * Invoke to tell listeners that an atomic test is about to start. + * @param description the description of the atomic test (generally a class and method name) + * @throws StoppedByUserException thrown if a user has requested that the test run stop + */ + public void fireTestStarted(final Description description) throws StoppedByUserException { + if (fPleaseStop) + throw new StoppedByUserException(); + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testStarted(description); + }; + }.run(); + } + + /** + * Invoke to tell listeners that an atomic test failed. + * @param failure the description of the test that failed and the exception thrown + */ + public void fireTestFailure(final Failure failure) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testFailure(failure); + }; + }.run(); + } + + /** + * Invoke to tell listeners that an atomic test was ignored. + * @param description the description of the ignored test + */ + public void fireTestIgnored(final Description description) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testIgnored(description); + }; + }.run(); + } + + /** + * Invoke to tell listeners that an atomic test finished. Always invoke fireTestFinished() + * if you invoke fireTestStarted() as listeners are likely to expect them to come in pairs. + * @param description the description of the test that finished + */ + public void fireTestFinished(final Description description) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testFinished(description); + }; + }.run(); + } + + /** + * Ask that the tests run stop before starting the next test. Phrased politely because + * the test currently running will not be interrupted. It seems a little odd to put this + * functionality here, but the RunNotifier is the only object guaranteed + * to be shared amongst the many runners involved. + */ + public void pleaseStop() { + fPleaseStop= true; + } +} \ No newline at end of file diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/notification/StoppedByUserException.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/notification/StoppedByUserException.java new file mode 100644 index 0000000000..829462445c --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/notification/StoppedByUserException.java @@ -0,0 +1,11 @@ +package org.litejunit.v3.notification; + +/** + * Thrown when a user has requested that the test run stop. Writers of + * test running GUIs should be prepared to catch a StoppedByUserException. + * + * @see org.junit.runner.notification.RunNotifier + */ +public class StoppedByUserException extends RuntimeException { + private static final long serialVersionUID= 1L; +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/requests/ClassRequest.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/requests/ClassRequest.java new file mode 100644 index 0000000000..315bbb6482 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/requests/ClassRequest.java @@ -0,0 +1,48 @@ +/** + * + */ +package org.litejunit.v3.requests; + +import java.lang.reflect.Constructor; + +import org.litejunit.v3.runner.Request; +import org.litejunit.v3.runner.Runner; +import org.litejunit.v3.runners.TestClassRunner; + + +public class ClassRequest extends Request { + private final Class fTestClass; + + public ClassRequest(Class each) { + fTestClass= each; + } + + @Override + public Runner getRunner() { + Class runnerClass= getRunnerClass(fTestClass); + try { + Constructor constructor= runnerClass.getConstructor(Class.class); // TODO good error message if no such constructor + Runner runner= (Runner) constructor + .newInstance(new Object[] { fTestClass }); + return runner; + } catch (Exception e) { + return null; + //return Request.errorReport(fTestClass, e).getRunner(); + } + } + + Class getRunnerClass(Class testClass) { + /*RunWith annotation= testClass.getAnnotation(RunWith.class); + if (annotation != null) { + return annotation.value(); + } else if (isPre4Test(testClass)) { + return OldTestClassRunner.class; + } else {*/ + return TestClassRunner.class; + /*}*/ + } + + /*boolean isPre4Test(Class testClass) { + return junit.framework.TestCase.class.isAssignableFrom(testClass); + }*/ +} \ No newline at end of file diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Description.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Description.java new file mode 100644 index 0000000000..db3610fd3f --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Description.java @@ -0,0 +1,127 @@ +package org.litejunit.v3.runner; + +import java.util.ArrayList; + +/** + * A Description describes a test which is to be run or has been run. Descriptions can + * be atomic (a single test) or compound (containing children tests). Descriptions are used + * to provide feedback about the tests that are about to run (for example, the tree view + * visible in many IDEs) or tests that have been run (for example, the failures view).

+ * Descriptions are implemented as a single class rather than a Composite because + * they are entirely informational. They contain no logic aside from counting their tests.

+ * In the past, we used the raw junit.framework.TestCases and junit.framework.TestSuites + * to display the tree of tests. This was no longer viable in JUnit 4 because atomic tests no longer have a superclass below Object. + * We needed a way to pass a class and name together. Description emerged from this. + * + * @see org.junit.runner.Request + * @see org.junit.runner.Runner + */ +public class Description { + + /** + * Create a Description named name. + * Generally, you will add children to this Description. + * @param name The name of the Description + * @return A Description named name + */ + public static Description createSuiteDescription(String name) { + return new Description(name); + } + + /** + * Create a Description of a single test named name in the class clazz. + * Generally, this will be a leaf Description. + * @param clazz The class of the test + * @param name The name of the test (a method name for test annotated with @Test) + * @return A Description named name + */ + public static Description createTestDescription(Class clazz, String name) { + return new Description(String.format("%s(%s)", name, clazz.getName())); + } + + /** + * Create a generic Description that says there are tests in testClass. + * This is used as a last resort when you cannot precisely describe the individual tests in the class. + * @param testClass A Class containing tests + * @return A Description of testClass + */ + public static Description createSuiteDescription(Class testClass) { + return new Description(testClass.getName()); + } + + public static Description TEST_MECHANISM = new Description("Test mechanism"); + private final ArrayList fChildren= new ArrayList(); + private final String fDisplayName; + + //TODO we seem to be using the static factories exclusively + private Description(final String displayName) { + fDisplayName= displayName; + } + + /** + * @return a user-understandable label + */ + public String getDisplayName() { + return fDisplayName; + } + + /** + * Add description as a child of the receiver. + * @param description The soon-to-be child. + */ + public void addChild(Description description) { + getChildren().add(description); + } + + /** + * @return the receiver's children, if any + */ + public ArrayList getChildren() { + return fChildren; + } + + /** + * @return true if the receiver is a suite + */ + public boolean isSuite() { + return !isTest(); + } + + /** + * @return true if the receiver is an atomic test + */ + public boolean isTest() { + return getChildren().isEmpty(); + } + + /** + * @return the total number of atomic tests in the receiver + */ + public int testCount() { + if (isTest()) + return 1; + int result= 0; + for (Description child : getChildren()) + result+= child.testCount(); + return result; + } + + @Override + public int hashCode() { + return getDisplayName().hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof Description)) + return false; + Description d = (Description) obj; + return getDisplayName().equals(d.getDisplayName()) + && getChildren().equals(d.getChildren()); + } + + @Override + public String toString() { + return getDisplayName(); + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/JUnitCore.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/JUnitCore.java new file mode 100644 index 0000000000..662f5ffd0c --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/JUnitCore.java @@ -0,0 +1,167 @@ +package org.litejunit.v3.runner; + +import java.util.ArrayList; +import java.util.List; + +import org.litejunit.v3.notification.RunListener; +import org.litejunit.v3.notification.RunNotifier; +import org.litejunit.v3.runners.InitializationError; +import org.litejunit.v3.runners.TestClassRunner; +import org.litejunit.v3.runners.TextListener; + + + +/** + * JUnitCore is a facade for running tests. It supports running JUnit 4 tests, + * JUnit 3.8.2 tests, and mixtures. To run tests from the command line, run java org.junit.runner.JUnitCore TestClass1 TestClass2 .... + * For one-shot test runs, use the static method runClasses(Class... classes) + * . If you want to add special listeners, + * create an instance of JUnitCore first and use it to run the tests. + * + * @see org.junit.runner.Result + * @see org.junit.runner.notification.RunListener + * @see org.junit.runner.Request + */ +public class JUnitCore { + + private RunNotifier notifier; + + /** + * Create a new JUnitCore to run tests. + */ + public JUnitCore() { + notifier= new RunNotifier(); + } + + /** + * Run the tests contained in the classes named in the args. + * If all tests run successfully, exit with a status of 0. Otherwise exit with a status of 1. + * Write feedback while tests are running and write + * stack traces for all failed tests after the tests all complete. + * @param args names of classes in which to find tests to run + */ + /*public static void main(String... args) { + Class clz = null; + try { + clz = Class.forName(args[0]); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + return; + } + + Request request = Request.aClass(clz); + + new JUnitCore().run(request); + + Result result= new JUnitCore().runMain(args); + killAllThreads(result); + }*/ + public static void runClass(Class clz){ + try { + TestClassRunner runner = new TestClassRunner(clz); + JUnitCore core = new JUnitCore(); + core.addListener(new TextListener()); + Result result = core.run(runner); + + } catch (InitializationError e) { + + e.printStackTrace(); + } + + } + /*private static void killAllThreads(Result result) { + System.exit(result.wasSuccessful() ? 0 : 1); + }*/ + + /** + * Run the tests contained in classes. Write feedback while the tests + * are running and write stack traces for all failed tests after all tests complete. This is + * similar to main(), but intended to be used programmatically. + * @param classes Classes in which to find tests + * @return a Result describing the details of the test run and the failed tests. + */ + /*public static Result runClasses(Class... classes) { + return new JUnitCore().run(classes); + }*/ + + /** + * Do not use. Testing purposes only. + */ + /*public Result runMain(String... args) { + + List classes= new ArrayList(); + for (String each : args) + try { + classes.add(Class.forName(each)); + } catch (ClassNotFoundException e) { + System.out.println("Could not find class: " + each); + } + RunListener listener= new TextListener(); + addListener(listener); + return run(classes.toArray(new Class[0])); + }*/ + + + + /** + * Run all the tests in classes. + * @param classes the classes containing tests + * @return a Result describing the details of the test run and the failed tests. + */ + /*public Result run(Class... classes) { + return run(Request.classes("All", classes)); + }*/ + + /** + * Run all the tests contained in request. + * @param request the request describing tests + * @return a Result describing the details of the test run and the failed tests. + */ + /*public Result run(Request request) { + return run(request.getRunner()); + }*/ + + /** + * Run all the tests contained in JUnit 3.8.x test. Here for backward compatibility. + * @param test the old-style test + * @return a Result describing the details of the test run and the failed tests. + */ + /*public Result run(junit.framework.Test test) { + return run(new OldTestClassRunner(test)); + } + */ + /** + * Do not use. Testing purposes only. + */ + public Result run(Runner runner) { + Result result= new Result(); + RunListener listener= result.createListener(); + addListener(listener); + + try { + notifier.fireTestRunStarted(runner.getDescription()); + runner.run(notifier); + notifier.fireTestRunFinished(result); + } finally { + removeListener(listener); + } + return result; + } + + /** + * Add a listener to be notified as the tests run. + * @param listener the listener + * @see org.junit.runner.notification.RunListener + */ + public void addListener(RunListener listener) { + notifier.addListener(listener); + } + + /** + * Remove a listener. + * @param listener the listener to remove + */ + public void removeListener(RunListener listener) { + notifier.removeListener(listener); + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Request.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Request.java new file mode 100644 index 0000000000..02db808bb7 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Request.java @@ -0,0 +1,86 @@ +package org.litejunit.v3.runner; + +import org.litejunit.v3.requests.ClassRequest; + + + +/** + * A Request is an abstract description of tests to be run. Older versions of + * JUnit did not need such a concept--tests to be run were described either by classes containing + * tests or a tree of Tests. However, we want to support filtering and sorting, + * so we need a more abstract specification than the tests themselves and a richer + * specification than just the classes. + *

+ * The flow when JUnit runs tests is that a Request specifies some tests to be run -> + * a Runner is created for each class implied by the Request -> the Runner + * returns a detailed Description which is a tree structure of the tests to be run. + */ +public abstract class Request { + /** + * Create a Request that, when processed, will run a single test. + * This is done by filtering out all other tests. This method is used to support rerunning + * single tests. + * @param clazz the class of the test + * @param methodName the name of the test + * @return a Request that will cause a single test be run + */ + /*public static Request method(Class clazz, String methodName) { + Description method= Description.createTestDescription(clazz, methodName); + return Request.aClass(clazz).filterWith(method); + }*/ + + /** + * Create a Request that, when processed, will run all the tests + * in a class. The odd name is necessary because class is a reserved word. + * @param clazz the class containing the tests + * @return a Request that will cause all tests in the class to be run + */ + public static Request aClass(Class clazz) { + return new ClassRequest(clazz); + } + + /** + * Create a Request that, when processed, will run all the tests + * in a set of classes. + * @param collectionName a name to identify this suite of tests + * @param classes the classes containing the tests + * @return a Request that will cause all tests in the classes to be run + */ + /*public static Request classes(String collectionName, Class... classes) { + return new ClassesRequest(collectionName, classes); + }*/ + + /*public static Request errorReport(Class klass, Throwable cause) { + return new ErrorReportingRequest(klass, cause); + }*/ + + public abstract Runner getRunner(); + + /*public Request filterWith(Filter filter) { + return new FilterRequest(this, filter); + } + + public Request filterWith(final Description desiredDescription) { + return filterWith(new Filter() { + @Override + public boolean shouldRun(Description description) { + // TODO: test for equality even if we have children? + if (description.isTest()) + return desiredDescription.equals(description); + for (Description each : description.getChildren()) + if (shouldRun(each)) + return true; + return false; + } + + @Override + public String describe() { + return String.format("Method %s", desiredDescription.getDisplayName()); + } + }); + } + + public Request sortWith(Comparator comparator) { + return new SortingRequest(this, comparator); + }*/ +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Result.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Result.java new file mode 100644 index 0000000000..591d083f71 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Result.java @@ -0,0 +1,98 @@ +package org.litejunit.v3.runner; + +import java.util.ArrayList; +import java.util.List; + +import org.litejunit.v3.notification.Failure; +import org.litejunit.v3.notification.RunListener; + + +/** + * A Result collects and summarizes information from running multiple + * tests. Since tests are expected to run correctly, successful tests are only noted in + * the count of tests that ran. + */ +public class Result { + private int fCount= 0; + private int fIgnoreCount= 0; + private List fFailures= new ArrayList(); + private long fRunTime= 0; + private long fStartTime; + + /** + * @return the number of tests run + */ + public int getRunCount() { + return fCount; + } + + /** + * @return the number of tests that failed during the run + */ + public int getFailureCount() { + return fFailures.size(); + } + + /** + * @return the number of milliseconds it took to run the entire suite to run + */ + public long getRunTime() { + return fRunTime; + } + + /** + * @return the Failures describing tests that failed and the problems they encountered + */ + public List getFailures() { + return fFailures; + } + + /** + * @return the number of tests ignored during the run + */ + public int getIgnoreCount() { + return fIgnoreCount; + } + + /** + * @return true if all tests succeeded + */ + public boolean wasSuccessful() { + return getFailureCount() == 0; + } + + private class Listener extends RunListener { + @Override + public void testRunStarted(Description description) throws Exception { + fStartTime= System.currentTimeMillis(); + } + + @Override + public void testRunFinished(Result result) throws Exception { + long endTime= System.currentTimeMillis(); + fRunTime+= endTime - fStartTime; + } + + @Override + public void testStarted(Description description) throws Exception { + fCount++; + } + + @Override + public void testFailure(Failure failure) throws Exception { + fFailures.add(failure); + } + + @Override + public void testIgnored(Description description) throws Exception { + fIgnoreCount++; + } + } + + /** + * Internal use only. + */ + public RunListener createListener() { + return new Listener(); + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/ResultPrinter.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/ResultPrinter.java new file mode 100644 index 0000000000..de8a41717c --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/ResultPrinter.java @@ -0,0 +1,72 @@ +package org.litejunit.v3.runner; + +import java.io.PrintStream; +import java.text.NumberFormat; + +import org.litejunit.v3.notification.Failure; + +public class ResultPrinter { + + private final PrintStream fWriter; + + public ResultPrinter(){ + fWriter = System.out; + } + + public void print(Result result) { + printHeader(result.getRunTime()); + printFailures(result); + printFooter(result); + } + protected void printHeader(long runTime) { + getWriter().println(); + getWriter().println("Time: " + elapsedTimeAsString(runTime)); + } + + protected void printFailures(Result result) { + if (result.getFailureCount() == 0) + return; + if (result.getFailureCount() == 1) + getWriter().println("There was " + result.getFailureCount() + " failure:"); + else + getWriter().println("There were " + result.getFailureCount() + " failures:"); + int i= 1; + for (Failure each : result.getFailures()) + printFailure(each, i++); + } + + protected void printFailure(Failure failure, int count) { + printFailureHeader(failure, count); + printFailureTrace(failure); + } + + protected void printFailureHeader(Failure failure, int count) { + getWriter().println(count + ") " + failure.getTestHeader()); + } + + protected void printFailureTrace(Failure failure) { + getWriter().print(failure.getTrace()); + } + + protected void printFooter(Result result) { + if (result.wasSuccessful()) { + getWriter().println(); + getWriter().print("OK"); + getWriter().println(" (" + result.getRunCount() + " test" + (result.getRunCount() == 1 ? "" : "s") + ")"); + + } else { + getWriter().println(); + getWriter().println("FAILURES!!!"); + getWriter().println("Tests run: " + result.getRunCount() + ", Failures: " + result.getFailureCount()); + } + getWriter().println(); + } + protected String elapsedTimeAsString(long runTime) { + return NumberFormat.getInstance().format((double) runTime / 1000); + } + private PrintStream getWriter() { + return fWriter; + } + + +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/RunWith.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/RunWith.java new file mode 100644 index 0000000000..c8ed3d4ff5 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/RunWith.java @@ -0,0 +1,24 @@ +package org.litejunit.v3.runner; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +//TODO add simple exampel +/** + * When you annotate a class with @RunWith, JUnit will invoke + * the class it references to run the tests in that class instead of the runner + * built into JUnit. We added this feature late in development. While it + * seems powerful we expect the runner API to change as we learn how people + * really use it. Some of the classes that are currently internal will likely be refined + * and become public. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface RunWith { + /** + * @return a Runner class (must have a constructor that takes a single Class to run) + */ + Class value(); +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Runner.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Runner.java new file mode 100644 index 0000000000..57ef0faf97 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Runner.java @@ -0,0 +1,24 @@ +package org.litejunit.v3.runner; + +import org.litejunit.v3.notification.RunNotifier; + + +public abstract class Runner { + /** + * @return a Description showing the tests to be run by the receiver + */ + public abstract Description getDescription(); + + /** + * Run the tests for this runner. + * @param notifier will be notified of events while tests are being run--tests being started, finishing, and failing + */ + public abstract void run(RunNotifier notifier); + + /** + * @return the number of tests to be run by the receiver + */ + public int testCount() { + return getDescription().testCount(); + } +} \ No newline at end of file diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/BeforeAndAfterRunner.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/BeforeAndAfterRunner.java new file mode 100644 index 0000000000..1bcbf40d79 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/BeforeAndAfterRunner.java @@ -0,0 +1,76 @@ +package org.litejunit.v3.runners; + +import java.lang.annotation.Annotation; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; + +public abstract class BeforeAndAfterRunner { + private static class FailedBefore extends Exception { + private static final long serialVersionUID= 1L; + } + + private final Class beforeAnnotation; + + private final Class afterAnnotation; + + private TestIntrospector testIntrospector; + + private Object test; + + public BeforeAndAfterRunner(Class testClass, + Class beforeAnnotation, + Class afterAnnotation, + Object test) { + this.beforeAnnotation= beforeAnnotation; + this.afterAnnotation= afterAnnotation; + this.testIntrospector= new TestIntrospector(testClass); + this.test= test; + } + + public void runProtected() { + try { + runBefores(); + runUnprotected(); + } catch (FailedBefore e) { + } finally { + runAfters(); + } + } + + protected abstract void runUnprotected(); + + protected abstract void addFailure(Throwable targetException); + + // Stop after first failed @Before + private void runBefores() throws FailedBefore { + try { + List befores= testIntrospector.getTestMethods(beforeAnnotation); + for (Method before : befores) + invokeMethod(before); + } catch (InvocationTargetException e) { + addFailure(e.getTargetException()); + throw new FailedBefore(); + } catch (Throwable e) { + addFailure(e); + throw new FailedBefore(); + } + } + + // Try to run all @Afters regardless + private void runAfters() { + List afters= testIntrospector.getTestMethods(afterAnnotation); + for (Method after : afters) + try { + invokeMethod(after); + } catch (InvocationTargetException e) { + addFailure(e.getTargetException()); + } catch (Throwable e) { + addFailure(e); // Untested, but seems impossible + } + } + + private void invokeMethod(Method method) throws Exception { + method.invoke(test); + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/InitializationError.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/InitializationError.java new file mode 100644 index 0000000000..76e21d02e4 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/InitializationError.java @@ -0,0 +1,25 @@ +package org.litejunit.v3.runners; + +import java.util.Arrays; +import java.util.List; + +public class InitializationError extends Exception { + private static final long serialVersionUID= 1L; + private final List fErrors; + + public InitializationError(List errors) { + fErrors= errors; + } + + public InitializationError(Throwable... errors) { + this(Arrays.asList(errors)); + } + + public InitializationError(String string) { + this(new Exception(string)); + } + + public List getCauses() { + return fErrors; + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/TestClassMethodsRunner.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/TestClassMethodsRunner.java new file mode 100644 index 0000000000..adf3b9c40d --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/TestClassMethodsRunner.java @@ -0,0 +1,100 @@ +package org.litejunit.v3.runners; + +import java.lang.reflect.Method; +import java.util.List; + +import org.litejunit.v3.Test; +import org.litejunit.v3.notification.Failure; +import org.litejunit.v3.notification.RunNotifier; +import org.litejunit.v3.runner.Description; +import org.litejunit.v3.runner.Runner; + + + +public class TestClassMethodsRunner extends Runner { + private final List testMethods; + private final Class testClass; + + public TestClassMethodsRunner(Class klass) { + testClass= klass; + testMethods= new TestIntrospector(testClass).getTestMethods(Test.class); + } + + @Override + public void run(RunNotifier notifier) { + /*if (testMethods.isEmpty()) + testAborted(notifier, getDescription());*/ + for (Method method : testMethods) + invokeTestMethod(method, notifier); + } + + /*private void testAborted(RunNotifier notifier, Description description) { + // TODO: duped! + // TODO: envious + notifier.fireTestStarted(description); + notifier.fireTestFailure(new Failure(description, new Exception("No runnable methods"))); + notifier.fireTestFinished(description); + }*/ + + @Override + public Description getDescription() { + Description spec= Description.createSuiteDescription(getName()); + List testMethods= this.testMethods; + for (Method method : testMethods) + spec.addChild(methodDescription(method)); + return spec; + } + + protected String getName() { + return getTestClass().getName(); + } + + protected Object createTest() throws Exception { + return getTestClass().getConstructor().newInstance(); + } + + protected void invokeTestMethod(Method method, RunNotifier notifier) { + Object test; + try { + test= createTest(); + } catch (Exception e) { + //testAborted(notifier, methodDescription(method)); + return; + } + createMethodRunner(test, method, notifier).run(); + } + + protected TestMethodRunner createMethodRunner(Object test, Method method, RunNotifier notifier) { + return new TestMethodRunner(test, method, notifier, methodDescription(method)); + } + + protected String testName(Method method) { + return method.getName(); + } + + protected Description methodDescription(Method method) { + return Description.createTestDescription(getTestClass(), testName(method)); + } + + /*public void filter(Filter filter) throws NoTestsRemainException { + for (Iterator iter= fTestMethods.iterator(); iter.hasNext();) { + Method method= (Method) iter.next(); + if (!filter.shouldRun(methodDescription(method))) + iter.remove(); + } + if (fTestMethods.isEmpty()) + throw new NoTestsRemainException(); + } + + public void sort(final Sorter sorter) { + Collections.sort(fTestMethods, new Comparator() { + public int compare(Method o1, Method o2) { + return sorter.compare(methodDescription(o1), methodDescription(o2)); + } + }); + }*/ + + protected Class getTestClass() { + return testClass; + } +} \ No newline at end of file diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/TestClassRunner.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/TestClassRunner.java new file mode 100644 index 0000000000..84c2a072ef --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/TestClassRunner.java @@ -0,0 +1,53 @@ +package org.litejunit.v3.runners; + +import org.litejunit.v3.AfterClass; +import org.litejunit.v3.BeforeClass; +import org.litejunit.v3.notification.Failure; +import org.litejunit.v3.notification.RunNotifier; +import org.litejunit.v3.runner.Description; +import org.litejunit.v3.runner.Runner; + +public class TestClassRunner extends Runner { + protected final Runner enclosedRunner; + private final Class testClass; + + public TestClassRunner(Class klass) throws InitializationError { + this(klass, new TestClassMethodsRunner(klass)); + } + + public TestClassRunner(Class klass, Runner runner) throws InitializationError { + testClass= klass; + enclosedRunner= runner; + + } + + + + @Override + public void run(final RunNotifier notifier) { + BeforeAndAfterRunner runner = new BeforeAndAfterRunner(getTestClass(), + BeforeClass.class, AfterClass.class, null) { + @Override + protected void runUnprotected() { + enclosedRunner.run(notifier); + } + + // TODO: looks very similar to other method of BeforeAfter, now + @Override + protected void addFailure(Throwable targetException) { + notifier.fireTestFailure(new Failure(getDescription(), targetException)); + } + }; + + runner.runProtected(); + } + + @Override + public Description getDescription() { + return enclosedRunner.getDescription(); + } + + protected Class getTestClass() { + return testClass; + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/TestIntrospector.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/TestIntrospector.java new file mode 100644 index 0000000000..1dda424d7f --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/TestIntrospector.java @@ -0,0 +1,82 @@ +package org.litejunit.v3.runners; + + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.litejunit.v3.Before; +import org.litejunit.v3.BeforeClass; +import org.litejunit.v3.Ignore; +import org.litejunit.v3.Test; +import org.litejunit.v3.Test.None; + + + +public class TestIntrospector { + private final Class< ?> testClass; + + public TestIntrospector(Class testClass) { + this.testClass= testClass; + } + + public List getTestMethods(Class annotationClass) { + List results= new ArrayList(); + + //for (Class eachClass : getSuperClasses(testClass)) { + Method[] methods= testClass.getDeclaredMethods(); + for (Method method : methods) { + Annotation annotation= method.getAnnotation(annotationClass); + if (annotation != null && ! isShadowed(method, results)) + results.add(method); + } + //} + if (runsTopToBottom(annotationClass)) + Collections.reverse(results); + return results; + } + + public boolean isIgnored(Method eachMethod) { + return eachMethod.getAnnotation(Ignore.class) != null; + } + + private boolean runsTopToBottom(Class< ? extends Annotation> annotation) { + return annotation.equals(Before.class) || annotation.equals(BeforeClass.class); + } + + private boolean isShadowed(Method method, List results) { + for (Method m : results) { + if (m.getName().equals(method.getName())) + return true; + } + return false; + } + + /*private List getSuperClasses(Class< ?> testClass) { + ArrayList results= new ArrayList(); + Class current= testClass; + while (current != null) { + results.add(current); + current= current.getSuperclass(); + } + return results; + }*/ + + long getTimeout(Method method) { + Test annotation= method.getAnnotation(Test.class); + long timeout= annotation.timeout(); + return timeout; + } + + Class expectedException(Method method) { + Test annotation= method.getAnnotation(Test.class); + if (annotation.expected() == None.class) + return null; + else + return annotation.expected(); + } + +} + diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/TestMethodRunner.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/TestMethodRunner.java new file mode 100644 index 0000000000..7034a4c812 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/TestMethodRunner.java @@ -0,0 +1,122 @@ +package org.litejunit.v3.runners; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import org.litejunit.v3.After; +import org.litejunit.v3.Before; +import org.litejunit.v3.notification.Failure; +import org.litejunit.v3.notification.RunNotifier; +import org.litejunit.v3.runner.Description; + + + +public class TestMethodRunner extends BeforeAndAfterRunner { + private final Object test; + private final Method method; + private final RunNotifier notifier; + private final TestIntrospector testIntrospector; + private final Description description; + + public TestMethodRunner(Object test, Method method, RunNotifier notifier, Description description) { + super(test.getClass(), Before.class, After.class, test); + this.test= test; + this.method= method; + this.notifier= notifier; + testIntrospector= new TestIntrospector(test.getClass()); + this.description= description; + } + + public void run() { + /*if (testIntrospector.isIgnored(method)) { + notifier.fireTestIgnored(description); + return; + }*/ + notifier.fireTestStarted(description); + try { + /*long timeout= testIntrospector.getTimeout(method); + if (timeout > 0) + runWithTimeout(timeout); + else*/ + runMethod(); + } finally { + notifier.fireTestFinished(description); + } + } + + /*private void runWithTimeout(long timeout) { + ExecutorService service= Executors.newSingleThreadExecutor(); + Callable callable= new Callable() { + public Object call() throws Exception { + runMethod(); + return null; + } + }; + Future result= service.submit(callable); + service.shutdown(); + try { + boolean terminated= service.awaitTermination(timeout, + TimeUnit.MILLISECONDS); + if (!terminated) + service.shutdownNow(); + result.get(timeout, TimeUnit.MILLISECONDS); // throws the exception if one occurred during the invocation + } catch (TimeoutException e) { + addFailure(new Exception(String.format("test timed out after %d milliseconds", timeout))); + } catch (Exception e) { + addFailure(e); + } + }*/ + + private void runMethod() { + runProtected(); + } + + @Override + protected void runUnprotected() { + try { + executeMethodBody(); + /*if (expectsException()) + addFailure(new AssertionError("Expected exception: " + expectedException().getName()));*/ + } catch (InvocationTargetException e) { + addFailure(e); + /*Throwable actual= e.getTargetException(); + if (!expectsException()) + addFailure(actual); + else if (isUnexpected(actual)) { + String message= "Unexpected exception, expected<" + expectedException().getName() + "> but was<" + + actual.getClass().getName() + ">"; + addFailure(new Exception(message, actual)); + }*/ + } catch (Throwable e) { + addFailure(e); + } + } + + protected void executeMethodBody() throws IllegalAccessException, InvocationTargetException { + method.invoke(test); + } + + @Override + protected void addFailure(Throwable e) { + notifier.fireTestFailure(new Failure(description, e)); + } + + /*private boolean expectsException() { + return expectedException() != null; + } + + private Class expectedException() { + return testIntrospector.expectedException(method); + }*/ + + /*private boolean isUnexpected(Throwable exception) { + return ! expectedException().isAssignableFrom(exception.getClass()); + }*/ +} + diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/TextListener.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/TextListener.java new file mode 100644 index 0000000000..53cab12ad2 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/TextListener.java @@ -0,0 +1,106 @@ +package org.litejunit.v3.runners; + +import java.io.PrintStream; +import java.text.NumberFormat; + +import org.litejunit.v3.notification.Failure; +import org.litejunit.v3.notification.RunListener; +import org.litejunit.v3.runner.Description; +import org.litejunit.v3.runner.Result; + + + +public class TextListener extends RunListener { + + private final PrintStream writer; + + public TextListener() { + this(System.out); + } + + public TextListener(PrintStream writer) { + this.writer= writer; + } + + @Override + public void testRunFinished(Result result) { + printHeader(result.getRunTime()); + printFailures(result); + printFooter(result); + } + + @Override + public void testStarted(Description description) { + writer.append('.'); + } + + @Override + public void testFailure(Failure failure) { + writer.append('E'); + } + + @Override + public void testIgnored(Description description) { + writer.append('I'); + } + + /* + * Internal methods + */ + + private PrintStream getWriter() { + return writer; + } + + protected void printHeader(long runTime) { + getWriter().println(); + getWriter().println("Time: " + elapsedTimeAsString(runTime)); + } + + protected void printFailures(Result result) { + if (result.getFailureCount() == 0) + return; + if (result.getFailureCount() == 1) + getWriter().println("There was " + result.getFailureCount() + " failure:"); + else + getWriter().println("There were " + result.getFailureCount() + " failures:"); + int i= 1; + for (Failure each : result.getFailures()) + printFailure(each, i++); + } + + protected void printFailure(Failure failure, int count) { + printFailureHeader(failure, count); + printFailureTrace(failure); + } + + protected void printFailureHeader(Failure failure, int count) { + getWriter().println(count + ") " + failure.getTestHeader()); + } + + protected void printFailureTrace(Failure failure) { + getWriter().print(failure.getTrace()); + } + + protected void printFooter(Result result) { + if (result.wasSuccessful()) { + getWriter().println(); + getWriter().print("OK"); + getWriter().println(" (" + result.getRunCount() + " test" + (result.getRunCount() == 1 ? "" : "s") + ")"); + + } else { + getWriter().println(); + getWriter().println("FAILURES!!!"); + getWriter().println("Tests run: " + result.getRunCount() + ", Failures: " + result.getFailureCount()); + } + getWriter().println(); + } + + /** + * Returns the formatted string of the elapsed time. Duplicated from + * BaseTestRunner. Fix it. + */ + protected String elapsedTimeAsString(long runTime) { + return NumberFormat.getInstance().format((double) runTime / 1000); + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/sample/Calculator.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/sample/Calculator.java new file mode 100644 index 0000000000..eaf42c77a6 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/sample/Calculator.java @@ -0,0 +1,22 @@ +package org.litejunit.v3.sample; + +public class Calculator { + + private int result = 0; + public void add(int x){ + result += x; + } + public void subtract(int x){ + result -=x; + } + + public int getResult(){ + return this.result; + } + public static void main(String[] args){ + Calculator calculator = new Calculator(); + calculator.add(10); + calculator.subtract(5); + System.out.println(calculator.getResult()); + } +} diff --git a/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/sample/CalculatorTest.java b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/sample/CalculatorTest.java new file mode 100644 index 0000000000..cae2673ac2 --- /dev/null +++ b/liuxin/ood/ood-assignment/src/main/java/org/litejunit/v3/sample/CalculatorTest.java @@ -0,0 +1,48 @@ +package org.litejunit.v3.sample; + +import org.litejunit.v3.After; +import org.litejunit.v3.AfterClass; +import org.litejunit.v3.Before; +import org.litejunit.v3.BeforeClass; +import org.litejunit.v3.Test; +import org.litejunit.v3.runner.JUnitCore; +import static org.litejunit.v3.Assert.*; + +public class CalculatorTest { + + Calculator calculator =null; + @Before + public void prepare(){ + calculator = new Calculator(); + } + @After + public void clean(){ + calculator = null; + } + @Test + public void testAdd(){ + + calculator.add(10); + assertEquals(15,calculator.getResult()); + } + @Test + public void testSubtract(){ + calculator.add(10); + calculator.subtract(5); + assertEquals(5,calculator.getResult()); + } + @BeforeClass + public static void prepareGlobalResouce(){ + System.err.println("prepare global resource"); + } + @AfterClass + public static void cleanGlobalResouce(){ + System.err.println("clean global resource"); + } + + + public static void main(String[] args){ + JUnitCore.runClass(CalculatorTest.class); + + } +} diff --git a/students/1049843090/ood/build.gradle b/students/1049843090/ood/build.gradle new file mode 100644 index 0000000000..adca958b35 --- /dev/null +++ b/students/1049843090/ood/build.gradle @@ -0,0 +1,28 @@ +group 'com.yangdd' +version '1.0-SNAPSHOT' +description = '面向对象设计' + +apply plugin: 'java' + +sourceCompatibility = 1.8 + +repositories { + mavenLocal() + mavenCentral() +} + +//项目布局,下面是Java plugin的默认布局 +sourceSets { + main.java.srcDir('src/main/java') + main.resources.srcDir('src/main/resources') + test.java.srcDir('src/test/java') + test.resources.srcDir('src/test/resources') +} + +dependencies { + testCompile('junit:junit:4.12') +} + +tasks.withType(JavaCompile) { + options.encoding = 'UTF-8' +} \ No newline at end of file diff --git a/students/1049843090/ood/settings.gradle b/students/1049843090/ood/settings.gradle new file mode 100644 index 0000000000..4ffc61b06a --- /dev/null +++ b/students/1049843090/ood/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'ood' + diff --git a/students/1049843090/ood/src/main/java/com/coderising/ood/srp/Configuration.java b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..70759b547a --- /dev/null +++ b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} \ No newline at end of file diff --git a/students/1049843090/ood/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..c57f37c4ce --- /dev/null +++ b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} \ No newline at end of file diff --git a/students/1049843090/ood/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..27b3f180a7 --- /dev/null +++ b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,46 @@ +package com.coderising.ood.srp; + +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Random; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * + * @param sql + * @return + */ + public static List query(String sql) { + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } + + + public static List querySubscriber(String productId) { + + List list = new ArrayList<>(); + + Random random = new Random(); + int number = random.nextInt(3); + + for (int i = 1; i <= number; i++) { + UserInfo userInfo = new UserInfo(); + userInfo.setName("User" + productId + i); + userInfo.setMail(userInfo.getName() + "@" + productId + ".com"); + list.add(userInfo); + } + return list; + } +} \ No newline at end of file diff --git a/students/1049843090/ood/src/main/java/com/coderising/ood/srp/MailData.java b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/MailData.java new file mode 100644 index 0000000000..6bcf25cc99 --- /dev/null +++ b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/MailData.java @@ -0,0 +1,73 @@ +package com.coderising.ood.srp; + +/** + * 邮件数据 + * + * @author yangdd + */ +public class MailData { + + protected String smtpHost; + protected String altSmtpHost; + protected String fromAddress; + protected String toAddress; + protected String subject; + protected String message; + private boolean debug; + + public String getSmtpHost() { + return smtpHost; + } + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public boolean isDebug() { + return debug; + } + + public void setDebug(boolean debug) { + this.debug = debug; + } +} diff --git a/students/1049843090/ood/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..9948734ff5 --- /dev/null +++ b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,45 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + + public static void sendEmail(MailData mailData) { + //假装发了一封邮件 + try { + StringBuilder buffer = new StringBuilder(); + buffer.append("Smtp:").append(mailData.getSmtpHost()).append("\n"); + buffer.append("From:").append(mailData.getFromAddress()).append("\n"); + buffer.append("To:").append(mailData.getToAddress()).append("\n"); + buffer.append("Subject:").append(mailData.getSubject()).append("\n"); + buffer.append("Content:").append(mailData.getMessage()).append("\n"); + System.out.println(buffer.toString()); + } catch (Exception e) { + try { + StringBuilder buffer = new StringBuilder(); + buffer.append("Smtp:").append(mailData.getAltSmtpHost()).append("\n"); + buffer.append("From:").append(mailData.getFromAddress()).append("\n"); + buffer.append("To:").append(mailData.getToAddress()).append("\n"); + buffer.append("Subject:").append(mailData.getSubject()).append("\n"); + buffer.append("Content:").append(mailData.getMessage()).append("\n"); + System.out.println(buffer.toString()); + } catch (Exception e1) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e1.getMessage()); + } + } + + + } + +} \ No newline at end of file diff --git a/students/1049843090/ood/src/main/java/com/coderising/ood/srp/ProductInfo.java b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/ProductInfo.java new file mode 100644 index 0000000000..c699da54a1 --- /dev/null +++ b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/ProductInfo.java @@ -0,0 +1,33 @@ +package com.coderising.ood.srp; + +import java.util.List; + +/** + * 产品信息 + * + * @author yangdd + */ +public class ProductInfo { + + private String id; + + private String description; + + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + +} diff --git a/students/1049843090/ood/src/main/java/com/coderising/ood/srp/ProductInfoService.java b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/ProductInfoService.java new file mode 100644 index 0000000000..5f91b05c36 --- /dev/null +++ b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/ProductInfoService.java @@ -0,0 +1,38 @@ +package com.coderising.ood.srp; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; + +/** + * @author yangdd + */ +public class ProductInfoService { + + public List getPromotionProducts() { + List list = new ArrayList<>(); + //可以抽取出一个读取文件的Util + BufferedReader br = null; + try { + String path = "/Users/yangdd/Documents/code/GitHub/coding2017-Q2/students/1049843090/ood/src/main/java/com/coderising/ood/srp/product_promotion.txt"; + File file = new File(path); + br = new BufferedReader(new FileReader(file)); + String temp = null; + String[] data = null; + while ((temp = br.readLine()) != null) { + data = temp.split(" "); + ProductInfo productInfo = new ProductInfo(); + productInfo.setId(data[0]); + productInfo.setDescription(data[1]); + list.add(productInfo); + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + return list; + } + +} diff --git a/students/1049843090/ood/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..d8accbd797 --- /dev/null +++ b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,58 @@ +package com.coderising.ood.srp; + +import java.util.List; + +public class PromotionMail { + + + public static void main(String[] args) throws Exception { + new PromotionMail().sendEMails(); + + } + + + private void setMessage(ProductInfo productInfo, UserInfo userInfo, MailData mailData) { + + + mailData.setSubject("您关注的产品降价了"); + String message = "尊敬的 " + userInfo.getName() + ", 您关注的产品 " + productInfo.getDescription() + " 降价了,欢迎购买!"; + mailData.setMessage(message); + + } + + + private void sendEMails() throws Exception { + ProductInfoService productInfoService = new ProductInfoService(); + UserInfoService userInfoService = new UserInfoService(); + List productInfos = productInfoService.getPromotionProducts(); + + System.out.println("开始发送邮件"); + MailData mailData = getMailData(); + productInfos.forEach(e -> { + List userInfos = userInfoService.getuserInfoByProduceId(e.getId()); + userInfos.forEach(userInfo -> { + if (userInfo.getMail().length() > 0) { + mailData.setToAddress(userInfo.getMail()); + setMessage(e, userInfo, mailData); + MailUtil.sendEmail(mailData); + } else { + System.out.println(userInfo.getName() + "邮件格式不正确"); + } + + }); + }); + + + } + + + private MailData getMailData() { + Configuration config = new Configuration(); + MailData mailData = new MailData(); + mailData.setSmtpHost(config.getProperty(ConfigurationKeys.SMTP_SERVER)); + mailData.setAltSmtpHost(config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER)); + mailData.setFromAddress(config.getProperty(ConfigurationKeys.EMAIL_ADMIN)); + return mailData; + } + +} \ No newline at end of file diff --git a/students/1049843090/ood/src/main/java/com/coderising/ood/srp/UserInfo.java b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/UserInfo.java new file mode 100644 index 0000000000..98b04b338e --- /dev/null +++ b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/UserInfo.java @@ -0,0 +1,29 @@ +package com.coderising.ood.srp; + +/** + * 用户信息 + * + * @author yangdd + */ +public class UserInfo { + + private String name; + + private String mail; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getMail() { + return mail; + } + + public void setMail(String mail) { + this.mail = mail; + } +} diff --git a/students/1049843090/ood/src/main/java/com/coderising/ood/srp/UserInfoService.java b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/UserInfoService.java new file mode 100644 index 0000000000..d320d41491 --- /dev/null +++ b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/UserInfoService.java @@ -0,0 +1,13 @@ +package com.coderising.ood.srp; + +import java.util.List; + +/** + * @author yangdd + */ +public class UserInfoService { + + public List getuserInfoByProduceId(String productId) { + return DBUtil.querySubscriber(productId); + } +} diff --git a/students/1049843090/ood/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/1049843090/ood/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/1058267830/newMail/src/com/coderising/ood/srp/Configuration.java b/students/1058267830/newMail/src/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f1fe384d94 --- /dev/null +++ b/students/1058267830/newMail/src/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,10 @@ +package com.coderising.ood.srp; + +public class Configuration { + + public static final String SMTP_SERVER = "smtp.163.com"; + public static final String ALT_SMTP_SERVER = "smtp1.163.com"; + public static final String EMAIL_ADMIN = "admin@company.com"; + public static final String PRODUCTS_FILE_PATH = "D:\\workspace\\design-pattern\\newMail\\src\\com\\coderising\\ood\\srp\\product_promotion.txt"; + +} diff --git a/students/1058267830/newMail/src/com/coderising/ood/srp/DBUtil.java b/students/1058267830/newMail/src/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..ec4dd0fddb --- /dev/null +++ b/students/1058267830/newMail/src/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +@SuppressWarnings("all") +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List queryUserList(String sql){ + + List userList = new ArrayList(); + + for (int i = 1; i <= 3; i++) { + User user = new User("User" + i, "aa@bb.com"); + userList.add(user); + } + + return userList; + } +} diff --git a/students/1058267830/newMail/src/com/coderising/ood/srp/MailUtil.java b/students/1058267830/newMail/src/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..77f7699825 --- /dev/null +++ b/students/1058267830/newMail/src/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,46 @@ +package com.coderising.ood.srp; + +import java.util.List; + +public class MailUtil { + + public static void sendEmail(List products, List users){ + + for(Product p : products){ + for(User u : users){ + sendEmailToUser(p, u); + } + } + + } + + private static void sendEmailToUser(Product product, User user) { + + String message = "尊敬的 "+user.getName()+", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!" ; + + String fromAddress = Configuration.EMAIL_ADMIN; + String subject = "您关注的产品降价了"; + String smtpHost = Configuration.SMTP_SERVER; + String altSmtpHost = Configuration.ALT_SMTP_SERVER; + + try{ + _sendEmailReal(user.getEmail(), fromAddress, subject, message, smtpHost, false); + }catch(Exception e){ + _sendEmailReal(user.getEmail(), fromAddress, subject, message, altSmtpHost, false); + } + + } + + private static void _sendEmailReal(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + +} diff --git a/students/1058267830/newMail/src/com/coderising/ood/srp/Product.java b/students/1058267830/newMail/src/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..4712c8f0ff --- /dev/null +++ b/students/1058267830/newMail/src/com/coderising/ood/srp/Product.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; + +public class Product { + + private String productId; + private String productDesc; + public Product(String productId, String productDesc) { + super(); + this.productId = productId; + this.productDesc = productDesc; + } + public String getProductId() { + return productId; + } + public void setProductId(String productId) { + this.productId = productId; + } + public String getProductDesc() { + return productDesc; + } + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + +} diff --git a/students/1058267830/newMail/src/com/coderising/ood/srp/ProductUtil.java b/students/1058267830/newMail/src/com/coderising/ood/srp/ProductUtil.java new file mode 100644 index 0000000000..d49f51dc51 --- /dev/null +++ b/students/1058267830/newMail/src/com/coderising/ood/srp/ProductUtil.java @@ -0,0 +1,34 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; + +@SuppressWarnings("all") +public class ProductUtil { + /** + * 得到促销产品列表,至于从哪里读取,由该方法内部决定,外部不需要知道 + * @throws IOException + */ + public static List getProducts() throws IOException{ + return readFile(new File(Configuration.PRODUCTS_FILE_PATH)); + } + + private static List readFile(File file) throws IOException { + List products = new ArrayList(); + FileInputStream fis = new FileInputStream(file); + BufferedReader br = new BufferedReader(new InputStreamReader(fis, "UTF-8")); + for( String line = br.readLine(); line != null; line = br.readLine() ){ + Product product = new Product(line.split(" ")[0], line.split(" ")[1]); + products.add(product); + } + + return products; + + } + +} diff --git a/students/1058267830/newMail/src/com/coderising/ood/srp/PromotionMail.java b/students/1058267830/newMail/src/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..0f6baa324e --- /dev/null +++ b/students/1058267830/newMail/src/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,32 @@ +package com.coderising.ood.srp; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class PromotionMail { + + public static void main(String[] args) { + + /** + * 整体步骤大概有3步: + * 1、读取配置文件,得到促销的商品列表 + * 2、调用DBUtil读取DB,得到订阅的用户列表 + * 3、调用MailUtil发送邮件 + */ + List products = new ArrayList(); + List users = new ArrayList(); + try { + + products = ProductUtil.getProducts(); + users = DBUtil.queryUserList("select *** from t_user"); + MailUtil.sendEmail(products, users); + + } catch (IOException e) { + e.printStackTrace(); + } + + + } + +} diff --git a/students/1058267830/newMail/src/com/coderising/ood/srp/User.java b/students/1058267830/newMail/src/com/coderising/ood/srp/User.java new file mode 100644 index 0000000000..6a7bc15952 --- /dev/null +++ b/students/1058267830/newMail/src/com/coderising/ood/srp/User.java @@ -0,0 +1,27 @@ +package com.coderising.ood.srp; + +public class User { + + private String name; + private String email; + + public User(String name, String email) { + super(); + this.name = name; + this.email = email; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + +} diff --git a/students/1058267830/newMail/src/com/coderising/ood/srp/product_promotion.txt b/students/1058267830/newMail/src/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/1058267830/newMail/src/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/1072760797/src/com/coderising/ood/ocp/DateUtil.java b/students/1072760797/src/com/coderising/ood/ocp/DateUtil.java new file mode 100644 index 0000000000..b6cf28c096 --- /dev/null +++ b/students/1072760797/src/com/coderising/ood/ocp/DateUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return null; + } + +} diff --git a/students/1072760797/src/com/coderising/ood/ocp/Logger.java b/students/1072760797/src/com/coderising/ood/ocp/Logger.java new file mode 100644 index 0000000000..b89d355fef --- /dev/null +++ b/students/1072760797/src/com/coderising/ood/ocp/Logger.java @@ -0,0 +1,17 @@ +package com.coderising.ood.ocp; + +public abstract class Logger { + + + public void log(String msg){ + + setMsg(msg); + + sendMsg(msg); + } + + public abstract void setMsg(String msg); + public abstract void sendMsg(String logMsg); + +} + diff --git a/students/1072760797/src/com/coderising/ood/ocp/MailUtil.java b/students/1072760797/src/com/coderising/ood/ocp/MailUtil.java new file mode 100644 index 0000000000..ec54b839c5 --- /dev/null +++ b/students/1072760797/src/com/coderising/ood/ocp/MailUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class MailUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/1072760797/src/com/coderising/ood/ocp/RAW_Logger.java b/students/1072760797/src/com/coderising/ood/ocp/RAW_Logger.java new file mode 100644 index 0000000000..c3e684e735 --- /dev/null +++ b/students/1072760797/src/com/coderising/ood/ocp/RAW_Logger.java @@ -0,0 +1,18 @@ +package com.coderising.ood.ocp; + +public class RAW_Logger extends Logger { + + @Override + public void setMsg(String msg) { + // TODO Auto-generated method stub + String logMsg = msg; + logMsg = msg; + } + + @Override + public void sendMsg(String logMsg) { + // TODO Auto-generated method stub + MailUtil.send(logMsg); + } + +} diff --git a/students/1072760797/src/com/coderising/ood/ocp/SMSUtil.java b/students/1072760797/src/com/coderising/ood/ocp/SMSUtil.java new file mode 100644 index 0000000000..13cf802418 --- /dev/null +++ b/students/1072760797/src/com/coderising/ood/ocp/SMSUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class SMSUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/1072760797/src/com/coderising/ood/ocp/good/Formatter.java b/students/1072760797/src/com/coderising/ood/ocp/good/Formatter.java new file mode 100644 index 0000000000..b6e2ccbc16 --- /dev/null +++ b/students/1072760797/src/com/coderising/ood/ocp/good/Formatter.java @@ -0,0 +1,7 @@ +package com.coderising.ood.ocp.good; + +public interface Formatter { + + String format(String msg); + +} diff --git a/students/1072760797/src/com/coderising/ood/ocp/good/FormatterFactory.java b/students/1072760797/src/com/coderising/ood/ocp/good/FormatterFactory.java new file mode 100644 index 0000000000..3c2009a674 --- /dev/null +++ b/students/1072760797/src/com/coderising/ood/ocp/good/FormatterFactory.java @@ -0,0 +1,13 @@ +package com.coderising.ood.ocp.good; + +public class FormatterFactory { + public static Formatter createFormatter(int type){ + if(type == 1){ + return new RawFormatter(); + } + if (type == 2){ + return new HtmlFormatter(); + } + return null; + } +} diff --git a/students/1072760797/src/com/coderising/ood/ocp/good/HtmlFormatter.java b/students/1072760797/src/com/coderising/ood/ocp/good/HtmlFormatter.java new file mode 100644 index 0000000000..3d375f5acc --- /dev/null +++ b/students/1072760797/src/com/coderising/ood/ocp/good/HtmlFormatter.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp.good; + +public class HtmlFormatter implements Formatter { + + @Override + public String format(String msg) { + + return null; + } + +} diff --git a/students/1072760797/src/com/coderising/ood/ocp/good/Logger.java b/students/1072760797/src/com/coderising/ood/ocp/good/Logger.java new file mode 100644 index 0000000000..f206472d0d --- /dev/null +++ b/students/1072760797/src/com/coderising/ood/ocp/good/Logger.java @@ -0,0 +1,18 @@ +package com.coderising.ood.ocp.good; + +public class Logger { + + private Formatter formatter; + private Sender sender; + + public Logger(Formatter formatter,Sender sender){ + this.formatter = formatter; + this.sender = sender; + } + public void log(String msg){ + sender.send(formatter.format(msg)) ; + } + + +} + diff --git a/students/1072760797/src/com/coderising/ood/ocp/good/RawFormatter.java b/students/1072760797/src/com/coderising/ood/ocp/good/RawFormatter.java new file mode 100644 index 0000000000..7f1cb4ae30 --- /dev/null +++ b/students/1072760797/src/com/coderising/ood/ocp/good/RawFormatter.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp.good; + +public class RawFormatter implements Formatter { + + @Override + public String format(String msg) { + + return null; + } + +} diff --git a/students/1072760797/src/com/coderising/ood/ocp/good/Sender.java b/students/1072760797/src/com/coderising/ood/ocp/good/Sender.java new file mode 100644 index 0000000000..aaa46c1fb7 --- /dev/null +++ b/students/1072760797/src/com/coderising/ood/ocp/good/Sender.java @@ -0,0 +1,7 @@ +package com.coderising.ood.ocp.good; + +public interface Sender { + + void send(String msg); + +} diff --git a/students/1072760797/src/com/coderising/ood/srp/Configuration.java b/students/1072760797/src/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..c458c8774a --- /dev/null +++ b/students/1072760797/src/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,58 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + private static Map configurations = new HashMap<>(); + private static String smtpHost; + private static String altSmtpHost; + private static String fromAddress; + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public Configuration(){ + setSMTPHost(); + setAltSMTPHost(); + setFromAddress(); + } + public String getProperty(String key) { + + return configurations.get(key); + } + + protected void setSMTPHost() + { + smtpHost = this.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + protected void setAltSMTPHost() + { + altSmtpHost = this.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + protected void setFromAddress() + { + fromAddress = this.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + public static String getSmtpHost() { + return smtpHost; + } + public static String getAltSmtpHost() { + return altSmtpHost; + } + public static String getFromAddress() { + return fromAddress; + } + + +} diff --git a/students/1072760797/src/com/coderising/ood/srp/ConfigurationKeys.java b/students/1072760797/src/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/1072760797/src/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/1072760797/src/com/coderising/ood/srp/ConfigureEmail.java b/students/1072760797/src/com/coderising/ood/srp/ConfigureEmail.java new file mode 100644 index 0000000000..87af1e42db --- /dev/null +++ b/students/1072760797/src/com/coderising/ood/srp/ConfigureEmail.java @@ -0,0 +1,58 @@ +package com.coderising.ood.srp; + +import java.io.IOException; +import java.util.HashMap; + +public class ConfigureEmail { + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + private Configuration config = null; + private EmailBean email = new EmailBean(); + private Product product; + + private String message; + private String subject; + private String toAddress; + + public ConfigureEmail(Configuration config, Product product, + HashMap userInfo) { + + this.config = config; + this.product = product; + + setMessage(userInfo); + setToAddress(userInfo); + + setBean(); + + } + + private void setBean() { + + email.setFromAddress(config.getFromAddress()); + email.setMessage(message); + email.setSmtpHost(config.getSmtpHost()); + email.setSubject(subject); + email.setToAddress(toAddress); + } + + public EmailBean getEmail() { + return email; + } + + public void setMessage(HashMap userInfo) { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 " + name + ", 您关注的产品 " + product.getProductDesc() + + " 降价了,欢迎购买!"; + } + + protected void setToAddress(HashMap userInfo) { + toAddress = (String) userInfo.get(EMAIL_KEY); + } + +} diff --git a/students/1072760797/src/com/coderising/ood/srp/DBUtil.java b/students/1072760797/src/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..7597905da1 --- /dev/null +++ b/students/1072760797/src/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,27 @@ +package com.coderising.ood.srp; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * + * @param sql + * @return + */ + public static List query(String sql) { + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/1072760797/src/com/coderising/ood/srp/EmailBean.java b/students/1072760797/src/com/coderising/ood/srp/EmailBean.java new file mode 100644 index 0000000000..d5923b9f28 --- /dev/null +++ b/students/1072760797/src/com/coderising/ood/srp/EmailBean.java @@ -0,0 +1,50 @@ +package com.coderising.ood.srp; + +public class EmailBean { + private String toAddress; + private String fromAddress; + private String subject; + private String message; + private String smtpHost; + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getSmtpHost() { + return smtpHost; + } + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + +} diff --git a/students/1072760797/src/com/coderising/ood/srp/MailUtil.java b/students/1072760797/src/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..508a11f3d8 --- /dev/null +++ b/students/1072760797/src/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,24 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, + String subject, String message, String smtpHost, boolean debug) { + // 假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + public static void sendEmail(EmailBean email, boolean debug) { + // TODO Auto-generated method stub + sendEmail(email.getToAddress(), email.getFromAddress(), + email.getSubject(), email.getMessage(), email.getSmtpHost(), + debug); + } + +} diff --git a/students/1072760797/src/com/coderising/ood/srp/MailingDao.java b/students/1072760797/src/com/coderising/ood/srp/MailingDao.java new file mode 100644 index 0000000000..cb5924f604 --- /dev/null +++ b/students/1072760797/src/com/coderising/ood/srp/MailingDao.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; + +import java.util.List; + +public class MailingDao { + + private String sendMailQuery; + public List getQuery(String productID) throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + + return loadMailingList(); + } + + private List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } +} diff --git a/students/1072760797/src/com/coderising/ood/srp/Product.java b/students/1072760797/src/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..7b5abd3c88 --- /dev/null +++ b/students/1072760797/src/com/coderising/ood/srp/Product.java @@ -0,0 +1,62 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +public class Product { + + private File file = null; + private String productID; + private String productDesc; + public Product(){} + public Product(File file) throws IOException{ + this.file = file; + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + } + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + public void setFile(File file) throws IOException { + this.file = file; + readFile(file); + } + public String getProductID() { + if(productID.isEmpty()){ + throw new RuntimeException("no productID"); + } + return productID; + } + public void setProductID(String productID) { + this.productID = productID; + } + public String getProductDesc() { + if(productDesc.isEmpty()){ + throw new RuntimeException("no productDesc"); + } + return productDesc; + } + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git a/students/1072760797/src/com/coderising/ood/srp/PromotionMail.java b/students/1072760797/src/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..b2713840e0 --- /dev/null +++ b/students/1072760797/src/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,77 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + List mailingList = null; + private static Configuration config; + + private Product product = null; + + public static void main(String[] args) throws Exception { + File f = new File("src/com/coderising/ood/srp/product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + init(file, mailDebug); + + } + + private void init(File file, boolean mailDebug) throws Exception { + product = new Product(file); + config = new Configuration(); + MailingDao dao = new MailingDao(); + mailingList = dao.getQuery(product.getProductID()); + + sendEMails(mailDebug, mailingList); + + } + + protected void sendEMails(boolean debug, List mailingList) + throws IOException { + + System.out.println("开始发送邮件"); + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + ConfigureEmail ce = new ConfigureEmail(config, product, + (HashMap) iter.next()); + EmailBean email = ce.getEmail(); + try { + if (email.getToAddress().length() > 0) + MailUtil.sendEmail(email, debug); + } catch (Exception e) { + + try { + MailUtil.sendEmail(email, debug); + + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + + e2.getMessage()); + } + } + } + + } + + else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/1072760797/src/com/coderising/ood/srp/product_promotion.txt b/students/1072760797/src/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/1072760797/src/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/108847244/ood/ood-assignment/pom.xml b/students/108847244/ood/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/108847244/ood/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/108847244/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/108847244/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/108847244/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/108847244/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/108847244/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/108847244/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/108847244/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/108847244/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/108847244/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/108847244/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/108847244/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..9f9e749af7 --- /dev/null +++ b/students/108847244/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/108847244/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/108847244/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..781587a846 --- /dev/null +++ b/students/108847244/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,199 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery = null; + + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected String productID = null; + protected String productDesc = null; + + private static Configuration config; + + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + + + config = new Configuration(); + + setSMTPHost(); + setAltSMTPHost(); + + + setFromAddress(); + + + setLoadQuery(); + + sendEMails(mailDebug, loadMailingList()); + + + } + + + + + protected void setProductID(String productID) + { + this.productID = productID; + + } + + protected String getproductID() + { + return productID; + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected void setSMTPHost() + { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() + { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + protected void setFromAddress() + { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setMessage(HashMap userInfo) throws IOException + { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + + + + } + + + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + private void setProductDesc(String desc) { + this.productDesc = desc; + } + + + protected void configureEMail(HashMap userInfo) throws IOException + { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try + { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } + + else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/108847244/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/108847244/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/108847244/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/1132643730/ood-assignment/pom.xml b/students/1132643730/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/1132643730/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java new file mode 100644 index 0000000000..9a4cbb0f0c --- /dev/null +++ b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java @@ -0,0 +1,28 @@ +/** + * 版权 (c) 2017 palmshe.com + * 保留所有权利。 + */ +package com.coderising.ood.ocp; + +import com.coderising.ood.ocp.formatter.LogFormatter; +import com.coderising.ood.ocp.handler.LogHandler; + +/** + * @Description: + * @author palmshe + * @date 2017年6月19日 下午9:10:02 + */ +public class Logger { + + private LogHandler logHandler; + private LogFormatter logFormatter; + + public Logger(LogHandler handler, LogFormatter formatter){ + this.logHandler= handler; + this.logFormatter= formatter; + } + + public void log(String msg){ + this.logHandler.handleLog(this.logFormatter.formatMsg(msg)); + } +} diff --git a/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/Main.java b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/Main.java new file mode 100644 index 0000000000..9a072602b0 --- /dev/null +++ b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/Main.java @@ -0,0 +1,29 @@ +/** + * 版权 (c) 2017 palmshe.com + * 保留所有权利。 + */ +package com.coderising.ood.ocp; + +import com.coderising.ood.ocp.formatter.DateUtil; +import com.coderising.ood.ocp.formatter.LogFormatter; +import com.coderising.ood.ocp.handler.LogHandler; +import com.coderising.ood.ocp.handler.MailUtil; +import com.coderising.ood.ocp.handler.SMSUtil; + +/** + * @Description: + * @author palmshe + * @date 2017年6月19日 下午9:36:38 + */ +public class Main { + + public static void main(String[] args) { + LogHandler sms= new SMSUtil(); + LogHandler mail= new MailUtil(); + LogFormatter date= new DateUtil(); + Logger log= new Logger(sms, date); + log.log("hello world"); + log= new Logger(mail, date); + log.log("hello coder"); + } +} diff --git a/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/DateUtil.java b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/DateUtil.java new file mode 100644 index 0000000000..7b45fd15dd --- /dev/null +++ b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/DateUtil.java @@ -0,0 +1,20 @@ +package com.coderising.ood.ocp.formatter; + +import java.util.Date; + +public class DateUtil implements LogFormatter{ + + private String getCurrentDateAsString() { + + return "current date: "+ new Date(); + } + + /* (non-Javadoc) + * @see com.coderising.ood.ocp.LogFormatter#formatMsg(java.lang.String) + */ + @Override + public String formatMsg(String msg) { + return getCurrentDateAsString()+ ", "+ msg; + } + +} diff --git a/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/LogFormatter.java b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/LogFormatter.java new file mode 100644 index 0000000000..0be87702f2 --- /dev/null +++ b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/LogFormatter.java @@ -0,0 +1,15 @@ +/** + * 版权 (c) 2017 palmshe.com + * 保留所有权利。 + */ +package com.coderising.ood.ocp.formatter; + +/** + * @Description: + * @author palmshe + * @date 2017年6月19日 下午9:07:00 + */ +public interface LogFormatter { + + String formatMsg(String msg); +} diff --git a/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/LogHandler.java b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/LogHandler.java new file mode 100644 index 0000000000..e86cebba24 --- /dev/null +++ b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/LogHandler.java @@ -0,0 +1,17 @@ +/** + * 版权 (c) 2017 palmshe.com + * 保留所有权利。 + */ +package com.coderising.ood.ocp.handler; + +import java.io.Serializable; + +/** + * @Description: + * @author palmshe + * @date 2017年6月19日 下午9:08:04 + */ +public interface LogHandler extends Serializable{ + + void handleLog(String msg); +} diff --git a/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/MailUtil.java b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/MailUtil.java new file mode 100644 index 0000000000..e9fb2d90da --- /dev/null +++ b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/MailUtil.java @@ -0,0 +1,9 @@ +package com.coderising.ood.ocp.handler; + +public class MailUtil implements LogHandler{ + + public void handleLog(String logMsg) { + System.out.println("MailUtil handle, msg= "+ logMsg); + } + +} diff --git a/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/PrintUtil.java b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/PrintUtil.java new file mode 100644 index 0000000000..8f2ab2b697 --- /dev/null +++ b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/PrintUtil.java @@ -0,0 +1,21 @@ +/** + * 版权 (c) 2017 palmshe.com + * 保留所有权利。 + */ +package com.coderising.ood.ocp.handler; + +/** + * @Description: + * @author palmshe + * @date 2017年6月19日 下午9:22:49 + */ +public class PrintUtil implements LogHandler{ + + /* (non-Javadoc) + * @see com.coderising.ood.ocp.LogHandler#send(java.lang.String) + */ + @Override + public void handleLog(String msg) { + System.out.println("PrintUtil handle, msg= "+ msg); + } +} diff --git a/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/SMSUtil.java b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/SMSUtil.java new file mode 100644 index 0000000000..4bd916587d --- /dev/null +++ b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/SMSUtil.java @@ -0,0 +1,9 @@ +package com.coderising.ood.ocp.handler; + +public class SMSUtil implements LogHandler{ + + public void handleLog(String logMsg) { + System.out.println("SMSUtil handle, msg= "+ logMsg); + } + +} diff --git a/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..ccffce577d --- /dev/null +++ b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public static String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/DataGenerator.java b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/DataGenerator.java new file mode 100644 index 0000000000..6e9f1c2e84 --- /dev/null +++ b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/DataGenerator.java @@ -0,0 +1,64 @@ +/** + * 版权 (c) 2017 palmshe.com + * 保留所有权利。 + */ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @Description: + * @author palmshe + * @date 2017年6月11日 下午10:24:46 + */ +public class DataGenerator { + + /** + * @Description:获取商品 + * @param file + * @return + * @throws IOException + */ + public static Map generateGoods(File file) throws IOException{ + Map good= new HashMap(); + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + good.put(PromotionMail.ID_KEY, data[0]); + good.put(PromotionMail.DESC_KEY, data[1]); + + System.out.println("产品ID = " + data[0] + "\n"); + System.out.println("产品描述 = " + data[1] + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + return good; + } + + /** + * @Description:获取客户 + * @param good + * @return + * @throws Exception + */ + public static List loadMailingList(Map good) throws Exception { + String id= (String)good.get(PromotionMail.ID_KEY); + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + id +"' " + + "and send_mail=1 "; + + return DBUtil.query(sendMailQuery); + } +} diff --git a/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..e31d8a9b75 --- /dev/null +++ b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,41 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + private static String fromAddress; + private static String smtpServer; + private static String altSmtpServer; + + public MailUtil(String fromAddress, String smtpServer, String altSmtpServer){ + this.fromAddress= fromAddress; + this.smtpServer= smtpServer; + this.altSmtpServer= altSmtpServer; + } + + /** + * @Description:发送邮件 + * @param pm + * @param debug + */ + public void sendEmail(PromotionMail pm, boolean debug){ + try { + sendEmail(fromAddress, pm.toAddress, pm.subject, pm.message, smtpServer, debug); + } catch (Exception e1) { + try { + sendEmail(fromAddress, pm.toAddress, pm.subject, pm.message, altSmtpServer, debug); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + private void sendEmail(String from, String to, String subject, String message, String server, boolean debug){ +// 假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(from).append("\n"); + buffer.append("To:").append(to).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + } +} diff --git a/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/Main.java b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/Main.java new file mode 100644 index 0000000000..9e8a514191 --- /dev/null +++ b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/Main.java @@ -0,0 +1,34 @@ +/** + * 版权 (c) 2017 palmshe.com + * 保留所有权利。 + */ +package com.coderising.ood.srp; + +import java.io.File; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +/** + * @Description: + * @author palmshe + * @date 2017年6月12日 下午10:07:23 + */ +public class Main { + public static void main(String[] args) { + try { + File f = new File("C:\\Users\\Administrator.PC-20170125UBDJ\\Desktop\\coder2017\\coding2017\\students\\1132643730\\ood-assignment\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"); + MailUtil maiUtil= new MailUtil(Configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN), Configuration.getProperty(ConfigurationKeys.SMTP_SERVER), Configuration.getProperty(ConfigurationKeys.ALT_SMTP_SERVER)); + Map good = DataGenerator.generateGoods(f); + List users= DataGenerator.loadMailingList(good); + if (!users.isEmpty()) { + Iterator it= users.iterator(); + while (it.hasNext()) { + maiUtil.sendEmail(new PromotionMail((Map)it.next(), good), true); + } + } + } catch (Exception e) { + System.out.println("构造发送邮件数据失败:"+ e.getMessage()); + } + } +} diff --git a/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..a773d878ee --- /dev/null +++ b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,26 @@ +package com.coderising.ood.srp; + +import java.util.Map; + +public class PromotionMail { + + protected String toAddress = null; + protected String subject = null; + protected String message = null; + protected String productID = null; + protected String productDesc = null; + + protected static final String NAME_KEY = "NAME"; + protected static final String EMAIL_KEY = "EMAIL"; + protected static final String ID_KEY = "ID"; + protected static final String DESC_KEY = "DESC"; + + public PromotionMail(Map user, Map good){ + String name = (String)user.get(NAME_KEY); + this.productDesc= (String)good.get(DESC_KEY); + this.productID= (String)good.get(ID_KEY); + this.toAddress= (String)user.get(EMAIL_KEY); + this.subject = "您关注的产品降价了"; + this.message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + } +} diff --git a/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/1132643730/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/1132643730/readme.md b/students/1132643730/readme.md new file mode 100644 index 0000000000..fdae662c31 --- /dev/null +++ b/students/1132643730/readme.md @@ -0,0 +1 @@ +### 学着使用git \ No newline at end of file diff --git a/students/115615290/ood-assignment/config/product_promotion.txt b/students/115615290/ood-assignment/config/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/115615290/ood-assignment/config/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/115615290/ood-assignment/pom.xml b/students/115615290/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/115615290/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/115615290/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/115615290/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..d11d29787e --- /dev/null +++ b/students/115615290/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/115615290/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/115615290/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/115615290/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/115615290/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/115615290/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..9f7cd5433f --- /dev/null +++ b/students/115615290/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,27 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + User user = new User(); + user.setName("User" + i); + user.setEmail("aa@bb.com"); + + userList.add(user); + } + + return userList; + } +} diff --git a/students/115615290/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/115615290/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..22584f3d95 --- /dev/null +++ b/students/115615290/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,21 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + if(toAddress==null||toAddress.equals("")){ + throw new RuntimeException("发送地址不能为空!"); + } + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/115615290/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java b/students/115615290/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..4208ee6d34 --- /dev/null +++ b/students/115615290/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,48 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +public class Product { + + private String productID; + private String productDesc; + + public Product (File file) throws IOException{ + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + public String getProductID() { + return productID; + } + public void setProductID(String productID) { + this.productID = productID; + } + public String getProductDesc() { + return productDesc; + } + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + + + +} diff --git a/students/115615290/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/115615290/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..e14524f666 --- /dev/null +++ b/students/115615290/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,74 @@ +package com.coderising.ood.srp; + +import java.io.File; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery = null; + + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String subject = null; + protected String message = null; + + + private static Configuration config; + + + + public static void main(String[] args) throws Exception { + + File f = new File("config/product_promotion.txt"); + PromotionMail pe = new PromotionMail(); + List users = DBUtil.query(pe.sendMailQuery); + Product product = new Product(f); + pe.sendEMails(users, product); + + } + + + public PromotionMail() throws Exception { + config = new Configuration(); + setSMTPHost(); + setAltSMTPHost(); + setFromAddress(); + } + + protected void setSMTPHost() { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + protected void setAltSMTPHost() { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + } + + + protected void setFromAddress() { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + public void setMessage(User user,Product product){ + subject = "您关注的产品降价了"; + message = "尊敬的 "+user.getName()+", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!" ; + } + + public void sendEMails(User user,Product product){ + setMessage(user,product); + System.out.println("开始发送邮件"); + MailUtil.sendEmail(user.getEmail(), fromAddress, subject, message, smtpHost, true); + System.out.println("邮件发送完毕"); + } + + public void sendEMails(List users,Product product){ + System.out.println("开始发送邮件"); + for(User user:users){ + setMessage(user,product); + MailUtil.sendEmail(user.getEmail(), fromAddress, subject, message, smtpHost, true); + } + System.out.println("邮件发送完毕"); + } +} diff --git a/students/115615290/ood-assignment/src/main/java/com/coderising/ood/srp/User.java b/students/115615290/ood-assignment/src/main/java/com/coderising/ood/srp/User.java new file mode 100644 index 0000000000..42e4c81f89 --- /dev/null +++ b/students/115615290/ood-assignment/src/main/java/com/coderising/ood/srp/User.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; + +public class User { + + private String name; + private String email; + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + + +} diff --git a/students/1158154002/pom.xml b/students/1158154002/pom.xml new file mode 100644 index 0000000000..1be81576cc --- /dev/null +++ b/students/1158154002/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/1158154002/src/main/java/com/coderising/dp/bridge/Circle.java b/students/1158154002/src/main/java/com/coderising/dp/bridge/Circle.java new file mode 100644 index 0000000000..39483dabb9 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/bridge/Circle.java @@ -0,0 +1,12 @@ +package com.coderising.dp.bridge; + +public class Circle extends Shape { + + @Override + public void draw() { + super.getDrawing().drawCircle(); + System.out.println("I'm a Line"); + + } + +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/dp/bridge/Drawing.java b/students/1158154002/src/main/java/com/coderising/dp/bridge/Drawing.java new file mode 100644 index 0000000000..97ad4b2378 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/bridge/Drawing.java @@ -0,0 +1,6 @@ +package com.coderising.dp.bridge; + +public interface Drawing { +void drawLine(); +void drawCircle(); +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/bridge/DrawingGL1.java b/students/1158154002/src/main/java/com/coderising/dp/bridge/DrawingGL1.java new file mode 100644 index 0000000000..c1addd2658 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/bridge/DrawingGL1.java @@ -0,0 +1,15 @@ +package com.coderising.dp.bridge; + +public class DrawingGL1 implements Drawing{ + + @Override + public void drawLine() { + System.out.println("DrawingGL1.drawLine"); + } + + @Override + public void drawCircle() { + System.out.println("DrawingGL1.drawCircle"); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/bridge/DrawingGL2.java b/students/1158154002/src/main/java/com/coderising/dp/bridge/DrawingGL2.java new file mode 100644 index 0000000000..b30a86d053 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/bridge/DrawingGL2.java @@ -0,0 +1,15 @@ +package com.coderising.dp.bridge; + +public class DrawingGL2 implements Drawing{ + + @Override + public void drawLine() { + System.out.println("DrawingGL2.drawLine"); + } + + @Override + public void drawCircle() { + System.out.println("DrawingGL2.drawCircle"); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/bridge/Rectangle.java b/students/1158154002/src/main/java/com/coderising/dp/bridge/Rectangle.java new file mode 100644 index 0000000000..ab4f171f96 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/bridge/Rectangle.java @@ -0,0 +1,11 @@ +package com.coderising.dp.bridge; + +public class Rectangle extends Shape { + + @Override + public void draw() { + super.getDrawing().drawLine(); + System.out.println("I'm a Rectangle"); + } + +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/dp/bridge/Shape.java b/students/1158154002/src/main/java/com/coderising/dp/bridge/Shape.java new file mode 100644 index 0000000000..f317e344d4 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/bridge/Shape.java @@ -0,0 +1,12 @@ +package com.coderising.dp.bridge; + +public abstract class Shape { + public Drawing drawing; + public Drawing getDrawing() { + return drawing; + } + public void setDrawing(Drawing drawing) { + this.drawing = drawing; + } + public abstract void draw(); +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/bridge/Test.java b/students/1158154002/src/main/java/com/coderising/dp/bridge/Test.java new file mode 100644 index 0000000000..3aceb7fe89 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/bridge/Test.java @@ -0,0 +1,16 @@ +package com.coderising.dp.bridge; + +public class Test { + + public static void main(String[] args) { + Shape rectangel=new Rectangle(); + rectangel.setDrawing(new DrawingGL1()); + rectangel.draw(); + + + Shape circle=new Circle(); + circle.setDrawing(new DrawingGL2()); + circle.draw(); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/builder/TagBuilder.java b/students/1158154002/src/main/java/com/coderising/dp/builder/TagBuilder.java new file mode 100644 index 0000000000..baefede533 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/builder/TagBuilder.java @@ -0,0 +1,43 @@ +package com.coderising.dp.builder; + +import java.util.List; + +public class TagBuilder { + private TagNode root; + private TagNode now; + private TagNode prev; + public TagBuilder(String rootTagName) { + root=new TagNode(rootTagName); + now=root; + } + + public TagBuilder addChild(String childTagName) { + prev=now; + now=new TagNode(childTagName); + prev.add(now); + + return this; + } + + public TagBuilder addSibling(String siblingTagName) { + List children=prev.getChildren(); + now=new TagNode(siblingTagName); + children.add(now); + return this; + + } + + public TagBuilder setAttribute(String name, String value) { + now.setAttribute(name, value); + return this; + } + + public TagBuilder setText(String value) { + + return this; + } + + public String toXML() { + return root.toXML(); + } +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/builder/TagBuilderTest.java b/students/1158154002/src/main/java/com/coderising/dp/builder/TagBuilderTest.java new file mode 100644 index 0000000000..147e159b23 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/builder/TagBuilderTest.java @@ -0,0 +1,45 @@ +package com.coderising.dp.builder; + +import static org.junit.Assert.assertEquals; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class TagBuilderTest { + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testToXML() { + + TagBuilder builder = new TagBuilder("order"); + + String xml = builder.addChild("line-items") + .addChild("line-item").setAttribute("pid", "P3677").setAttribute("qty", "3") + .addSibling("line-item").setAttribute("pid", "P9877").setAttribute("qty", "10") + .toXML(); + + String expected = "" + + "" + + "" + + "" + + "" + + ""; + + System.out.println(xml); + assertEquals(expected, xml); + +// com.oracle.nio.BufferSecrets +// +// com.sun.corba.se.spi.extension.ServantCachingPolicy +// +// java.net.ProxySelector + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/builder/TagNode.java b/students/1158154002/src/main/java/com/coderising/dp/builder/TagNode.java new file mode 100644 index 0000000000..33b421cf10 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/builder/TagNode.java @@ -0,0 +1,83 @@ +package com.coderising.dp.builder; + +import java.util.ArrayList; +import java.util.List; + +public class TagNode { + private String tagName; + private String tagValue; + private List children = new ArrayList<>(); + private List attributes = new ArrayList<>(); + + public TagNode(String name){ + this.tagName = name; + } + public void add(TagNode child){ + this.children.add(child); + } + public void setAttribute(String name, String value) { + Attribute attr = findAttribute(name); + if(attr != null){ + attr.value = value; + return; + } + + attributes.add(new Attribute(name,value)); + } + private Attribute findAttribute(String name){ + for(Attribute attr : attributes){ + if(attr.name.equals(name)){ + return attr; + } + } + return null; + } + public void setValue(String value) { + this.tagValue = value; + + } + public String getTagName() { + return tagName; + } + public List getChildren() { + return children; + } + + private static class Attribute{ + public Attribute(String name, String value) { + this.name = name; + this.value = value; + } + String name; + String value; + + } + public String toXML(){ + return toXML(this); + } + private String toXML(TagNode node){ + StringBuilder buffer = new StringBuilder(); + buffer.append("<").append(node.tagName); + if(node.attributes.size()> 0){ + for(int i=0;i"); + return buffer.toString(); + } + buffer.append(">"); + for(TagNode childNode : node.children){ + buffer.append(toXML(childNode)); + } + buffer.append(""); + + + return buffer.toString(); + } + private String toXML(Attribute attr){ + return attr.name+"=\""+attr.value + "\""; + } +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/chain/EmailLogger.java b/students/1158154002/src/main/java/com/coderising/dp/chain/EmailLogger.java new file mode 100644 index 0000000000..8a249c048a --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/chain/EmailLogger.java @@ -0,0 +1,15 @@ +package com.coderising.dp.chain; + +public class EmailLogger extends Logger{ + + EmailLogger(int level) { + super(level); + } + + @Override + protected void write(String message) { + System.out.println("EmailLogger "+message); + } + + +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/chain/FileLogger.java b/students/1158154002/src/main/java/com/coderising/dp/chain/FileLogger.java new file mode 100644 index 0000000000..22b8a4cd9b --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/chain/FileLogger.java @@ -0,0 +1,15 @@ +package com.coderising.dp.chain; + +public class FileLogger extends Logger { + + FileLogger(int level) { + super(level); + } + + @Override + protected void write(String message) { + System.out.println("FileLogger " + message); + } + + +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/chain/Logger.java b/students/1158154002/src/main/java/com/coderising/dp/chain/Logger.java new file mode 100644 index 0000000000..1265063c31 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/chain/Logger.java @@ -0,0 +1,28 @@ +package com.coderising.dp.chain; + +public abstract class Logger { + public static int DEBUG = 1; + public static int NOTICE = 2; + public static int ERR = 3; + protected int level; + + Logger(int level) { + this.level=level; + } + protected Logger nextLogger; + public Logger setNextLogger(Logger nextLogger) { + this.nextLogger = nextLogger; + return this; + } + + public void message(String message,int level){ + if (this.level<=level) { + write(message); + } + if (nextLogger!=null) { + nextLogger.message( message,level); + } + } + abstract protected void write(String message); + +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/chain/StdoutLogger.java b/students/1158154002/src/main/java/com/coderising/dp/chain/StdoutLogger.java new file mode 100644 index 0000000000..0bf96e8d9c --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/chain/StdoutLogger.java @@ -0,0 +1,13 @@ +package com.coderising.dp.chain; + +public class StdoutLogger extends Logger{ + + StdoutLogger(int level) { + super(level); + } + + @Override + protected void write(String message) { + System.out.println("StdoutLogger "+message); + } +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/chain/Test.java b/students/1158154002/src/main/java/com/coderising/dp/chain/Test.java new file mode 100644 index 0000000000..13ff6419e1 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/chain/Test.java @@ -0,0 +1,15 @@ +package com.coderising.dp.chain; + +public class Test { + + public static void main(String[] args) { + Logger logger = new StdoutLogger(Logger.DEBUG) + .setNextLogger(new EmailLogger(Logger.NOTICE).setNextLogger(new FileLogger(Logger.ERR))); + logger.message("进入函数计算", Logger.DEBUG); + + logger.message("第一步已经完成", Logger.NOTICE); + + logger.message("一个致命的错误发生了", Logger.ERR); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/command/Command.java b/students/1158154002/src/main/java/com/coderising/dp/command/Command.java new file mode 100644 index 0000000000..bd54aeec59 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/command/Command.java @@ -0,0 +1,5 @@ +package com.coderising.dp.command; + +public interface Command { + void order(); +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/command/Cook.java b/students/1158154002/src/main/java/com/coderising/dp/command/Cook.java new file mode 100644 index 0000000000..710d752521 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/command/Cook.java @@ -0,0 +1,11 @@ +package com.coderising.dp.command; + +public class Cook { + void cookSteak(){ + System.out.println("Steak is ok"); + } + + void cookPork(){ + System.out.println("Pork is ok"); + } +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/command/OrderPorkCommand.java b/students/1158154002/src/main/java/com/coderising/dp/command/OrderPorkCommand.java new file mode 100644 index 0000000000..b0e1c61191 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/command/OrderPorkCommand.java @@ -0,0 +1,13 @@ +package com.coderising.dp.command; + +public class OrderPorkCommand implements Command{ + private Cook cook; + public OrderPorkCommand(Cook cook) { + this.cook=cook; + } + @Override + public void order() { + cook.cookPork(); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/command/OrderSteakCommand.java b/students/1158154002/src/main/java/com/coderising/dp/command/OrderSteakCommand.java new file mode 100644 index 0000000000..e56b2649b5 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/command/OrderSteakCommand.java @@ -0,0 +1,15 @@ +package com.coderising.dp.command; + +public class OrderSteakCommand implements Command { + private Cook cook; + + public OrderSteakCommand(Cook cook) { + this.cook = cook; + } + + @Override + public void order() { + cook.cookSteak(); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/command/Waiter.java b/students/1158154002/src/main/java/com/coderising/dp/command/Waiter.java new file mode 100644 index 0000000000..0c9e94852c --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/command/Waiter.java @@ -0,0 +1,33 @@ +package com.coderising.dp.command; + +import java.util.ArrayList; +import java.util.List; + +public class Waiter { + private List commands = new ArrayList<>(); + + public void addOrder(Command command) { + commands.add(command); + } + + public void sendOrders(){ + for (Command command : commands) { + command.order(); + } + } + + public static void main(String[] args) { + Cook cook=new Cook(); + + Waiter waiter=new Waiter(); + + Command command1=new OrderSteakCommand(cook); + Command command2=new OrderPorkCommand(cook); + + waiter.addOrder(command1); + waiter.addOrder(command2); + + waiter.sendOrders(); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/composite/Line.java b/students/1158154002/src/main/java/com/coderising/dp/composite/Line.java new file mode 100644 index 0000000000..411eb80876 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/composite/Line.java @@ -0,0 +1,11 @@ +package com.coderising.dp.composite; + +public class Line implements Shape { + + @Override + public void draw() { + System.out.println("I'm a Line"); + + } + +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/dp/composite/Picture.java b/students/1158154002/src/main/java/com/coderising/dp/composite/Picture.java new file mode 100644 index 0000000000..b52ac69ae2 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/composite/Picture.java @@ -0,0 +1,33 @@ +package com.coderising.dp.composite; + +import java.util.ArrayList; +import java.util.List; + +public class Picture implements Shape{ + private List shapes=new ArrayList<>(); + @Override + public void draw() { + for (Shape shape : shapes) { + shape.draw(); + } + } + + public void add(Shape shape){ + shapes.add(shape); + } + + public static void main(String[] args) { + Picture aPicture=new Picture(); + aPicture.add(new Line()); + aPicture.add(new Rectangle()); + + Picture a=new Picture(); + a.add(new Text()); + a.add(new Line()); + a.add(new Square()); + aPicture.add(a); + + aPicture.draw(); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/composite/Rectangle.java b/students/1158154002/src/main/java/com/coderising/dp/composite/Rectangle.java new file mode 100644 index 0000000000..9547cd7aa9 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/composite/Rectangle.java @@ -0,0 +1,10 @@ +package com.coderising.dp.composite; + +public class Rectangle implements Shape { + + @Override + public void draw() { + System.out.println("I'm a Rectangle"); + } + +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/dp/composite/Shape.java b/students/1158154002/src/main/java/com/coderising/dp/composite/Shape.java new file mode 100644 index 0000000000..45c428c6b9 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/composite/Shape.java @@ -0,0 +1,5 @@ +package com.coderising.dp.composite; + +public interface Shape { + public void draw(); +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/composite/Square.java b/students/1158154002/src/main/java/com/coderising/dp/composite/Square.java new file mode 100644 index 0000000000..50b94ca09d --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/composite/Square.java @@ -0,0 +1,10 @@ +package com.coderising.dp.composite; + +public class Square implements Shape { + + @Override + public void draw() { + System.out.println("I'm a Square"); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/composite/Text.java b/students/1158154002/src/main/java/com/coderising/dp/composite/Text.java new file mode 100644 index 0000000000..db0268f18a --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/composite/Text.java @@ -0,0 +1,10 @@ +package com.coderising.dp.composite; + +public class Text implements Shape { + + @Override + public void draw() { + System.out.println("I'm a Text"); + } + +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/dp/decorator/Email.java b/students/1158154002/src/main/java/com/coderising/dp/decorator/Email.java new file mode 100644 index 0000000000..50ce116777 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/decorator/Email.java @@ -0,0 +1,5 @@ +package com.coderising.dp.decorator; + +public interface Email { + public String getContent(); +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/decorator/EmailImpl.java b/students/1158154002/src/main/java/com/coderising/dp/decorator/EmailImpl.java new file mode 100644 index 0000000000..7ce815ca35 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/decorator/EmailImpl.java @@ -0,0 +1,14 @@ +package com.coderising.dp.decorator; + +public class EmailImpl implements Email{ + private String content; + + public EmailImpl(String content) { + this.content = content; + } + + @Override + public String getContent() { + return content; + } +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/decorator/EmailProxy.java b/students/1158154002/src/main/java/com/coderising/dp/decorator/EmailProxy.java new file mode 100644 index 0000000000..344459a35f --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/decorator/EmailProxy.java @@ -0,0 +1,29 @@ +package com.coderising.dp.decorator; + +public class EmailProxy implements Email{ + Email email; + + @Override + public String getContent() { + String content=email.getContent()+"\n本邮件仅为个人观点,并不代表公司立场"; + System.out.println(content); + content=Encrypt.SHA256(content); + System.out.println(content); + return content; + } + + public void setEmail(Email email) { + this.email = email; + } + + public static void main(String[] args) { + EmailImpl email=new EmailImpl("hello world!"); + EmailProxy proxy=new EmailProxy(); + EmailProxy proxy1=new EmailProxy(); + proxy.setEmail(email); + // proxy.getContent(); + proxy1.setEmail(proxy); + proxy1.getContent(); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/dp/decorator/Encrypt.java b/students/1158154002/src/main/java/com/coderising/dp/decorator/Encrypt.java new file mode 100644 index 0000000000..79f2a4a4d6 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/dp/decorator/Encrypt.java @@ -0,0 +1,76 @@ +package com.coderising.dp.decorator; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class Encrypt { + /** + * 传入文本内容,返回 SHA-256 串 + * + * @param strText + * @return + */ + public static String SHA256(final String strText) + { + return SHA(strText, "SHA-256"); + } + + /** + * 传入文本内容,返回 SHA-512 串 + * + * @param strText + * @return + */ + public static String SHA512(final String strText) + { + return SHA(strText, "SHA-512"); + } + + /** + * 字符串 SHA 加密 + * + * @param strSourceText + * @return + */ + private static String SHA(final String strText, final String strType) + { + // 返回值 + String strResult = null; + + // 是否是有效字符串 + if (strText != null && strText.length() > 0) + { + try + { + // SHA 加密开始 + // 创建加密对象 并傳入加密類型 + MessageDigest messageDigest = MessageDigest.getInstance(strType); + // 传入要加密的字符串 + messageDigest.update(strText.getBytes()); + // 得到 byte 類型结果 + byte byteBuffer[] = messageDigest.digest(); + + // 將 byte 轉換爲 string + StringBuffer strHexString = new StringBuffer(); + // 遍歷 byte buffer + for (int i = 0; i < byteBuffer.length; i++) + { + String hex = Integer.toHexString(0xff & byteBuffer[i]); + if (hex.length() == 1) + { + strHexString.append('0'); + } + strHexString.append(hex); + } + // 得到返回結果 + strResult = strHexString.toString(); + } + catch (NoSuchAlgorithmException e) + { + e.printStackTrace(); + } + } + + return strResult; + } +} diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/extension/RepeatedTest.java b/students/1158154002/src/main/java/com/coderising/litejunit/extension/RepeatedTest.java new file mode 100644 index 0000000000..f13faf5b43 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/extension/RepeatedTest.java @@ -0,0 +1,32 @@ +package com.coderising.litejunit.extension; + +import com.coderising.litejunit.v2.Test; +import com.coderising.litejunit.v2.TestResult; + +/** + * A Decorator that runs a test repeatedly. + * + */ +public class RepeatedTest extends TestDecorator { + private int fTimesRepeat; + + public RepeatedTest(Test test, int repeat) { + super(test); + if (repeat < 0) + throw new IllegalArgumentException("Repetition count must be > 0"); + fTimesRepeat= repeat; + } + public int countTestCases() { + return super.countTestCases()*fTimesRepeat; + } + public void run(TestResult result) { + for (int i= 0; i < fTimesRepeat; i++) { + if (result.shouldStop()) + break; + super.run(result); + } + } + public String toString() { + return super.toString()+"(repeated)"; + } +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/extension/TestDecorator.java b/students/1158154002/src/main/java/com/coderising/litejunit/extension/TestDecorator.java new file mode 100644 index 0000000000..3b51d7bff1 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/extension/TestDecorator.java @@ -0,0 +1,40 @@ +package com.coderising.litejunit.extension; + +import com.coderising.litejunit.v2.Assert; +import com.coderising.litejunit.v2.Test; +import com.coderising.litejunit.v2.TestResult; + +/** + * A Decorator for Tests. Use TestDecorator as the base class + * for defining new test decorators. Test decorator subclasses + * can be introduced to add behaviour before or after a test + * is run. + * + */ +public class TestDecorator extends Assert implements Test { + protected Test test; + + public TestDecorator(Test test) { + this.test= test; + } + /** + * The basic run behaviour. + */ + public void basicRun(TestResult result) { + test.run(result); + } + public int countTestCases() { + return test.countTestCases(); + } + public void run(TestResult result) { + basicRun(result); + } + + public String toString() { + return test.toString(); + } + + public Test getTest() { + return test; + } +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/extension/TestSetup.java b/students/1158154002/src/main/java/com/coderising/litejunit/extension/TestSetup.java new file mode 100644 index 0000000000..54f95f6f79 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/extension/TestSetup.java @@ -0,0 +1,39 @@ +package com.coderising.litejunit.extension; + +import com.coderising.litejunit.v2.Protectable; +import com.coderising.litejunit.v2.Test; +import com.coderising.litejunit.v2.TestResult; + +/** + * A Decorator to set up and tear down additional fixture state. + * Subclass TestSetup and insert it into your tests when you want + * to set up additional state once before the tests are run. + */ +public class TestSetup extends TestDecorator { + + public TestSetup(Test test) { + super(test); + } + public void run(final TestResult result) { + Protectable p= new Protectable() { + public void protect() throws Exception { + setUp(); + basicRun(result); + tearDown(); + } + }; + result.runProtected(this, p); + } + /** + * Sets up the fixture. Override to set up additional fixture + * state. + */ + protected void setUp() throws Exception { + } + /** + * Tears down the fixture. Override to tear down the additional + * fixture state. + */ + protected void tearDown() throws Exception { + } +} diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/sample/AllTest.java b/students/1158154002/src/main/java/com/coderising/litejunit/sample/AllTest.java new file mode 100644 index 0000000000..8cf38f176b --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/sample/AllTest.java @@ -0,0 +1,42 @@ +package com.coderising.litejunit.sample; + +import com.coderising.litejunit.extension.RepeatedTest; +import com.coderising.litejunit.extension.TestSetup; +import com.coderising.litejunit.sample.calculator.CalculatorSuite; +import com.coderising.litejunit.v2.Test; +import com.coderising.litejunit.v2.TestSuite; + +public class AllTest { +// public static Test suite(){ +// +// TestSuite suite= new TestSuite("All Test"); +// suite.addTest(CalculatorSuite.suite()); +// //suite.addTestSuite(PersonTest.class); +// return suite; +// +// } + + public static Test suite(){ + + TestSuite suite= new TestSuite("All Test"); + suite.addTest(CalculatorSuite.suite()); + suite.addTest(new RepeatedTest(new TestSuite(PersonTest.class), 2)); + return new OverallTestSetup(suite); + } + + + static class OverallTestSetup extends TestSetup{ + + public OverallTestSetup(Test test) { + super(test); + + } + protected void setUp() throws Exception { + System.out.println("this is overall testsetup"); + } + protected void tearDown() throws Exception { + System.out.println("this is overall teardown"); + } + + } +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/sample/PersonTest.java b/students/1158154002/src/main/java/com/coderising/litejunit/sample/PersonTest.java new file mode 100644 index 0000000000..bcb8b1c971 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/sample/PersonTest.java @@ -0,0 +1,38 @@ +package com.coderising.litejunit.sample; + +import com.coderising.litejunit.v2.TestCase; + +public class PersonTest extends TestCase { + + Person p = null; + protected void setUp() { + p = new Person("andy",30); + } + public PersonTest(String name) { + super(name); + } + public void testAge(){ + this.assertEquals(30, p.getAge()); + } + public void testName(){ + this.assertEquals("andy", p.getName()); + } +} +class Person{ + private String name; + private int age; + + public Person(String name, int age) { + + this.name = name; + this.age = age; + } + public String getName() { + return name; + } + public int getAge() { + return age; + } + + +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/sample/calculator/Calculator.java b/students/1158154002/src/main/java/com/coderising/litejunit/sample/calculator/Calculator.java new file mode 100644 index 0000000000..cede0aab15 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/sample/calculator/Calculator.java @@ -0,0 +1,22 @@ +package com.coderising.litejunit.sample.calculator; + +public class Calculator { + + private int result = 0; + public void add(int x){ + result += x; + } + public void subtract(int x){ + result -=x; + } + + public int getResult(){ + return this.result; + } + public static void main(String[] args){ + Calculator calculator = new Calculator(); + calculator.add(10); + calculator.subtract(5); + System.out.println(calculator.getResult()); + } +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/sample/calculator/CalculatorSuite.java b/students/1158154002/src/main/java/com/coderising/litejunit/sample/calculator/CalculatorSuite.java new file mode 100644 index 0000000000..df3159bf91 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/sample/calculator/CalculatorSuite.java @@ -0,0 +1,12 @@ +package com.coderising.litejunit.sample.calculator; + +import com.coderising.litejunit.v2.Test; +import com.coderising.litejunit.v2.TestSuite; + +public class CalculatorSuite { + public static Test suite(){ + TestSuite suite= new TestSuite("Calculator All Test"); + suite.addTestSuite(CalculatorTest.class); + return suite; + } +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/sample/calculator/CalculatorTest.java b/students/1158154002/src/main/java/com/coderising/litejunit/sample/calculator/CalculatorTest.java new file mode 100644 index 0000000000..eb14934330 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/sample/calculator/CalculatorTest.java @@ -0,0 +1,59 @@ +package com.coderising.litejunit.sample.calculator; + +import com.coderising.litejunit.v2.TestCase; + +public class CalculatorTest extends TestCase { + public CalculatorTest(String name) { + super(name); + + } + Calculator calculator =null; + public void setUp(){ + calculator = new Calculator(); + } + public void tearDown(){ + calculator = null; + } + public void testAdd(){ + + calculator.add(10); + assertEquals(10,calculator.getResult()); + } + public void testSubtract(){ + calculator.add(10); + calculator.subtract(5); + //throw new RuntimeException("this is a test"); + assertEquals(5,calculator.getResult()); + } + + public static void main(String[] args){ + /*{ + TestCase tc1 = new CalculatorTest("testAdd"){ + protected void runTest() { + testAdd(); + } + }; + + TestCase tc2 = new CalculatorTest("testSubtract"){ + protected void runTest() { + testSubtract(); + } + }; + tc1.run(); + tc2.run(); + } + + + TestSuite ts = new TestSuite(); + ts.addTest(new CalculatorTest("testAdd")); + ts.addTest(new CalculatorTest("testSubtract")); + + + { + TestCase tc1 = new CalculatorTest("test1"); + TestCase tc2 = new CalculatorTest("test2"); + tc1.run(); + tc2.run(); + }*/ + } +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v/Assert.java b/students/1158154002/src/main/java/com/coderising/litejunit/v/Assert.java new file mode 100644 index 0000000000..0b68ef790c --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v/Assert.java @@ -0,0 +1,225 @@ +package com.coderising.litejunit.v; + +/** + * A set of assert methods. + */ + +public class Assert { + /** + * Protect constructor since it is a static only class + */ + protected Assert() { + } + + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError with the given message. + */ + static public void assertTrue(String message, boolean condition) { + if (!condition) + fail(message); + } + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError. + */ + static public void assertTrue(boolean condition) { + assertTrue(null, condition); + } + /** + * Fails a test with the given message. + */ + static public void fail(String message) { + throw new AssertionFailedError(message); + } + /** + * Fails a test with no message. + */ + static public void fail() { + fail(null); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(String message, Object expected, Object actual) { + if (expected == null && actual == null) + return; + if (expected != null && expected.equals(actual)) + return; + failNotEquals(message, expected, actual); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(Object expected, Object actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, double expected, double actual, double delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Double.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Double(expected), new Double(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) // Because comparison with NaN always returns false + failNotEquals(message, new Double(expected), new Double(actual)); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(double expected, double actual, double delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, float expected, float actual, float delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Float.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Float(expected), new Float(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) + failNotEquals(message, new Float(expected), new Float(actual)); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(float expected, float actual, float delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(String message, long expected, long actual) { + assertEquals(message, new Long(expected), new Long(actual)); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(long expected, long actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(String message, boolean expected, boolean actual) { + assertEquals(message, new Boolean(expected), new Boolean(actual)); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(boolean expected, boolean actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(String message, byte expected, byte actual) { + assertEquals(message, new Byte(expected), new Byte(actual)); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(byte expected, byte actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(String message, char expected, char actual) { + assertEquals(message, new Character(expected), new Character(actual)); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(char expected, char actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(String message, short expected, short actual) { + assertEquals(message, new Short(expected), new Short(actual)); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(short expected, short actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(String message, int expected, int actual) { + assertEquals(message, new Integer(expected), new Integer(actual)); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(int expected, int actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(Object object) { + assertNotNull(null, object); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(String message, Object object) { + assertTrue(message, object != null); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(Object object) { + assertNull(null, object); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(String message, Object object) { + assertTrue(message, object == null); + } + /** + * Asserts that two objects refer to the same object. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertSame(String message, Object expected, Object actual) { + if (expected == actual) + return; + failNotSame(message, expected, actual); + } + /** + * Asserts that two objects refer to the same object. If they are not + * the same an AssertionFailedError is thrown. + */ + static public void assertSame(Object expected, Object actual) { + assertSame(null, expected, actual); + } + + static private void failNotEquals(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected:<"+expected+"> but was:<"+actual+">"); + } + + static private void failNotSame(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected same"); + } +} diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v/AssertionFailedError.java b/students/1158154002/src/main/java/com/coderising/litejunit/v/AssertionFailedError.java new file mode 100644 index 0000000000..3c45ba40d5 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v/AssertionFailedError.java @@ -0,0 +1,13 @@ +package com.coderising.litejunit.v; + +/** + * Thrown when an assertion failed. + */ +public class AssertionFailedError extends Error { + + public AssertionFailedError () { + } + public AssertionFailedError (String message) { + super (message); + } +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v/Test.java b/students/1158154002/src/main/java/com/coderising/litejunit/v/Test.java new file mode 100644 index 0000000000..f5639552c3 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v/Test.java @@ -0,0 +1,6 @@ +package com.coderising.litejunit.v; + +public interface Test { + public abstract int countTestCases(); + public void run(TestResult tr); +} diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v/TestCase.java b/students/1158154002/src/main/java/com/coderising/litejunit/v/TestCase.java new file mode 100644 index 0000000000..49ac03b69f --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v/TestCase.java @@ -0,0 +1,63 @@ +package com.coderising.litejunit.v; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +public abstract class TestCase extends Assert implements Test { + private String name; + public TestCase(String name) { + this.name=name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public void run(TestResult tr) { + tr.run(this); + } + + public void doRun() { + setUp(); + try { + runTest(); + } finally { + tearDown(); + } + } + + protected void setUp(){ + + } + + private void runTest(){ + try { + Method method=this.getClass().getMethod(this.getName(),new Class[0]); + method.invoke(this, null); + } catch (NoSuchMethodException | SecurityException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } + + } + + + @Override + public int countTestCases() { + return 1; + } + + protected void tearDown(){ + + } + +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v/TestFailure.java b/students/1158154002/src/main/java/com/coderising/litejunit/v/TestFailure.java new file mode 100644 index 0000000000..e7a6fc1606 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v/TestFailure.java @@ -0,0 +1,39 @@ +package com.coderising.litejunit.v; + +/** + * A TestFailure collects a failed test together with + * the caught exception. + * @see TestResult + */ +public class TestFailure { + protected Test failedTest; + protected Throwable thrownException; + + /** + * Constructs a TestFailure with the given test and exception. + */ + public TestFailure(Test failedTest, Throwable thrownException) { + this.failedTest= failedTest; + this.thrownException= thrownException; + } + /** + * Gets the failed test. + */ + public Test failedTest() { + return failedTest; + } + /** + * Gets the thrown exception. + */ + public Throwable thrownException() { + return thrownException; + } + /** + * Returns a short description of the failure. + */ + public String toString() { + StringBuffer buffer= new StringBuffer(); + buffer.append(failedTest+": "+thrownException.getMessage()); + return buffer.toString(); + } +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v/TestListener.java b/students/1158154002/src/main/java/com/coderising/litejunit/v/TestListener.java new file mode 100644 index 0000000000..b98409a549 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v/TestListener.java @@ -0,0 +1,12 @@ +package com.coderising.litejunit.v; + +public interface TestListener { + + void addError(Test test,Throwable t); + + void addFailure(Test test,AssertionFailedError t); + + void endTest(Test test); + + void startTest(Test test); +} diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v/TestSuite.java b/students/1158154002/src/main/java/com/coderising/litejunit/v/TestSuite.java new file mode 100644 index 0000000000..ca694254b0 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v/TestSuite.java @@ -0,0 +1,77 @@ +package com.coderising.litejunit.v; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +public class TestSuite extends Assert implements Test { + List tests = new ArrayList<>(); + + public TestSuite(final Class clazz) { + Constructor cons = null; + cons = getConstructor(clazz, cons); + + Method[] methods = clazz.getDeclaredMethods(); + for (Method method : methods) { + if (isPublicTestMethod(method)) { + tests.add(addTestMethod(cons, method.getName())); + } + } + } + + private Constructor getConstructor(final Class clazz, Constructor cons) { + try { + cons = clazz.getConstructor(String.class); + } catch (NoSuchMethodException e) { + e.printStackTrace(); + } catch (SecurityException e) { + e.printStackTrace(); + } + return cons; + } + + private Test addTestMethod(Constructor cons, String name) { + try { + return (Test) cons.newInstance(name); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException + | InvocationTargetException e) { + e.printStackTrace(); + } + return null; + } + + private boolean isPublicTestMethod(Method method) { + return isPublic(method) && isTest(method); + } + + private boolean isTest(Method method) { + return method.getName().startsWith("test") && method.getParameterCount() == 0 + && method.getReturnType().equals(Void.TYPE); + } + + private boolean isPublic(Method method) { + return Modifier.isPublic(method.getModifiers()); + } + + @Override + public int countTestCases() { + int count=0; + for (Test test : tests) { + count+=test.countTestCases(); + } + + return count; + } + + @Override + public void run(TestResult tr) { + for (Test test : tests) { + test.run(tr); + } + + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v/runner/BaseTestRunner.java b/students/1158154002/src/main/java/com/coderising/litejunit/v/runner/BaseTestRunner.java new file mode 100644 index 0000000000..1217e45024 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v/runner/BaseTestRunner.java @@ -0,0 +1,45 @@ +package com.coderising.litejunit.v.runner; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import com.coderising.litejunit.v.AssertionFailedError; +import com.coderising.litejunit.v.Test; +import com.coderising.litejunit.v.TestListener; + +public abstract class BaseTestRunner implements TestListener { + public static final String METHOD_NAME = "suite"; + + public Test getTest(String testCase) { + if (testCase.length() <= 0) { + return null; + } + Class clazz = null; + try { + clazz = loadSuitClass(testCase); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + + try { + Method method = clazz.getMethod(METHOD_NAME, new Class[0]); + return (Test) method.invoke(null, null); + } catch (NoSuchMethodException e) { + e.printStackTrace(); + } catch (SecurityException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } + + return null; + } + + private static Class loadSuitClass(String suitClassName) throws ClassNotFoundException { + return Class.forName(suitClassName); + } +} diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v/textui/TestRunner.java b/students/1158154002/src/main/java/com/coderising/litejunit/v/textui/TestRunner.java new file mode 100644 index 0000000000..9c7342bc30 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v/textui/TestRunner.java @@ -0,0 +1,156 @@ +package com.coderising.litejunit.v.textui; + +import java.io.PrintStream; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.text.NumberFormat; +import java.util.Iterator; + +import com.coderising.litejunit.v.AssertionFailedError; +import com.coderising.litejunit.v.Test; +import com.coderising.litejunit.v.TestFailure; +import com.coderising.litejunit.v.TestResult; +import com.coderising.litejunit.v.runner.BaseTestRunner; + +public class TestRunner extends BaseTestRunner { + PrintStream writer=System.out; + int column=0; + + public static void main(String[] args) { + TestRunner testRunner = new TestRunner(); + try { + TestResult result= testRunner.start(args); + } catch (Exception e) { + e.printStackTrace(); + } + + } + + private TestResult start(String[] args) throws Exception { + if (args.length == 0) { + throw new Exception("参数错误!"); + } + String testCase = args[0]; + Test test = getTest(testCase); + return this.doRun(test); + } + + private TestResult doRun(Test suite){ + TestResult result=new TestResult(); + result.addListener(this); + long startTime= System.currentTimeMillis(); + suite.run(result); + long endTime= System.currentTimeMillis(); + long runTime= endTime-startTime; + writer().println(); + writer().println("Time: "+elapsedTimeAsString(runTime)); + print(result); + + writer().println(); + return result; + } + + private void print(TestResult result) { + printErrors(result); + printFailures(result); + printHeader(result); + + } + + /** + * Prints the errors to the standard output + */ + public void printErrors(TestResult result) { + if (result.errorCount() != 0) { + if (result.errorCount() == 1) + writer().println("There was "+result.errorCount()+" error:"); + else + writer().println("There were "+result.errorCount()+" errors:"); + + int i= 1; + for (Iterator e= result.errors(); e.hasNext(); i++) { + TestFailure failure= e.next(); + writer().println(i+") "+failure.failedTest()); + writer().print(getFilteredTrace(failure.thrownException())); + } + } + } + private static String getFilteredTrace(Throwable t) { + StringWriter stringWriter= new StringWriter(); + PrintWriter writer= new PrintWriter(stringWriter); + t.printStackTrace(writer); + StringBuffer buffer= stringWriter.getBuffer(); + String trace= buffer.toString(); + return trace; + } + + /** + * Prints failures to the standard output + */ + public void printFailures(TestResult result) { + if (result.failureCount() != 0) { + if (result.failureCount() == 1) + writer().println("There was " + result.failureCount() + " failure:"); + else + writer().println("There were " + result.failureCount() + " failures:"); + int i = 1; + for (Iterator e= result.failures(); e.hasNext(); i++) { + TestFailure failure= (TestFailure) e.next(); + writer().print(i + ") " + failure.failedTest()); + Throwable t= failure.thrownException(); + writer().print(getFilteredTrace(failure.thrownException())); + } + } + } + /** + * Prints the header of the report + */ + public void printHeader(TestResult result) { + if (result.wasSuccessful()) { + writer().println(); + writer().print("OK"); + writer().println (" (" + result.runCount() + " tests)"); + + } else { + writer().println(); + writer().println("FAILURES!!!"); + writer().println("Tests run: "+result.runCount()+ + ", Failures: "+result.failureCount()+ + ", Errors: "+result.errorCount()); + } + } + + + private String elapsedTimeAsString(long runTime) { + return NumberFormat.getInstance().format((double)runTime/1000); + } + + @Override + public void addError(Test test, Throwable t) { + writer().print("E"); + } + + @Override + public void addFailure(Test test, AssertionFailedError t) { + writer().print("F"); + } + + @Override + public void endTest(Test test) { + + } + + @Override + public void startTest(Test test) { + writer().print("."); + if (column++ >= 40) { + writer().println(); + column= 0; + } + } + + private PrintStream writer(){ + return writer; + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v1/Assert.java b/students/1158154002/src/main/java/com/coderising/litejunit/v1/Assert.java new file mode 100644 index 0000000000..c94f7bdb8a --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v1/Assert.java @@ -0,0 +1,225 @@ +package com.coderising.litejunit.v1; + +/** + * A set of assert methods. + */ + +public class Assert { + /** + * Protect constructor since it is a static only class + */ + protected Assert() { + } + + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError with the given message. + */ + static public void assertTrue(String message, boolean condition) { + if (!condition) + fail(message); + } + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError. + */ + static public void assertTrue(boolean condition) { + assertTrue(null, condition); + } + /** + * Fails a test with the given message. + */ + static public void fail(String message) { + throw new AssertionFailedError(message); + } + /** + * Fails a test with no message. + */ + static public void fail() { + fail(null); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(String message, Object expected, Object actual) { + if (expected == null && actual == null) + return; + if (expected != null && expected.equals(actual)) + return; + failNotEquals(message, expected, actual); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(Object expected, Object actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, double expected, double actual, double delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Double.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Double(expected), new Double(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) // Because comparison with NaN always returns false + failNotEquals(message, new Double(expected), new Double(actual)); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(double expected, double actual, double delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, float expected, float actual, float delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Float.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Float(expected), new Float(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) + failNotEquals(message, new Float(expected), new Float(actual)); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(float expected, float actual, float delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(String message, long expected, long actual) { + assertEquals(message, new Long(expected), new Long(actual)); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(long expected, long actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(String message, boolean expected, boolean actual) { + assertEquals(message, new Boolean(expected), new Boolean(actual)); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(boolean expected, boolean actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(String message, byte expected, byte actual) { + assertEquals(message, new Byte(expected), new Byte(actual)); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(byte expected, byte actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(String message, char expected, char actual) { + assertEquals(message, new Character(expected), new Character(actual)); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(char expected, char actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(String message, short expected, short actual) { + assertEquals(message, new Short(expected), new Short(actual)); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(short expected, short actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(String message, int expected, int actual) { + assertEquals(message, new Integer(expected), new Integer(actual)); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(int expected, int actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(Object object) { + assertNotNull(null, object); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(String message, Object object) { + assertTrue(message, object != null); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(Object object) { + assertNull(null, object); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(String message, Object object) { + assertTrue(message, object == null); + } + /** + * Asserts that two objects refer to the same object. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertSame(String message, Object expected, Object actual) { + if (expected == actual) + return; + failNotSame(message, expected, actual); + } + /** + * Asserts that two objects refer to the same object. If they are not + * the same an AssertionFailedError is thrown. + */ + static public void assertSame(Object expected, Object actual) { + assertSame(null, expected, actual); + } + + static private void failNotEquals(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected:<"+expected+"> but was:<"+actual+">"); + } + + static private void failNotSame(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected same"); + } +} diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v1/AssertionFailedError.java b/students/1158154002/src/main/java/com/coderising/litejunit/v1/AssertionFailedError.java new file mode 100644 index 0000000000..0d109969de --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v1/AssertionFailedError.java @@ -0,0 +1,13 @@ +package com.coderising.litejunit.v1; + +/** + * Thrown when an assertion failed. + */ +public class AssertionFailedError extends Error { + + public AssertionFailedError () { + } + public AssertionFailedError (String message) { + super (message); + } +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v1/Calculator.java b/students/1158154002/src/main/java/com/coderising/litejunit/v1/Calculator.java new file mode 100644 index 0000000000..828e011938 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v1/Calculator.java @@ -0,0 +1,22 @@ +package com.coderising.litejunit.v1; + +public class Calculator { + + private int result = 0; + public void add(int x){ + result += x; + } + public void subtract(int x){ + result -=x; + } + + public int getResult(){ + return this.result; + } + public static void main(String[] args){ + Calculator calculator = new Calculator(); + calculator.add(10); + calculator.subtract(5); + System.out.println(calculator.getResult()); + } +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v1/CalculatorTest.java b/students/1158154002/src/main/java/com/coderising/litejunit/v1/CalculatorTest.java new file mode 100644 index 0000000000..180ba461e0 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v1/CalculatorTest.java @@ -0,0 +1,69 @@ +package com.coderising.litejunit.v1; + +public class CalculatorTest extends TestCase { + public CalculatorTest(String name) { + super(name); + + } + + Calculator calculator = null; + + public void setUp() { + calculator = new Calculator(); + } + + public void tearDown() { + calculator = null; + } + + public void testAdd() { + + calculator.add(10); + assertEquals(10, calculator.getResult()); + } + + public void testSubtract() { + calculator.add(10); + calculator.subtract(5); + assertEquals(5, calculator.getResult()); + } + + public static void main(String[] args) { + TestSuite ts = new TestSuite(CalculatorTest.class); + TestResult tr = new TestResult(); + ts.run(tr); + System.out.println(tr.wasSuccessful()); + for (TestFailure failure : tr.failures) { + System.err.println(failure); + } + + /*{ + TestCase tc1 = new CalculatorTest("testAdd"){ + protected void runTest() { + testAdd(); + } + }; + + TestCase tc2 = new CalculatorTest("testSubtract"){ + protected void runTest() { + testSubtract(); + } + }; + tc1.run(); + tc2.run(); + } + + + TestSuite ts = new TestSuite(); + ts.addTest(new CalculatorTest("testAdd")); + ts.addTest(new CalculatorTest("testSubtract")); + + + { + TestCase tc1 = new CalculatorTest("test1"); + TestCase tc2 = new CalculatorTest("test2"); + tc1.run(); + tc2.run(); + }*/ + } +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v1/Test.java b/students/1158154002/src/main/java/com/coderising/litejunit/v1/Test.java new file mode 100644 index 0000000000..4b9e496e33 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v1/Test.java @@ -0,0 +1,6 @@ +package com.coderising.litejunit.v1; + +public interface Test { + public abstract int countTestCases(); + public void run(TestResult tr); +} diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v1/TestCase.java b/students/1158154002/src/main/java/com/coderising/litejunit/v1/TestCase.java new file mode 100644 index 0000000000..62a505af92 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v1/TestCase.java @@ -0,0 +1,59 @@ +package com.coderising.litejunit.v1; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +public abstract class TestCase extends Assert implements Test { + private String name; + + public TestCase(String name) { + this.name = name; + } + + public int countTestCases() { + return 1; + } + + protected void runTest() throws Throwable{ + Method runMethod= null; + try { + runMethod= getClass().getMethod(name, null); + } catch (NoSuchMethodException e) { + fail("Method \""+name+"\" not found"); + } + if (!Modifier.isPublic(runMethod.getModifiers())) { + fail("Method \""+name+"\" should be public"); + } + + try { + runMethod.invoke(this, new Class[0]); + } + catch (InvocationTargetException e) { + e.fillInStackTrace(); + throw e.getTargetException(); + } + catch (IllegalAccessException e) { + e.fillInStackTrace(); + throw e; + } + } + + protected void setUp() { + } + + protected void tearDown() { + } + + public void run(TestResult tr) { + tr.run(this); + } + public void doRun() throws Throwable{ + setUp(); + try{ + runTest(); + } + finally{ + tearDown(); + } + } +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v1/TestFailure.java b/students/1158154002/src/main/java/com/coderising/litejunit/v1/TestFailure.java new file mode 100644 index 0000000000..de314e894b --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v1/TestFailure.java @@ -0,0 +1,39 @@ +package com.coderising.litejunit.v1; + +/** + * A TestFailure collects a failed test together with + * the caught exception. + * @see TestResult + */ +public class TestFailure { + protected Test failedTest; + protected Throwable thrownException; + + /** + * Constructs a TestFailure with the given test and exception. + */ + public TestFailure(Test failedTest, Throwable thrownException) { + this.failedTest= failedTest; + this.thrownException= thrownException; + } + /** + * Gets the failed test. + */ + public Test failedTest() { + return failedTest; + } + /** + * Gets the thrown exception. + */ + public Throwable thrownException() { + return thrownException; + } + /** + * Returns a short description of the failure. + */ + public String toString() { + StringBuffer buffer= new StringBuffer(); + buffer.append(failedTest+": "+thrownException.getMessage()); + return buffer.toString(); + } +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v1/TestSuite.java b/students/1158154002/src/main/java/com/coderising/litejunit/v1/TestSuite.java new file mode 100644 index 0000000000..bd01327df0 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v1/TestSuite.java @@ -0,0 +1,133 @@ +package com.coderising.litejunit.v1; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Vector; + +public class TestSuite extends Assert implements Test { + private List tests = new ArrayList<>(10); + private String name; + + public TestSuite() { + + } + + public TestSuite(final Class theClass) { + this.name = theClass.getName(); + Constructor constructor = null; + try { + constructor = getConstructor(theClass); + } catch (NoSuchMethodException e) { + addTest(warning("Class " + theClass.getName() + " has no public constructor TestCase(String name)")); + return; + } + + if (!Modifier.isPublic(theClass.getModifiers())) { + addTest(warning("Class " + theClass.getName() + " is not public")); + return; + } + + Vector names = new Vector<>(); + Method[] methods = theClass.getDeclaredMethods(); + for (int i = 0; i < methods.length; i++) { + addTestMethod(methods[i], names, constructor); + } + + if (tests.size() == 0) + addTest(warning("No tests found in " + theClass.getName())); + } + + private Constructor getConstructor(Class theClass) throws NoSuchMethodException { + Class[] args = { String.class }; + return theClass.getConstructor(args); + } + + private void addTestMethod(Method m, Vector names, Constructor constructor) { + String name = m.getName(); + if (names.contains(name)) + return; + if (isPublicTestMethod(m)) { + names.addElement(name); + + Object[] args = new Object[] { name }; + try { + addTest((Test) constructor.newInstance(args)); + } catch (InstantiationException e) { + addTest(warning("Cannot instantiate test case: " + name + " (" + exceptionToString(e) + ")")); + } catch (InvocationTargetException e) { + addTest(warning( + "Exception in constructor: " + name + " (" + exceptionToString(e.getTargetException()) + ")")); + } catch (IllegalAccessException e) { + addTest(warning("Cannot access test case: " + name + " (" + exceptionToString(e) + ")")); + } + + } else { // almost a test method + if (isTestMethod(m)) + addTest(warning("Test method isn't public: " + m.getName())); + } + } + + private boolean isPublicTestMethod(Method m) { + return isTestMethod(m) && Modifier.isPublic(m.getModifiers()); + } + + private boolean isTestMethod(Method m) { + String name = m.getName(); + Class[] parameters = m.getParameterTypes(); + Class returnType = m.getReturnType(); + return parameters.length == 0 && name.startsWith("test") && returnType.equals(Void.TYPE); + } + + public void addTest(Test test) { + tests.add(test); + } + + private Test warning(final String message) { + return new TestCase("warning") { + public void doRun() { + fail(message); + } + }; + } + + private String exceptionToString(Throwable t) { + StringWriter stringWriter = new StringWriter(); + PrintWriter writer = new PrintWriter(stringWriter); + t.printStackTrace(writer); + return stringWriter.toString(); + + } + + @Override + public void run(TestResult result) { + for (Iterator e = tests(); e.hasNext();) { + if (result.shouldStop()) { + break; + } + Test test = (Test) e.next(); + test.run(result); + } + + } + + public int countTestCases() { + int count = 0; + + for (Iterator e = tests(); e.hasNext();) { + Test test = e.next(); + count = count + test.countTestCases(); + } + return count; + } + + public Iterator tests() { + return tests.iterator(); + } +} diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v2/Assert.java b/students/1158154002/src/main/java/com/coderising/litejunit/v2/Assert.java new file mode 100644 index 0000000000..b0a6191fec --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v2/Assert.java @@ -0,0 +1,243 @@ +package com.coderising.litejunit.v2; + +/** +* A set of assert methods. +*/ + +public class Assert { + /** + * Protect constructor since it is a static only class + */ + protected Assert() { + } + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError with the given message. + * @deprecated use assertTrue + */ + /*static public void assert(String message, boolean condition) { + if (!condition) + fail(message); + }*/ + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError. + * @deprecated use assertTrue + * + */ + /*static public void assert(boolean condition) { + assert(null, condition); + } +*/ + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError with the given message. + */ + static public void assertTrue(String message, boolean condition) { + if (!condition) + fail(message); + } + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError. + */ + static public void assertTrue(boolean condition) { + assertTrue(null, condition); + } + /** + * Fails a test with the given message. + */ + static public void fail(String message) { + throw new AssertionFailedError(message); + } + /** + * Fails a test with no message. + */ + static public void fail() { + fail(null); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(String message, Object expected, Object actual) { + if (expected == null && actual == null) + return; + if (expected != null && expected.equals(actual)) + return; + failNotEquals(message, expected, actual); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(Object expected, Object actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, double expected, double actual, double delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Double.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Double(expected), new Double(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) // Because comparison with NaN always returns false + failNotEquals(message, new Double(expected), new Double(actual)); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(double expected, double actual, double delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, float expected, float actual, float delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Float.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Float(expected), new Float(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) + failNotEquals(message, new Float(expected), new Float(actual)); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(float expected, float actual, float delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(String message, long expected, long actual) { + assertEquals(message, new Long(expected), new Long(actual)); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(long expected, long actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(String message, boolean expected, boolean actual) { + assertEquals(message, new Boolean(expected), new Boolean(actual)); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(boolean expected, boolean actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(String message, byte expected, byte actual) { + assertEquals(message, new Byte(expected), new Byte(actual)); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(byte expected, byte actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(String message, char expected, char actual) { + assertEquals(message, new Character(expected), new Character(actual)); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(char expected, char actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(String message, short expected, short actual) { + assertEquals(message, new Short(expected), new Short(actual)); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(short expected, short actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(String message, int expected, int actual) { + assertEquals(message, new Integer(expected), new Integer(actual)); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(int expected, int actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(Object object) { + assertNotNull(null, object); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(String message, Object object) { + assertTrue(message, object != null); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(Object object) { + assertNull(null, object); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(String message, Object object) { + assertTrue(message, object == null); + } + /** + * Asserts that two objects refer to the same object. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertSame(String message, Object expected, Object actual) { + if (expected == actual) + return; + failNotSame(message, expected, actual); + } + /** + * Asserts that two objects refer to the same object. If they are not + * the same an AssertionFailedError is thrown. + */ + static public void assertSame(Object expected, Object actual) { + assertSame(null, expected, actual); + } + + static private void failNotEquals(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected:<"+expected+"> but was:<"+actual+">"); + } + + static private void failNotSame(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected same"); + } +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v2/AssertionFailedError.java b/students/1158154002/src/main/java/com/coderising/litejunit/v2/AssertionFailedError.java new file mode 100644 index 0000000000..fbfdb42df3 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v2/AssertionFailedError.java @@ -0,0 +1,13 @@ +package com.coderising.litejunit.v2; + +/** + * Thrown when an assertion failed. + */ +public class AssertionFailedError extends Error { + + public AssertionFailedError () { + } + public AssertionFailedError (String message) { + super (message); + } +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v2/Protectable.java b/students/1158154002/src/main/java/com/coderising/litejunit/v2/Protectable.java new file mode 100644 index 0000000000..1b5b177e5f --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v2/Protectable.java @@ -0,0 +1,14 @@ +package com.coderising.litejunit.v2; + +/** + * A Protectable can be run and can throw a Throwable. + * + * @see TestResult + */ +public interface Protectable { + + /** + * Run the the following method protected. + */ + public abstract void protect() throws Throwable; +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v2/Test.java b/students/1158154002/src/main/java/com/coderising/litejunit/v2/Test.java new file mode 100644 index 0000000000..0dcdcb0726 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v2/Test.java @@ -0,0 +1,6 @@ +package com.coderising.litejunit.v2; + +public interface Test { + public abstract int countTestCases(); + public void run(TestResult tr); +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v2/TestCase.java b/students/1158154002/src/main/java/com/coderising/litejunit/v2/TestCase.java new file mode 100644 index 0000000000..b282ff5985 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v2/TestCase.java @@ -0,0 +1,64 @@ +package com.coderising.litejunit.v2; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + + + +public abstract class TestCase extends Assert implements Test { + private String name; + + + public TestCase(String name) { + this.name = name; + } + + + public int countTestCases() { + return 1; + } + + protected void runTest() throws Throwable{ + Method runMethod= null; + try { + runMethod= getClass().getMethod(name, null); + } catch (NoSuchMethodException e) { + fail("Method \""+name+"\" not found"); + } + if (!Modifier.isPublic(runMethod.getModifiers())) { + fail("Method \""+name+"\" should be public"); + } + + try { + runMethod.invoke(this, new Class[0]); + } + catch (InvocationTargetException e) { + e.fillInStackTrace(); + throw e.getTargetException(); + } + catch (IllegalAccessException e) { + e.fillInStackTrace(); + throw e; + } + } + + protected void setUp() { + } + + protected void tearDown() { + } + + public void run(TestResult tr) { + tr.run(this); + } + public void doRun() throws Throwable{ + setUp(); + try{ + runTest(); + } + finally{ + tearDown(); + } + } +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v2/TestFailure.java b/students/1158154002/src/main/java/com/coderising/litejunit/v2/TestFailure.java new file mode 100644 index 0000000000..ddacec71fd --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v2/TestFailure.java @@ -0,0 +1,39 @@ +package com.coderising.litejunit.v2; + +/** + * A TestFailure collects a failed test together with + * the caught exception. + * @see TestResult + */ +public class TestFailure { + protected Test failedTest; + protected Throwable thrownException; + + /** + * Constructs a TestFailure with the given test and exception. + */ + public TestFailure(Test failedTest, Throwable thrownException) { + this.failedTest= failedTest; + this.thrownException= thrownException; + } + /** + * Gets the failed test. + */ + public Test failedTest() { + return failedTest; + } + /** + * Gets the thrown exception. + */ + public Throwable thrownException() { + return thrownException; + } + /** + * Returns a short description of the failure. + */ + public String toString() { + StringBuffer buffer= new StringBuffer(); + buffer.append(failedTest+": "+thrownException.getMessage()); + return buffer.toString(); + } +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v2/TestListener.java b/students/1158154002/src/main/java/com/coderising/litejunit/v2/TestListener.java new file mode 100644 index 0000000000..7e765d4066 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v2/TestListener.java @@ -0,0 +1,15 @@ +package com.coderising.litejunit.v2; + +/** + * A Listener for test progress + */ +public interface TestListener { + + public void addError(Test test, Throwable t); + + public void addFailure(Test test, AssertionFailedError t); + + public void endTest(Test test); + + public void startTest(Test test); +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v2/TestSuite.java b/students/1158154002/src/main/java/com/coderising/litejunit/v2/TestSuite.java new file mode 100644 index 0000000000..11a6094ed1 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v2/TestSuite.java @@ -0,0 +1,133 @@ +package com.coderising.litejunit.v2; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; + +import java.util.Iterator; +import java.util.List; +import java.util.Vector; + + +public class TestSuite extends Assert implements Test { + private List tests= new ArrayList<>(10); + private String name; + public TestSuite(){ + + } + public TestSuite(final Class theClass) { + this.name= theClass.getName(); + Constructor constructor= null; + try { + constructor= getConstructor(theClass); + } catch (NoSuchMethodException e) { + addTest(warning("Class "+theClass.getName()+" has no public constructor TestCase(String name)")); + return; + } + + if (!Modifier.isPublic(theClass.getModifiers())) { + addTest(warning("Class "+theClass.getName()+" is not public")); + return; + } + + Vector names= new Vector<>(); + Method[] methods= theClass.getDeclaredMethods(); + for (int i= 0; i < methods.length; i++) { + addTestMethod(methods[i], names, constructor); + } + + if (tests.size() == 0) + addTest(warning("No tests found in "+theClass.getName())); + } + + public TestSuite(String name) { + this.name = name; + } + private Constructor getConstructor(Class theClass) throws NoSuchMethodException { + Class[] args= { String.class }; + return theClass.getConstructor(args); + } + private void addTestMethod(Method m, Vector names, Constructor constructor) { + String name= m.getName(); + if (names.contains(name)) + return; + if (isPublicTestMethod(m)) { + names.addElement(name); + + Object[] args= new Object[]{name}; + try { + addTest((Test)constructor.newInstance(args)); + } catch (InstantiationException e) { + addTest(warning("Cannot instantiate test case: "+name+" ("+exceptionToString(e)+")")); + } catch (InvocationTargetException e) { + addTest(warning("Exception in constructor: "+name+" ("+exceptionToString(e.getTargetException())+")")); + } catch (IllegalAccessException e) { + addTest(warning("Cannot access test case: "+name+" ("+exceptionToString(e)+")")); + } + + } else { // almost a test method + if (isTestMethod(m)) + addTest(warning("Test method isn't public: "+m.getName())); + } + } + private boolean isPublicTestMethod(Method m) { + return isTestMethod(m) && Modifier.isPublic(m.getModifiers()); + } + private boolean isTestMethod(Method m) { + String name= m.getName(); + Class[] parameters= m.getParameterTypes(); + Class returnType= m.getReturnType(); + return parameters.length == 0 && name.startsWith("test") && returnType.equals(Void.TYPE); + } + public void addTest(Test test) { + tests.add(test); + } + public void addTestSuite(Class testClass) { + addTest(new TestSuite(testClass)); + } + private Test warning(final String message) { + return new TestCase("warning") { + public void doRun() { + fail(message); + } + }; + } + private String exceptionToString(Throwable t) { + StringWriter stringWriter= new StringWriter(); + PrintWriter writer= new PrintWriter(stringWriter); + t.printStackTrace(writer); + return stringWriter.toString(); + + } + + + + @Override + public void run(TestResult result) { + for (Iterator e= tests(); e.hasNext(); ) { + if (result.shouldStop() ){ + break; + } + Test test= (Test)e.next(); + test.run(result); + } + + } + + public int countTestCases() { + int count= 0; + + for (Iterator e= tests(); e.hasNext(); ) { + Test test= e.next(); + count= count + test.countTestCases(); + } + return count; + } + public Iterator tests() { + return tests.iterator(); + } +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v2/runner/BaseTestRunner.java b/students/1158154002/src/main/java/com/coderising/litejunit/v2/runner/BaseTestRunner.java new file mode 100644 index 0000000000..bbd63e10a0 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v2/runner/BaseTestRunner.java @@ -0,0 +1,85 @@ +package com.coderising.litejunit.v2.runner; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.text.NumberFormat; + +import com.coderising.litejunit.v2.Test; +import com.coderising.litejunit.v2.TestListener; +import com.coderising.litejunit.v2.TestSuite; + + +public abstract class BaseTestRunner implements TestListener { + public static final String SUITE_METHODNAME= "suite"; + /** + * Returns a filtered stack trace + */ + public static String getFilteredTrace(Throwable t) { + StringWriter stringWriter= new StringWriter(); + PrintWriter writer= new PrintWriter(stringWriter); + t.printStackTrace(writer); + StringBuffer buffer= stringWriter.getBuffer(); + String trace= buffer.toString(); + return trace; + //return BaseTestRunner.filterStack(trace); + } + + public Test getTest(String suiteClassName) { + if (suiteClassName.length() <= 0) { + return null; + } + Class testClass= null; + try { + testClass= loadSuiteClass(suiteClassName); + } catch (ClassNotFoundException e) { + String clazz= e.getMessage(); + if (clazz == null) + clazz= suiteClassName; + runFailed("Class not found \""+clazz+"\""); + return null; + } catch(Exception e) { + runFailed("Error: "+e.toString()); + return null; + } + Method suiteMethod= null; + try { + suiteMethod= testClass.getMethod(SUITE_METHODNAME, new Class[0]); + } catch(Exception e) { + // try to extract a test suite automatically + //clearStatus(); + return new TestSuite(testClass); + } + Test test= null; + try { + test= (Test)suiteMethod.invoke(null, new Class[0]); // static method + if (test == null) + return test; + } + catch (InvocationTargetException e) { + runFailed("Failed to invoke suite():" + e.getTargetException().toString()); + return null; + } + catch (IllegalAccessException e) { + runFailed("Failed to invoke suite():" + e.toString()); + return null; + } + + //clearStatus(); + return test; + } + protected Class loadSuiteClass(String suiteClassName) throws ClassNotFoundException { + + //TODO + return Class.forName(suiteClassName); + + + //return getLoader().load(suiteClassName); + } + protected abstract void runFailed(String message); + + public String elapsedTimeAsString(long runTime) { + return NumberFormat.getInstance().format((double)runTime/1000); + } +} diff --git a/students/1158154002/src/main/java/com/coderising/litejunit/v2/textui/TestRunner.java b/students/1158154002/src/main/java/com/coderising/litejunit/v2/textui/TestRunner.java new file mode 100644 index 0000000000..01b4c20a4c --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/litejunit/v2/textui/TestRunner.java @@ -0,0 +1,196 @@ +package com.coderising.litejunit.v2.textui; + +import java.io.PrintStream; +import java.util.Iterator; + +import com.coderising.litejunit.v2.AssertionFailedError; +import com.coderising.litejunit.v2.Test; +import com.coderising.litejunit.v2.TestFailure; +import com.coderising.litejunit.v2.TestResult; +import com.coderising.litejunit.v2.TestSuite; +import com.coderising.litejunit.v2.runner.BaseTestRunner; + + +public class TestRunner extends BaseTestRunner { + PrintStream writer= System.out; + int column= 0; + + /** + * Constructs a TestRunner. + */ + public TestRunner() { + } + + + /** + * Always use the StandardTestSuiteLoader. Overridden from + * BaseTestRunner. + */ + /*public TestSuiteLoader getLoader() { + return new StandardTestSuiteLoader(); + }*/ + + public synchronized void addError(Test test, Throwable t) { + writer().print("E"); + } + + public synchronized void addFailure(Test test, AssertionFailedError t) { + writer().print("F"); + } + + public TestResult doRun(Test suite) { + TestResult result= new TestResult(); + result.addListener(this); + long startTime= System.currentTimeMillis(); + suite.run(result); + long endTime= System.currentTimeMillis(); + long runTime= endTime-startTime; + writer().println(); + writer().println("Time: "+elapsedTimeAsString(runTime)); + print(result); + + writer().println(); + + + return result; + } + + + + public synchronized void startTest(Test test) { + writer().print("."); + if (column++ >= 40) { + writer().println(); + column= 0; + } + } + + public void endTest(Test test) { + } + + public static void main(String args[]) { + TestRunner testRunner= new TestRunner(); + try { + TestResult r= testRunner.start(args); + if (!r.wasSuccessful()) + System.exit(-1); + System.exit(0); + } catch(Exception e) { + System.err.println(e.getMessage()); + System.exit(-2); + } + } + /** + * Prints failures to the standard output + */ + public synchronized void print(TestResult result) { + printErrors(result); + printFailures(result); + printHeader(result); + } + /** + * Prints the errors to the standard output + */ + public void printErrors(TestResult result) { + if (result.errorCount() != 0) { + if (result.errorCount() == 1) + writer().println("There was "+result.errorCount()+" error:"); + else + writer().println("There were "+result.errorCount()+" errors:"); + + int i= 1; + for (Iterator e= result.errors(); e.hasNext(); i++) { + TestFailure failure= e.next(); + writer().println(i+") "+failure.failedTest()); + writer().print(getFilteredTrace(failure.thrownException())); + } + } + } + /** + * Prints failures to the standard output + */ + public void printFailures(TestResult result) { + if (result.failureCount() != 0) { + if (result.failureCount() == 1) + writer().println("There was " + result.failureCount() + " failure:"); + else + writer().println("There were " + result.failureCount() + " failures:"); + int i = 1; + for (Iterator e= result.failures(); e.hasNext(); i++) { + TestFailure failure= (TestFailure) e.next(); + writer().print(i + ") " + failure.failedTest()); + Throwable t= failure.thrownException(); + writer().print(getFilteredTrace(failure.thrownException())); + } + } + } + /** + * Prints the header of the report + */ + public void printHeader(TestResult result) { + if (result.wasSuccessful()) { + writer().println(); + writer().print("OK"); + writer().println (" (" + result.runCount() + " tests)"); + + } else { + writer().println(); + writer().println("FAILURES!!!"); + writer().println("Tests run: "+result.runCount()+ + ", Failures: "+result.failureCount()+ + ", Errors: "+result.errorCount()); + } + } + + + /** + * Starts a test run. Analyzes the command line arguments + * and runs the given test suite. + */ + protected TestResult start(String args[]) throws Exception { + if(args.length == 0){ + throw new Exception("Usage: TestRunner testCaseName"); + } + String testCase= args[0]; + + try { + Test suite= getTest(testCase); + return doRun(suite); + } + catch(Exception e) { + throw new Exception("Could not create and run test suite: "+e); + } + } + + protected void runFailed(String message) { + System.err.println(message); + System.exit(-1); + } + + /** + * Runs a suite extracted from a TestCase subclass. + */ + static public void run(Class testClass) { + run(new TestSuite(testClass)); + } + /** + * Runs a single test and collects its results. + * This method can be used to start a test run + * from your program. + *
+	 * public static void main (String[] args) {
+	 *     test.textui.TestRunner.run(suite());
+	 * }
+	 * 
+ */ + static public void run(Test suite) { + TestRunner aTestRunner= new TestRunner(); + aTestRunner.doRun(suite); + } + + protected PrintStream writer() { + return writer; + } + + +} \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/ood/ocp/DateUtil.java b/students/1158154002/src/main/java/com/coderising/ood/ocp/DateUtil.java new file mode 100644 index 0000000000..9471308b5b --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/ood/ocp/DateUtil.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp; + +import java.util.Date; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return new Date().toString(); + } +} diff --git a/students/1158154002/src/main/java/com/coderising/ood/ocp/EmailLog.java b/students/1158154002/src/main/java/com/coderising/ood/ocp/EmailLog.java new file mode 100644 index 0000000000..197f08d2db --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/ood/ocp/EmailLog.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class EmailLog implements LogMethod{ + + @Override + public void send(String msg) { + System.out.println("Email send "+msg); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/ood/ocp/LogMethod.java b/students/1158154002/src/main/java/com/coderising/ood/ocp/LogMethod.java new file mode 100644 index 0000000000..f813444cd8 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/ood/ocp/LogMethod.java @@ -0,0 +1,5 @@ +package com.coderising.ood.ocp; + +public interface LogMethod { + void send(String msg); +} diff --git a/students/1158154002/src/main/java/com/coderising/ood/ocp/LogType.java b/students/1158154002/src/main/java/com/coderising/ood/ocp/LogType.java new file mode 100644 index 0000000000..ed2b6fc7e6 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/ood/ocp/LogType.java @@ -0,0 +1,5 @@ +package com.coderising.ood.ocp; + +public interface LogType { + String getMsg(String msg); +} diff --git a/students/1158154002/src/main/java/com/coderising/ood/ocp/Logger.java b/students/1158154002/src/main/java/com/coderising/ood/ocp/Logger.java new file mode 100644 index 0000000000..09fae40095 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/ood/ocp/Logger.java @@ -0,0 +1,21 @@ +package com.coderising.ood.ocp; + +public class Logger { + + LogType type; + LogMethod method; + + public Logger(LogType logType, LogMethod logMethod) { + this.type = logType; + this.method = logMethod; + } + + public void log(String msg) { + method.send(type.getMsg(msg)); + } + + public static void main(String[] args) { + Logger logger=new Logger(new RawLog(), new EmailLog()); + logger.log("hello world !"); + } +} diff --git a/students/1158154002/src/main/java/com/coderising/ood/ocp/PrintLog.java b/students/1158154002/src/main/java/com/coderising/ood/ocp/PrintLog.java new file mode 100644 index 0000000000..6f1b379707 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/ood/ocp/PrintLog.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class PrintLog implements LogMethod{ + + @Override + public void send(String msg) { + System.out.println("Print Log "+msg); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/ood/ocp/RawLog.java b/students/1158154002/src/main/java/com/coderising/ood/ocp/RawLog.java new file mode 100644 index 0000000000..88f1811f2e --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/ood/ocp/RawLog.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class RawLog implements LogType { + + @Override + public String getMsg(String msg) { + return msg; + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/ood/ocp/RawLogWithDate.java b/students/1158154002/src/main/java/com/coderising/ood/ocp/RawLogWithDate.java new file mode 100644 index 0000000000..c791fe142d --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/ood/ocp/RawLogWithDate.java @@ -0,0 +1,12 @@ +package com.coderising.ood.ocp; + +public class RawLogWithDate implements LogType { + + @Override + public String getMsg(String msg) { + String txtDate = DateUtil.getCurrentDateAsString(); + msg = txtDate + ": " + msg; + return msg; + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/ood/ocp/SmsLog.java b/students/1158154002/src/main/java/com/coderising/ood/ocp/SmsLog.java new file mode 100644 index 0000000000..8bca6372ba --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/ood/ocp/SmsLog.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class SmsLog implements LogMethod{ + + @Override + public void send(String msg) { + System.out.println("SMS send "+msg); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/ood/srp/BaseFileLoader.java b/students/1158154002/src/main/java/com/coderising/ood/srp/BaseFileLoader.java new file mode 100644 index 0000000000..8294670ffd --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/ood/srp/BaseFileLoader.java @@ -0,0 +1,10 @@ +package com.coderising.ood.srp; + +import java.io.File; +import java.util.Map; + +import com.coderising.ood.srp.api.FileLoader; + +public abstract class BaseFileLoader implements FileLoader { + public abstract Map readFile(File file); +} diff --git a/students/1158154002/src/main/java/com/coderising/ood/srp/Configuration.java b/students/1158154002/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..927c7155cc --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/1158154002/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..868a03ff83 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/1158154002/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/1158154002/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..65383e4dba --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/1158154002/src/main/java/com/coderising/ood/srp/FileLoaderImpl.java b/students/1158154002/src/main/java/com/coderising/ood/srp/FileLoaderImpl.java new file mode 100644 index 0000000000..75c0bf4954 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/ood/srp/FileLoaderImpl.java @@ -0,0 +1,39 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public class FileLoaderImpl extends BaseFileLoader{ + + @Override + public Map readFile(File file) { + BufferedReader br = null; + Map map=new HashMap(); + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + map.put("productID", data[0]); + map.put("productDesc", data[1]); + + System.out.println("产品ID = " + data[0] + "\n"); + System.out.println("产品描述 = " + data[1] + "\n"); + + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + br.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + return map; + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/ood/srp/HandlerEmail.java b/students/1158154002/src/main/java/com/coderising/ood/srp/HandlerEmail.java new file mode 100644 index 0000000000..f9ec8061e6 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/ood/srp/HandlerEmail.java @@ -0,0 +1,55 @@ +package com.coderising.ood.srp; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.coderising.ood.srp.model.Constant; +import com.coderising.ood.srp.model.Mail; + +public class HandlerEmail { + + protected String sendMailQuery; + + protected Configuration config = new Configuration(); + + protected Mail mail=new Mail(); + + protected FileLoaderImpl fileLoader=new FileLoaderImpl(); + + public HandlerEmail(File file) { + Map map=fileLoader.readFile(file); + mail.setProductDesc((String)map.get("productDesc")); + mail.setProductID((String)map.get("productID")); + mail.setSmtpHost(config.getProperty(ConfigurationKeys.SMTP_SERVER)); + mail.setAltSmtpHost(config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER)); + mail.setFromAddress(config.getProperty(ConfigurationKeys.EMAIL_ADMIN)); + + } + + protected void setLoadQuery() throws Exception { + sendMailQuery = "Select name from subscriptions " + "where product_id= '" + mail.getProductID() + "' " + + "and send_mail=1 "; + + System.out.println("loadQuery set"); + } + + protected void setMessage(HashMap userInfo) throws IOException { + String name = (String) userInfo.get(Constant.NAME_KEY); + mail.setSubject("您关注的产品降价了"); + mail.setMessage("尊敬的 " + name + ", 您关注的产品 " + mail.getProductDesc() + " 降价了,欢迎购买!"); + } + + protected void configureEMail(HashMap userInfo) throws IOException { + mail.setToAddress((String) userInfo.get(Constant.EMAIL_KEY)); + if (mail.getToAddress().length() > 0) + setMessage(userInfo); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/1158154002/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..373f3ee306 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/1158154002/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/1158154002/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..91a5c0328c --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,63 @@ +package com.coderising.ood.srp; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + protected HandlerEmail hanlder; + + public static void main(String[] args) throws Exception { + + File f = new File( + "D:\\mygit\\coding2017\\students\\1158154002\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + hanlder = new HandlerEmail(file); + hanlder.setLoadQuery(); + sendEMails(mailDebug, hanlder.loadMailingList()); + + } + + protected void sendEMails(boolean debug, List mailingList) throws IOException { + + System.out.println("开始发送邮件"); + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + hanlder.configureEMail((HashMap) iter.next()); + try { + if (hanlder.mail.getToAddress().length() > 0) + MailUtil.sendEmail(hanlder.mail.getToAddress(), hanlder.mail.getFromAddress(), hanlder.mail.getSubject(), + hanlder.mail.getMessage(), hanlder.mail.getSmtpHost(), debug); + } catch (Exception e) { + + try { + MailUtil.sendEmail(hanlder.mail.getToAddress(), hanlder.mail.getFromAddress(), hanlder.mail.getSubject(), + hanlder.mail.getMessage(), hanlder.mail.getAltSmtpHost(), debug); + + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + } + + else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/1158154002/src/main/java/com/coderising/ood/srp/api/FileLoader.java b/students/1158154002/src/main/java/com/coderising/ood/srp/api/FileLoader.java new file mode 100644 index 0000000000..d864d5e74e --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/ood/srp/api/FileLoader.java @@ -0,0 +1,8 @@ +package com.coderising.ood.srp.api; + +import java.io.File; +import java.util.Map; + +public interface FileLoader { + Map readFile(File file); +} diff --git a/students/1158154002/src/main/java/com/coderising/ood/srp/model/Constant.java b/students/1158154002/src/main/java/com/coderising/ood/srp/model/Constant.java new file mode 100644 index 0000000000..ad6258531e --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/ood/srp/model/Constant.java @@ -0,0 +1,6 @@ +package com.coderising.ood.srp.model; + +public class Constant { + public static final String NAME_KEY = "NAME"; + public static final String EMAIL_KEY = "EMAIL"; +} diff --git a/students/1158154002/src/main/java/com/coderising/ood/srp/model/Mail.java b/students/1158154002/src/main/java/com/coderising/ood/srp/model/Mail.java new file mode 100644 index 0000000000..c6715e4385 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/ood/srp/model/Mail.java @@ -0,0 +1,63 @@ +package com.coderising.ood.srp.model; + +public class Mail { + private String smtpHost; + private String altSmtpHost; + private String fromAddress; + private String toAddress; + private String subject; + private String message; + private String productID; + private String productDesc; + + public String getSmtpHost() { + return smtpHost; + } + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + public String getAltSmtpHost() { + return altSmtpHost; + } + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + public String getFromAddress() { + return fromAddress; + } + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + public String getToAddress() { + return toAddress; + } + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + public String getSubject() { + return subject; + } + public void setSubject(String subject) { + this.subject = subject; + } + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + public String getProductID() { + return productID; + } + public void setProductID(String productID) { + this.productID = productID; + } + public String getProductDesc() { + return productDesc; + } + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + + +} diff --git a/students/1158154002/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/1158154002/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/payroll/AddCommissionEmployeeTransaction.java b/students/1158154002/src/main/java/com/coderising/payroll/AddCommissionEmployeeTransaction.java new file mode 100644 index 0000000000..45b30ab31b --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/AddCommissionEmployeeTransaction.java @@ -0,0 +1,28 @@ +package com.coderising.payroll; + +import com.coderising.payroll.api.AddEmployeeTransaction; +import com.coderising.payroll.api.Affiliation; +import com.coderising.payroll.api.PaymentClassification; +import com.coderising.payroll.api.PaymentMethod; +import com.coderising.payroll.api.PaymentSchedule; + +public class AddCommissionEmployeeTransaction extends AddEmployeeTransaction{ + private double rate; + private double salary; + public AddCommissionEmployeeTransaction(String name, String address, PaymentMethod paymentMethod, + Affiliation affiliation) { + super(name, address, paymentMethod, affiliation); + this.rate=rate; + } + + @Override + public PaymentClassification getClassification() { + return new CommissionClassification(rate,salary); + } + + @Override + public PaymentSchedule getSchedule() { + return new WeeklySchedule(); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/AddEmployeeTransaction.java b/students/1158154002/src/main/java/com/coderising/payroll/AddEmployeeTransaction.java new file mode 100644 index 0000000000..9a5ed30b31 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/AddEmployeeTransaction.java @@ -0,0 +1,37 @@ +package com.coderising.payroll; + +import com.coderising.payroll.api.Affiliation; +import com.coderising.payroll.api.PaymentClassification; +import com.coderising.payroll.api.PaymentMethod; +import com.coderising.payroll.api.PaymentSchedule; + +public abstract class AddEmployeeTransaction { + private String name; + private String address; + private PaymentMethod paymentMethod; + private Affiliation affiliation; + + + public AddEmployeeTransaction(String name, String address, PaymentMethod paymentMethod, Affiliation affiliation) { + super(); + this.name = name; + this.address = address; + this.paymentMethod = paymentMethod; + this.affiliation = affiliation; + } + + public abstract PaymentClassification getClassification(); + + public abstract PaymentSchedule getSchedule(); + + public void execute(){ + PaymentClassification pc=getClassification(); + PaymentSchedule ps=getSchedule(); + Employee e=new Employee(name, address); + e.setClassification(pc); + e.setSchedule(ps); + e.setPaymentMethod(paymentMethod); + e.setAffiliation(affiliation); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/AddHourlyEmployeeTransaction.java b/students/1158154002/src/main/java/com/coderising/payroll/AddHourlyEmployeeTransaction.java new file mode 100644 index 0000000000..c7b92eafd3 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/AddHourlyEmployeeTransaction.java @@ -0,0 +1,27 @@ +package com.coderising.payroll; + +import com.coderising.payroll.api.AddEmployeeTransaction; +import com.coderising.payroll.api.Affiliation; +import com.coderising.payroll.api.PaymentClassification; +import com.coderising.payroll.api.PaymentMethod; +import com.coderising.payroll.api.PaymentSchedule; + +public class AddHourlyEmployeeTransaction extends AddEmployeeTransaction{ + private double rate; + public AddHourlyEmployeeTransaction(String name, String address, PaymentMethod paymentMethod, + Affiliation affiliation) { + super(name, address, paymentMethod, affiliation); + this.rate=rate; + } + + @Override + public PaymentClassification getClassification() { + return new HourlyClassification(rate); + } + + @Override + public PaymentSchedule getSchedule() { + return new WeeklySchedule(); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/AddSalariedEmployeeTransaction.java b/students/1158154002/src/main/java/com/coderising/payroll/AddSalariedEmployeeTransaction.java new file mode 100644 index 0000000000..4edfbd0d1e --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/AddSalariedEmployeeTransaction.java @@ -0,0 +1,27 @@ +package com.coderising.payroll; + +import com.coderising.payroll.api.AddEmployeeTransaction; +import com.coderising.payroll.api.Affiliation; +import com.coderising.payroll.api.PaymentClassification; +import com.coderising.payroll.api.PaymentMethod; +import com.coderising.payroll.api.PaymentSchedule; + +public class AddSalariedEmployeeTransaction extends AddEmployeeTransaction{ + private double salary; + public AddSalariedEmployeeTransaction(String name, String address, PaymentMethod paymentMethod, + Affiliation affiliation) { + super(name, address, paymentMethod, affiliation); + this.salary=salary; + } + + @Override + public PaymentClassification getClassification() { + return new SalariedClassification(salary); + } + + @Override + public PaymentSchedule getSchedule() { + return new MonthlySchedule(); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/BankMethod.java b/students/1158154002/src/main/java/com/coderising/payroll/BankMethod.java new file mode 100644 index 0000000000..2a37417717 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/BankMethod.java @@ -0,0 +1,15 @@ +package com.coderising.payroll; + +import com.coderising.payroll.api.PaymentMethod; + +public class BankMethod implements PaymentMethod{ + + private String bank; + private String account; + + @Override + public void pay(Paycheck pc) { + System.out.println("BankMethod"); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/BiWeeklySchedule.java b/students/1158154002/src/main/java/com/coderising/payroll/BiWeeklySchedule.java new file mode 100644 index 0000000000..39ab695425 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/BiWeeklySchedule.java @@ -0,0 +1,22 @@ +package com.coderising.payroll; + +import java.util.Date; + +import com.coderising.payroll.api.PaymentSchedule; +import com.coderising.payroll.util.DateUtil; + +public class BiWeeklySchedule implements PaymentSchedule { + Date firstPayableFriday = DateUtil.parseDate("2017-06-02"); + + @Override + public boolean isPayDate(Date date) { + int interval = DateUtil.getDaysBetween(firstPayableFriday, date); + return interval % 14 == 0; + } + + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.add(payPeriodEndDate, -13); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/CommissionClassification.java b/students/1158154002/src/main/java/com/coderising/payroll/CommissionClassification.java new file mode 100644 index 0000000000..758e5e8ba8 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/CommissionClassification.java @@ -0,0 +1,34 @@ +package com.coderising.payroll; + +import java.util.Date; +import java.util.Map; + +import com.coderising.payroll.api.PaymentClassification; +import com.coderising.payroll.util.DateUtil; + +public class CommissionClassification implements PaymentClassification{ + private double salary; + private double rate; + private Map receipts; + + public CommissionClassification(double rate, double salary) { + this.rate=rate; + this.salary=salary; + } + + public void addSalesReceipt(SalesReceipt sr) { + receipts.put(sr.getSaleDate(), sr); + } + + @Override + public double calculatePay(Paycheck pc) { + double commission=0; + for (SalesReceipt sr : receipts.values()) { + if (DateUtil.between(sr.getSaleDate(), pc.getPayPeriodStartDate(), pc.getPayPeriodEndDate())) { + commission+=sr.getAmount()*rate; + } + } + return salary+commission; + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/Employee.java b/students/1158154002/src/main/java/com/coderising/payroll/Employee.java new file mode 100644 index 0000000000..45f503ab4a --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/Employee.java @@ -0,0 +1,55 @@ +package com.coderising.payroll; + +import java.util.Date; + +import com.coderising.payroll.api.Affiliation; +import com.coderising.payroll.api.PaymentClassification; +import com.coderising.payroll.api.PaymentMethod; +import com.coderising.payroll.api.PaymentSchedule; + +public class Employee { + String id; + String name; + String address; + + Affiliation affiliation; + PaymentClassification classification; + PaymentSchedule schedule; + PaymentMethod paymentMethod; + + public Employee(String name, String address){ + this.name = name; + this.address = address; + } + public boolean isPayDay(Date d) { + return schedule.isPayDate(d); + } + + public Date getPayPeriodStartDate(Date d) { + return schedule.getPayPeriodStartDate(d); + } + + public void payDay(Paycheck pc){ + double grossPay=classification.calculatePay(pc); + double deductions=affiliation.calculateDeductions(pc); + double netPay=grossPay-deductions; + pc.setGrossPay(grossPay); + pc.setDeductions(deductions); + pc.setNetPay(netPay); + paymentMethod.pay(pc); + } + + public void setClassification(PaymentClassification classification) { + this.classification = classification; + } + public void setSchedule(PaymentSchedule schedule) { + this.schedule = schedule; + } + public void setPaymentMethod(PaymentMethod paymentMethod) { + this.paymentMethod = paymentMethod; + } + + public void setAffiliation(Affiliation affiliation) { + this.affiliation = affiliation; + } +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/HoldMethod.java b/students/1158154002/src/main/java/com/coderising/payroll/HoldMethod.java new file mode 100644 index 0000000000..ec0892eb6a --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/HoldMethod.java @@ -0,0 +1,12 @@ +package com.coderising.payroll; + +import com.coderising.payroll.api.PaymentMethod; + +public class HoldMethod implements PaymentMethod{ + + @Override + public void pay(Paycheck pc) { + System.out.println("HoldMethod"); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/HourlyClassification.java b/students/1158154002/src/main/java/com/coderising/payroll/HourlyClassification.java new file mode 100644 index 0000000000..6d61cae25e --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/HourlyClassification.java @@ -0,0 +1,42 @@ +package com.coderising.payroll; + +import java.util.Date; +import java.util.Map; + +import com.coderising.payroll.api.PaymentClassification; +import com.coderising.payroll.util.DateUtil; + +public class HourlyClassification implements PaymentClassification { + + private double rate; + private Map timeCards; + + public HourlyClassification(double rate) { + this.rate=rate; + } + + public void addTimeCard(TimeCard tc) { + timeCards.put(tc.getDate(), tc); + } + + @Override + public double calculatePay(Paycheck pc) { + double totalPay = 0; + for (TimeCard tc : timeCards.values()) { + if (DateUtil.between(tc.getDate(), pc.getPayPeriodStartDate(), pc.getPayPeriodEndDate())) { + totalPay+=calculatePayForTimeCard(tc); + } + } + return totalPay; + } + + private double calculatePayForTimeCard(TimeCard tc) { + int hours = tc.getHours(); + if (hours > 8) { + return 8 * rate + (hours - 8) * 1.5 * rate; + } else { + return 8 * rate; + } + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/MailMethod.java b/students/1158154002/src/main/java/com/coderising/payroll/MailMethod.java new file mode 100644 index 0000000000..8cbcf755e0 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/MailMethod.java @@ -0,0 +1,13 @@ +package com.coderising.payroll; + +import com.coderising.payroll.api.PaymentMethod; + +public class MailMethod implements PaymentMethod{ + private String address; + + @Override + public void pay(Paycheck pc) { + System.out.println("MailMethod"); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/MonthlySchedule.java b/students/1158154002/src/main/java/com/coderising/payroll/MonthlySchedule.java new file mode 100644 index 0000000000..4b96edd28e --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/MonthlySchedule.java @@ -0,0 +1,20 @@ +package com.coderising.payroll; + +import java.util.Date; + +import com.coderising.payroll.api.PaymentSchedule; +import com.coderising.payroll.util.DateUtil; + +public class MonthlySchedule implements PaymentSchedule{ + + @Override + public boolean isPayDate(Date date) { + return DateUtil.isLasyDayOfMonth(date); + } + + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.getFirstDay(payPeriodEndDate); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/NonAffiliation.java b/students/1158154002/src/main/java/com/coderising/payroll/NonAffiliation.java new file mode 100644 index 0000000000..ec8b6bc5a4 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/NonAffiliation.java @@ -0,0 +1,12 @@ +package com.coderising.payroll; + +import com.coderising.payroll.api.Affiliation; + +public class NonAffiliation implements Affiliation{ + + @Override + public double calculateDeductions(Paycheck pc) { + return 0; + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/Paycheck.java b/students/1158154002/src/main/java/com/coderising/payroll/Paycheck.java new file mode 100644 index 0000000000..5a7f0f87e0 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/Paycheck.java @@ -0,0 +1,34 @@ +package com.coderising.payroll; + +import java.util.Date; + +public class Paycheck { + private Date payPeriodStart; + private Date payPeriodEnd; + private double grossPay; + private double netPay; + private double deductions; + + public Paycheck(Date payPeriodStart, Date payPeriodEnd){ + this.payPeriodStart = payPeriodStart; + this.payPeriodEnd = payPeriodEnd; + } + public void setGrossPay(double grossPay) { + this.grossPay = grossPay; + + } + public void setDeductions(double deductions) { + this.deductions = deductions; + } + public void setNetPay(double netPay){ + this.netPay = netPay; + } + public Date getPayPeriodEndDate() { + + return this.payPeriodEnd; + } + public Date getPayPeriodStartDate() { + + return this.payPeriodStart; + } +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/SalariedClassification.java b/students/1158154002/src/main/java/com/coderising/payroll/SalariedClassification.java new file mode 100644 index 0000000000..8bc025e1d8 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/SalariedClassification.java @@ -0,0 +1,18 @@ +package com.coderising.payroll; + +import com.coderising.payroll.api.PaymentClassification; + +public class SalariedClassification implements PaymentClassification{ + private double salary; + + public SalariedClassification(double salary) { + this.salary=salary; + } + + @Override + public double calculatePay(Paycheck pc) { + // TODO Auto-generated method stub + return salary; + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/SalesReceipt.java b/students/1158154002/src/main/java/com/coderising/payroll/SalesReceipt.java new file mode 100644 index 0000000000..25bbcd81bc --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/SalesReceipt.java @@ -0,0 +1,14 @@ +package com.coderising.payroll; + +import java.util.Date; + +public class SalesReceipt { + private Date saleDate; + private double amount; + public Date getSaleDate() { + return saleDate; + } + public double getAmount() { + return amount; + } +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/ServiceCharge.java b/students/1158154002/src/main/java/com/coderising/payroll/ServiceCharge.java new file mode 100644 index 0000000000..4630f71f17 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/ServiceCharge.java @@ -0,0 +1,22 @@ +package com.coderising.payroll; + +import java.util.Date; + +public class ServiceCharge { + private Date date; + private double amount; + public Date getDate() { + return date; + } + public void setDate(Date date) { + this.date = date; + } + public double getAmount() { + return amount; + } + public void setAmount(double amount) { + this.amount = amount; + } + + +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/TimeCard.java b/students/1158154002/src/main/java/com/coderising/payroll/TimeCard.java new file mode 100644 index 0000000000..0ee88399c5 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/TimeCard.java @@ -0,0 +1,15 @@ +package com.coderising.payroll; + +import java.util.Date; + +public class TimeCard { + private Date date; + private int hours; + + public Date getDate() { + return date; + } + public int getHours() { + return hours; + } +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/UnionAffiliation.java b/students/1158154002/src/main/java/com/coderising/payroll/UnionAffiliation.java new file mode 100644 index 0000000000..7505b585a8 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/UnionAffiliation.java @@ -0,0 +1,35 @@ +package com.coderising.payroll; + +import java.util.Date; +import java.util.Map; + +import com.coderising.payroll.api.Affiliation; +import com.coderising.payroll.util.DateUtil; + +public class UnionAffiliation implements Affiliation{ + private String memberID; + private double weeklyDue; + private Map serviceCharges; + + public void addServiceCharge(ServiceCharge sc){ + serviceCharges.put(sc.getDate(), sc); + } + + @Override + public double calculateDeductions(Paycheck pc) { + double totalPay = 0; + for (ServiceCharge sc : serviceCharges.values()) { + if (DateUtil.between(sc.getDate(), pc.getPayPeriodStartDate(), pc.getPayPeriodEndDate())) { + totalPay+=sc.getAmount(); + } + } + return totalPay+calculatePayForWeeklyDue(pc); + } + + private double calculatePayForWeeklyDue(Paycheck pc) { + int interval=DateUtil.getDaysBetween( pc.getPayPeriodStartDate(),pc.getPayPeriodEndDate()); + return interval/7*weeklyDue; + } + + +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/WeeklySchedule.java b/students/1158154002/src/main/java/com/coderising/payroll/WeeklySchedule.java new file mode 100644 index 0000000000..93e96d2412 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/WeeklySchedule.java @@ -0,0 +1,21 @@ +package com.coderising.payroll; + +import java.util.Date; + +import com.coderising.payroll.api.PaymentSchedule; +import com.coderising.payroll.util.DateUtil; + +public class WeeklySchedule implements PaymentSchedule{ + + @Override + public boolean isPayDate(Date date) { + + return DateUtil.isFriday(date); + } + + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.add(payPeriodEndDate, -6); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/api/AddEmployeeTransaction.java b/students/1158154002/src/main/java/com/coderising/payroll/api/AddEmployeeTransaction.java new file mode 100644 index 0000000000..8537092b94 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/api/AddEmployeeTransaction.java @@ -0,0 +1,34 @@ +package com.coderising.payroll.api; + +import com.coderising.payroll.Employee; + +public abstract class AddEmployeeTransaction { + private String name; + private String address; + private PaymentMethod paymentMethod; + private Affiliation affiliation; + + + public AddEmployeeTransaction(String name, String address, PaymentMethod paymentMethod, Affiliation affiliation) { + super(); + this.name = name; + this.address = address; + this.paymentMethod = paymentMethod; + this.affiliation = affiliation; + } + + public abstract PaymentClassification getClassification(); + + public abstract PaymentSchedule getSchedule(); + + public void execute(){ + PaymentClassification pc=getClassification(); + PaymentSchedule ps=getSchedule(); + Employee e=new Employee(name, address); + e.setClassification(pc); + e.setSchedule(ps); + e.setPaymentMethod(paymentMethod); + e.setAffiliation(affiliation); + } + +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/api/Affiliation.java b/students/1158154002/src/main/java/com/coderising/payroll/api/Affiliation.java new file mode 100644 index 0000000000..9a28cd1c46 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/api/Affiliation.java @@ -0,0 +1,7 @@ +package com.coderising.payroll.api; + +import com.coderising.payroll.Paycheck; + +public interface Affiliation { + public double calculateDeductions(Paycheck pc); +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/api/PaymentClassification.java b/students/1158154002/src/main/java/com/coderising/payroll/api/PaymentClassification.java new file mode 100644 index 0000000000..66e1c6704f --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/api/PaymentClassification.java @@ -0,0 +1,7 @@ +package com.coderising.payroll.api; + +import com.coderising.payroll.Paycheck; + +public interface PaymentClassification { + public double calculatePay(Paycheck pc); +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/api/PaymentMethod.java b/students/1158154002/src/main/java/com/coderising/payroll/api/PaymentMethod.java new file mode 100644 index 0000000000..2be20094b0 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/api/PaymentMethod.java @@ -0,0 +1,7 @@ +package com.coderising.payroll.api; + +import com.coderising.payroll.Paycheck; + +public interface PaymentMethod { + public void pay(Paycheck pc); +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/api/PaymentSchedule.java b/students/1158154002/src/main/java/com/coderising/payroll/api/PaymentSchedule.java new file mode 100644 index 0000000000..520b6a2e98 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/api/PaymentSchedule.java @@ -0,0 +1,8 @@ +package com.coderising.payroll.api; + +import java.util.Date; + +public interface PaymentSchedule { + public boolean isPayDate(Date date); + public Date getPayPeriodStartDate( Date payPeriodEndDate); +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/package-info.java b/students/1158154002/src/main/java/com/coderising/payroll/package-info.java new file mode 100644 index 0000000000..149c6a9f42 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/package-info.java @@ -0,0 +1,8 @@ +/** + * + */ +/** + * @author Administrator + * + */ +package com.coderising.payroll; \ No newline at end of file diff --git a/students/1158154002/src/main/java/com/coderising/payroll/service/PayrollService.java b/students/1158154002/src/main/java/com/coderising/payroll/service/PayrollService.java new file mode 100644 index 0000000000..188bca74b0 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/service/PayrollService.java @@ -0,0 +1,29 @@ +package com.coderising.payroll.service; + +import java.util.Date; +import java.util.List; + +import com.coderising.payroll.Employee; +import com.coderising.payroll.Paycheck; + +public class PayrollService { + public List getAllEmployees(){ + return null; + } + + public void savePayCheck(Paycheck pc){} + + public static void main(String[] args) { + PayrollService payrollService=new PayrollService(); + Date date=new Date(); + List employees=payrollService.getAllEmployees(); + for (Employee e : employees) { + if (e.isPayDay(date)) { + Paycheck pc=new Paycheck(e.getPayPeriodStartDate(date), date); + e.payDay(pc); + payrollService.savePayCheck(pc); + } + } + + } +} diff --git a/students/1158154002/src/main/java/com/coderising/payroll/util/DateUtil.java b/students/1158154002/src/main/java/com/coderising/payroll/util/DateUtil.java new file mode 100644 index 0000000000..f2a3269b63 --- /dev/null +++ b/students/1158154002/src/main/java/com/coderising/payroll/util/DateUtil.java @@ -0,0 +1,65 @@ +package com.coderising.payroll.util; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +public class DateUtil { + public static boolean isLasyDayOfMonth(Date date) { + Calendar b = Calendar.getInstance(); + b.setTime(date); + int lastDay = b.getActualMaximum(Calendar.DAY_OF_MONTH); + int now = b.get(Calendar.DAY_OF_MONTH); + return now == lastDay; + } + + public static Date getFirstDay(Date payPeriodEndDate) { + Calendar c = Calendar.getInstance(); + c.add(Calendar.MONTH, 0); + c.set(Calendar.DAY_OF_MONTH, 1); + return c.getTime(); + } + + public static Date add(Date date, int num) { + Calendar c = Calendar.getInstance(); + c.setTime(date); + c.add(Calendar.DATE, num); + return c.getTime(); + } + + public static Date parseDate(String date) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date time = null; + try { + time = sdf.parse(date); + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return time; + } + + public static boolean isFriday(Date date) { + Calendar c = Calendar.getInstance(); + c.setTime(date); + return c.get(Calendar.DAY_OF_WEEK) == 6; + } + + public static int getDaysBetween(Date start, Date end) { + Calendar aCalendar = Calendar.getInstance(); + aCalendar.setTime(end); + + int day1 = aCalendar.get(Calendar.DAY_OF_YEAR); + aCalendar.setTime(start); + + int day2 = aCalendar.get(Calendar.DAY_OF_YEAR); + + return day1 - day2; + } + + public static boolean between(Date saleDate, Date payPeriodStartDate, Date payPeriodEndDate) { + + return saleDate.getTime()>=payPeriodStartDate.getTime()&&saleDate.getTime()<=payPeriodEndDate.getTime(); + } +} diff --git a/students/1170794299/README.MD b/students/1170794299/README.MD new file mode 100644 index 0000000000..f29dee6099 --- /dev/null +++ b/students/1170794299/README.MD @@ -0,0 +1 @@ +测试 diff --git a/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/Circle.java b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/Circle.java new file mode 100644 index 0000000000..9762bd591d --- /dev/null +++ b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/Circle.java @@ -0,0 +1,19 @@ +package com.coderising.dp.bridge; + +public class Circle extends Shape { + private int x, y, r; + + public Circle(Drawing drawing, int x, int y, int r) { + super(drawing); + this.x = x; + this.y = y; + this.r = r; + } + + @Override + public void draw() { + // TODO Auto-generated method stub + drawing.drawCircle(x, y, r); + } + +} diff --git a/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/Drawing.java b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/Drawing.java new file mode 100644 index 0000000000..d81f4709b9 --- /dev/null +++ b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/Drawing.java @@ -0,0 +1,6 @@ +package com.coderising.dp.bridge; + +public interface Drawing { + public void drawLine(int x1, int y1, int x2, int y2); + public void drawCircle(int x, int y, int r); +} diff --git a/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/DrawingGL1.java b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/DrawingGL1.java new file mode 100644 index 0000000000..94410c0655 --- /dev/null +++ b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/DrawingGL1.java @@ -0,0 +1,18 @@ +package com.coderising.dp.bridge; + +public class DrawingGL1 implements Drawing { + private GraphicLibrary1 graphicLibray1; + + @Override + public void drawLine(int x1, int y1, int x2, int y2) { + // TODO Auto-generated method stub + graphicLibray1.draw_a_line(x1, y1, x2, y2); + } + + @Override + public void drawCircle(int x, int y, int r) { + // TODO Auto-generated method stub + graphicLibray1.draw_a_circle(x, y, r); + } + +} diff --git a/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/DrawingGL2.java b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/DrawingGL2.java new file mode 100644 index 0000000000..757cc2c4b2 --- /dev/null +++ b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/DrawingGL2.java @@ -0,0 +1,18 @@ +package com.coderising.dp.bridge; + +public class DrawingGL2 implements Drawing { + private GraphicLibrary2 graphicLibrary2; + + @Override + public void drawLine(int x1, int y1, int x2, int y2) { + // TODO Auto-generated method stub + graphicLibrary2.drawLine(x1, x2, y1, y2); + } + + @Override + public void drawCircle(int x, int y, int r) { + // TODO Auto-generated method stub + graphicLibrary2.drawCircle(x, y, r); + } + +} diff --git a/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/GraphicLibrary1.java b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/GraphicLibrary1.java new file mode 100644 index 0000000000..798cfbc7f9 --- /dev/null +++ b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/GraphicLibrary1.java @@ -0,0 +1,11 @@ +package com.coderising.dp.bridge; + +public class GraphicLibrary1 { + public void draw_a_line(int x1,int y1,int x2,int y2){ + + } + public void draw_a_circle(int x,int y, int r){ + + } + +} diff --git a/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/GraphicLibrary2.java b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/GraphicLibrary2.java new file mode 100644 index 0000000000..2e67a1220b --- /dev/null +++ b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/GraphicLibrary2.java @@ -0,0 +1,11 @@ +package com.coderising.dp.bridge; + +public class GraphicLibrary2 { + public void drawLine(int x1,int x2,int y1,int y2){ + + } + public void drawCircle(int x,int y, int r){ + + } + +} diff --git a/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/Rectangle.java b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/Rectangle.java new file mode 100644 index 0000000000..b297769c9a --- /dev/null +++ b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/Rectangle.java @@ -0,0 +1,24 @@ +package com.coderising.dp.bridge; + +public class Rectangle extends Shape { + private int x1, y1, x2, y2; + + public Rectangle(Drawing drawing, int x1, int y1, int x2, int y2) { + // TODO Auto-generated constructor stub + super(drawing); + this.x1 = x1; + this.y1 = y1; + this.x2 = x2; + this.y2 = y2; + } + + @Override + public void draw() { + // TODO Auto-generated method stub + drawing.drawLine(x1, y1, x1, y2); + drawing.drawLine(x1, y2, x2, y2); + drawing.drawLine(x2, y2, x2, y1); + drawing.drawLine(x2, y1, x1, y1); + } + +} diff --git a/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/Shape.java b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/Shape.java new file mode 100644 index 0000000000..d909382018 --- /dev/null +++ b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/Shape.java @@ -0,0 +1,11 @@ +package com.coderising.dp.bridge; + +public abstract class Shape { + protected Drawing drawing; + public Shape(Drawing drawing) { + // TODO Auto-generated constructor stub + this.drawing = drawing; + } + + public abstract void draw(); +} diff --git a/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Line.java b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Line.java new file mode 100644 index 0000000000..e6ab14c61b --- /dev/null +++ b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Line.java @@ -0,0 +1,10 @@ +package com.coderising.dp.composite; + +public class Line implements Shape { + + @Override + public void draw() { + System.out.println("I'm a line"); + } + +} diff --git a/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Picture.java b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Picture.java new file mode 100644 index 0000000000..6775f730ac --- /dev/null +++ b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Picture.java @@ -0,0 +1,35 @@ +package com.coderising.dp.composite; + +import java.util.ArrayList; + +public class Picture implements Shape { + ArrayList shapes = new ArrayList<>(); + + @Override + public void draw() { + // TODO Auto-generated method stub + for(Shape shape:shapes) { + shape.draw(); + } + } + + public void add(Shape shape) { + shapes.add(shape); + } + + public static void main(String[] args) { + Picture aPicture = new Picture(); + + Picture p = new Picture(); + p.add(new Text()); + p.add(new Line()); + p.add(new Rectangle()); + + aPicture.add(p); + + aPicture.add(new Line()); + aPicture.add(new Rectangle()); + + aPicture.draw(); + } +} diff --git a/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Rectangle.java b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Rectangle.java new file mode 100644 index 0000000000..7db5bb1c22 --- /dev/null +++ b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Rectangle.java @@ -0,0 +1,11 @@ +package com.coderising.dp.composite; + +public class Rectangle implements Shape { + + @Override + public void draw() { + // TODO Auto-generated method stub + System.out.println("I'm a rectangle"); + } + +} diff --git a/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Shape.java b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Shape.java new file mode 100644 index 0000000000..4562f10b12 --- /dev/null +++ b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Shape.java @@ -0,0 +1,5 @@ +package com.coderising.dp.composite; + +public interface Shape { + public void draw(); +} diff --git a/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Square.java b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Square.java new file mode 100644 index 0000000000..fd17ae3059 --- /dev/null +++ b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Square.java @@ -0,0 +1,11 @@ +package com.coderising.dp.composite; + +public class Square implements Shape { + + @Override + public void draw() { + // TODO Auto-generated method stub + System.out.println("I'm a Square"); + } + +} diff --git a/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Text.java b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Text.java new file mode 100644 index 0000000000..c3c9ebf609 --- /dev/null +++ b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Text.java @@ -0,0 +1,11 @@ +package com.coderising.dp.composite; + +public class Text implements Shape { + + @Override + public void draw() { + // TODO Auto-generated method stub + System.out.println("I'm a Text"); + } + +} diff --git a/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/Email.java b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/Email.java new file mode 100644 index 0000000000..064de1e837 --- /dev/null +++ b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/Email.java @@ -0,0 +1,6 @@ +package com.coderising.dp.decorator; + +public interface Email { + public String getContent(); +} + diff --git a/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/EmailDecorator.java b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/EmailDecorator.java new file mode 100644 index 0000000000..093d9d92c1 --- /dev/null +++ b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/EmailDecorator.java @@ -0,0 +1,15 @@ +package com.coderising.dp.decorator; + +public abstract class EmailDecorator implements Email{ + protected Email email; + + public EmailDecorator(Email email) { + // TODO Auto-generated constructor stub + this.email = email; + } + + public String getContent() { + // TODO Auto-generated method stub + return email.getContent(); + } +} \ No newline at end of file diff --git a/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/EmailImpl.java b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/EmailImpl.java new file mode 100644 index 0000000000..640aef6da3 --- /dev/null +++ b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/EmailImpl.java @@ -0,0 +1,12 @@ +package com.coderising.dp.decorator; + +public class EmailImpl implements Email { + private String content; + + public EmailImpl(String content) { + this.content = content; + } + public String getContent() { + return content; + } +} diff --git a/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/EncryptEmail.java b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/EncryptEmail.java new file mode 100644 index 0000000000..5715936bd2 --- /dev/null +++ b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/EncryptEmail.java @@ -0,0 +1,19 @@ +package com.coderising.dp.decorator; + +public class EncryptEmail extends EmailDecorator { + public EncryptEmail(Email email) { + // TODO Auto-generated constructor stub + super(email); + } + + @Override + public String getContent() { + // TODO Auto-generated method stub + return encrypt(super.getContent()); + } + + private String encrypt(String content) { + // concrete encrypt algorithm + return content+"encrypt"; + } +} diff --git a/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/SendOutEmail.java b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/SendOutEmail.java new file mode 100644 index 0000000000..cd756c3cab --- /dev/null +++ b/students/1203029076/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/SendOutEmail.java @@ -0,0 +1,14 @@ +package com.coderising.dp.decorator; + +public class SendOutEmail extends EmailDecorator{ + public SendOutEmail(Email email) { + // TODO Auto-generated constructor stub + super(email); + } + + @Override + public String getContent() { + // TODO Auto-generated method stub + return super.getContent()+"\nʼΪ˹۵㣬˾"; + } +} diff --git a/students/1204187480/.gitignore b/students/1204187480/.gitignore new file mode 100644 index 0000000000..2a5296f902 --- /dev/null +++ b/students/1204187480/.gitignore @@ -0,0 +1,21 @@ +*.class +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +#ide config +.metadata +.recommenders +.idea/ +*.iml +rebel.* +.rebel.* + +target diff --git a/students/1204187480/code/homework/.gitignore b/students/1204187480/code/homework/.gitignore new file mode 100644 index 0000000000..2a5296f902 --- /dev/null +++ b/students/1204187480/code/homework/.gitignore @@ -0,0 +1,21 @@ +*.class +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +#ide config +.metadata +.recommenders +.idea/ +*.iml +rebel.* +.rebel.* + +target diff --git a/students/1204187480/code/homework/coderising/pom.xml b/students/1204187480/code/homework/coderising/pom.xml new file mode 100644 index 0000000000..d7d922d4d8 --- /dev/null +++ b/students/1204187480/code/homework/coderising/pom.xml @@ -0,0 +1,26 @@ + + 4.0.0 + coderising + + com.coding + parent + 1.0-SNAPSHOT + ../parent/pom.xml + + + + 2.1 + + + + + + commons-digester + commons-digester + ${commons-digester.version} + + + + + \ No newline at end of file diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/jvm/clz/AccessFlag.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/jvm/clz/AccessFlag.java new file mode 100644 index 0000000000..6b60e0bed2 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/jvm/clz/AccessFlag.java @@ -0,0 +1,7 @@ +package com.coderising.jvm.clz; + +/** + * Created by luoziyihao on 5/23/17. + */ +public class AccessFlag { +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/jvm/clz/ClassFile.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/jvm/clz/ClassFile.java new file mode 100644 index 0000000000..855bf9c7e0 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/jvm/clz/ClassFile.java @@ -0,0 +1,7 @@ +package com.coderising.jvm.clz; + +/** + * Created by luoziyihao on 5/23/17. + */ +public class ClassFile { +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/jvm/clz/ClassIndex.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/jvm/clz/ClassIndex.java new file mode 100644 index 0000000000..7b177aa12f --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/jvm/clz/ClassIndex.java @@ -0,0 +1,10 @@ +package com.coderising.jvm.clz; + +/** + * Created by luoziyihao on 5/23/17. + */ +public class ClassIndex { + + String minorVersion; + String majorVersion; +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/jvm/loader/ClassFileLoader.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/jvm/loader/ClassFileLoader.java new file mode 100644 index 0000000000..1c5f8196e8 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/jvm/loader/ClassFileLoader.java @@ -0,0 +1,114 @@ +package com.coderising.jvm.loader; + + +import com.coding.common.util.FileUtils2; +import org.apache.commons.lang3.StringUtils; +import strman.Strman; + +import java.io.File; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +import static com.coding.common.util.FileUtils2.getCanonicalPath; +import static org.apache.commons.lang3.StringUtils.replace; +import static org.apache.commons.lang3.StringUtils.substringAfter; + +/** + * Created by luoziyihao on 4/27/17. + */ +public class ClassFileLoader { + + private List clzPaths; + + private Map clzContext; + + public void addClassPath(String path) { + if (clzPaths == null) { + clzPaths = new ArrayList<>(5); + } + if (StringUtils.isBlank(path)) { + return; + } + File file = new File(path); + if (!file.isDirectory()) { + return; + } + String canonicalName = getCanonicalPath(file); + if (clzPaths.contains(canonicalName)) { + return; + } + clzPaths.add(getCanonicalPath(file)); + } + + + private static final String SPLIT = ";"; + + public String getClassPath() { + StringBuilder classPath = new StringBuilder(); + + for (String e : clzPaths) { + classPath.append(e) + .append(SPLIT); + } + if (classPath.length() > 1) { + classPath.deleteCharAt(classPath.length() - 1); + } + return classPath.toString(); + } + + private static final String CLZ_SUFFIX = ".class"; + + public byte[] readBinaryCode(String className) { + if (StringUtils.isBlank(className)) { + throw new IllegalStateException("className is blank"); + } + byte[] binaryCode = getClzContext().get(Strman.append(className, CLZ_SUFFIX)); + if (binaryCode == null) { + throw new IllegalStateException( + Strman.format("className={0} is not found in classpath", className)); + } + return binaryCode; + } + + private Map getClzContext() { + if (clzContext == null) { + clzContext = createClzContextWithClzPaths(clzPaths); + } + return clzContext; + } + + private Map createClzContextWithClzPaths(List clzPaths) { + Map clzContext = new ConcurrentHashMap<>(60); + for (String e : clzPaths) { + File file = new File(e); + if (file.isDirectory()) { + List files = FileUtils2.listAllFiles(file); + clzContext = addClassElements(clzContext, e, files); + } + } + return clzContext; + } + + private Map addClassElements(Map clzContext, String classpath, List files) { + for (File classFile : files) { + String filePath = getCanonicalPath(classFile); + String canonicalName = getCanonicalName(classpath, filePath); + byte[] bytes = FileUtils2.getBytes(classFile); + clzContext.put(canonicalName, bytes); + } + return clzContext; + } + + /** + * 将classpath 下的文件路径转成 a.b.c.class 的格式 + */ + private static final String POINT = "."; + + private String getCanonicalName(String classpath, String filePath) { + String tmp = replace(substringAfter(filePath, classpath), File.separator, POINT); + if (tmp.startsWith(POINT)) { + tmp = StringUtils.removeStart(tmp, POINT); + } + return tmp; + } +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/jvm/loader/ClassFileParser.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/jvm/loader/ClassFileParser.java new file mode 100644 index 0000000000..9c77821341 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/jvm/loader/ClassFileParser.java @@ -0,0 +1,7 @@ +package com.coderising.jvm.loader; + +/** + * Created by luoziyihao on 5/23/17. + */ +public class ClassFileParser { +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/LoginAction.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/LoginAction.java new file mode 100644 index 0000000000..dcdbe226ed --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/LoginAction.java @@ -0,0 +1,39 @@ +package com.coderising.litestruts; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * @author liuxin + * + */ +public class LoginAction{ + private String name ; + private String password; + private String message; + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String execute(){ + if("test".equals(name) && "1234".equals(password)){ + this.message = "login successful"; + return "success"; + } + this.message = "login failed,please check your user/pwd"; + return "fail"; + } + + public void setName(String name){ + this.name = name; + } + public void setPassword(String password){ + this.password = password; + } + public String getMessage(){ + return this.message; + } +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/Struts.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/Struts.java new file mode 100644 index 0000000000..0b238b2db0 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/Struts.java @@ -0,0 +1,121 @@ +package com.coderising.litestruts; + +import com.coderising.litestruts.parser.ActionConfig; +import com.coderising.litestruts.parser.DefaultStrutsParser; +import com.coderising.litestruts.parser.StrutsConfig; +import com.coderising.litestruts.parser.StrutsParser; +import com.coding.common.util.BeanUtils; + +import java.util.Map; + + +public class Struts { + + private static StrutsParser strutsParser = new DefaultStrutsParser(); + + private static final String STRUTS_CONFIG_PATH = "struts.xml"; + private static final BeanUtils beanUtils = new BeanUtils(); + + public static View runAction(String actionName, Map parameters) { + + /* + + 0. 读取配置文件struts.xml + + 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + ("name"="test" , "password"="1234") , + 那就应该调用 setName和setPassword方法 + + 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + + 3. 通过反射找到对象的所有getter方法(例如 getMessage), + 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + 放到View对象的parameters + + 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + 放到View对象的jsp字段中。 + + */ + + /** + * 0. 读取配置文件struts.xml + */ + StrutsConfig strutsConfig = strutsParser.parser(STRUTS_CONFIG_PATH); + ActionConfig actionConfig = strutsConfig.getActions().get(actionName); + /** + * 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + ("name"="test" , "password"="1234") , + 那就应该调用 setName和setPassword方法 + */ + Object action = setPropertiesForAction(actionConfig, actionName, parameters); + + /** + * 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + */ + String resultName = doExecute(action); + /** + * 3. 通过反射找到对象的所有getter方法(例如 getMessage), + 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + 放到View对象的parameters + */ + View view = createViewAndSetParameters(action); + /** + * 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + 放到View对象的jsp字段中。 + */ + setViewValue(view, resultName, actionConfig); + return view; + } + + private static void setViewValue(View view, String resultName, ActionConfig config) { + view.setJsp(config.getResults().get(resultName).getView()); + } + + private static View createViewAndSetParameters(Object action) { + View view = new View(); + view.setParameters(beanUtils.describe(action)); + return view; + } + + private static String doExecute(Object action) { + return (String) beanUtils.invokeWithNoParamter("execute", action); + } + + private static Object setPropertiesForAction(ActionConfig actionConfig, String actionName, Map parameters) { + Object action = createInstance(findActionClass(actionConfig.getClassName())); + for (Map.Entry entry : parameters.entrySet()) { + setProperty(entry.getKey(), entry.getValue(), action); + } + return action; + } + + /** + * todo 校验 key 是否存在 + * + * @param key + * @param value + * @param action + */ + private static void setProperty(String key, String value, Object action) { + beanUtils.setPara(value, key, action); + } + + private static Object createInstance(Class classValue) { + try { + return classValue.newInstance(); + } catch (InstantiationException | IllegalAccessException e) { + throw new IllegalStateException(e); + } + } + + private static Class findActionClass(String className) { + try { + return Class.forName(className); + } catch (ClassNotFoundException e) { + throw new IllegalStateException(e); + } + } + +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/StrutsTest.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/StrutsTest.java new file mode 100644 index 0000000000..b8c81faf3c --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/StrutsTest.java @@ -0,0 +1,43 @@ +package com.coderising.litestruts; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + + + + + +public class StrutsTest { + + @Test + public void testLoginActionSuccess() { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/View.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/View.java new file mode 100644 index 0000000000..07df2a5dab --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/View.java @@ -0,0 +1,23 @@ +package com.coderising.litestruts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/parser/ActionConfig.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/parser/ActionConfig.java new file mode 100644 index 0000000000..4aaba284fb --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/parser/ActionConfig.java @@ -0,0 +1,45 @@ +package com.coderising.litestruts.parser; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by luoziyihao on 3/5/17. + */ +public class ActionConfig { + private String name; + private String className; + private Map results = new HashMap<>(10); + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public Map getResults() { + return results; + } + + public void setResults(Map results) { + this.results = results; + } + + public void addResult(Result result) { + this.results.put(result.getName(), result); + } + + +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/parser/DefaultStrutsParser.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/parser/DefaultStrutsParser.java new file mode 100644 index 0000000000..ea58507738 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/parser/DefaultStrutsParser.java @@ -0,0 +1,52 @@ +package com.coderising.litestruts.parser; + +import com.alibaba.fastjson.JSON; +import org.apache.commons.digester.Digester; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.xml.sax.SAXException; + +import java.io.File; +import java.io.IOException; + +/** + * 解析 struts.xml 文件 + * @apiNote 借鉴 http://www.everycoding.com/coding/78.html; http://blog.csdn.net/caihaijiang/article/details/5944955 + * Created by luoziyihao on 3/5/17. + */ +public class DefaultStrutsParser implements StrutsParser { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Override + public StrutsConfig parser(String filePathInClasspath) { + String path = this.getClass().getClassLoader().getResource(filePathInClasspath).getPath(); + File input = new File(path); + Digester digester = new Digester(); + // 创建 StrutsConfig 对象 + digester.addObjectCreate("struts", StrutsConfig.class); + // 将 struts 节点上的attribute属性映射到 StrutsConfig 对象的属性上 + digester.addSetProperties("struts"); + digester.addObjectCreate("struts/action", ActionConfig.class); + // 将 struts/action 节点上的attribute属性映射到 Action 对象的属性上, 并自定义属性映射 + digester.addSetProperties("struts/action" + , new String[]{"name", "class"}, new String[]{"name", "className"}); + digester.addObjectCreate("struts/action/result", Result.class); + digester.addSetProperties("struts/action/result" + , new String[]{"name"}, new String[]{"name"}); + // 将 struts/action/result 节点上的body属性映射到 Result 对象的属性上 + digester.addCallMethod("struts/action/result", "setView", 0); + // 对应struts/action/result 生成的对象添加到 Action中 + digester.addSetNext("struts/action/result", "addResult"); + // 对应struts/action 生成的对象添加到 Struts中 + digester.addSetNext("struts/action", "addAction"); + + try { + StrutsConfig strutsConfig = (StrutsConfig) digester.parse(input); + logger.debug("strutsConfig={}", JSON.toJSONString(strutsConfig)); + return strutsConfig; + } catch (IOException | SAXException e) { + throw new IllegalStateException(e); + } + + } +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/parser/Result.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/parser/Result.java new file mode 100644 index 0000000000..c402418e6b --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/parser/Result.java @@ -0,0 +1,22 @@ +package com.coderising.litestruts.parser; + +public class Result { + private String name; + private String view; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getView() { + return view; + } + + public void setView(String view) { + this.view = view; + } +} \ No newline at end of file diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/parser/StrutsConfig.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/parser/StrutsConfig.java new file mode 100644 index 0000000000..88f769157e --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/parser/StrutsConfig.java @@ -0,0 +1,23 @@ +package com.coderising.litestruts.parser; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by luoziyihao on 3/5/17. + */ +public class StrutsConfig { + public Map actions = new HashMap<>(10); + + public Map getActions() { + return actions; + } + + public void setActions(Map actions) { + this.actions = actions; + } + + public void addAction(ActionConfig action) { + this.actions.put(action.getName(), action); + } +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/parser/StrutsParser.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/parser/StrutsParser.java new file mode 100644 index 0000000000..ab7358c777 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/litestruts/parser/StrutsParser.java @@ -0,0 +1,8 @@ +package com.coderising.litestruts.parser; + +/** + * Created by luoziyihao on 3/5/17. + */ +public interface StrutsParser { + StrutsConfig parser(String filePathInClasspath); +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/Configuration.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..9f9e749af7 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..781587a846 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,199 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery = null; + + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected String productID = null; + protected String productDesc = null; + + private static Configuration config; + + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + + + config = new Configuration(); + + setSMTPHost(); + setAltSMTPHost(); + + + setFromAddress(); + + + setLoadQuery(); + + sendEMails(mailDebug, loadMailingList()); + + + } + + + + + protected void setProductID(String productID) + { + this.productID = productID; + + } + + protected String getproductID() + { + return productID; + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected void setSMTPHost() + { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() + { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + protected void setFromAddress() + { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setMessage(HashMap userInfo) throws IOException + { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + + + + } + + + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + private void setProductDesc(String desc) { + this.productDesc = desc; + } + + + protected void configureEMail(HashMap userInfo) throws IOException + { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try + { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } + + else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/Product.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/Product.java new file mode 100644 index 0000000000..3aef295085 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/Product.java @@ -0,0 +1,27 @@ +package com.coderising.ood.srp.optimize; + +/** + * 产品对象 + * Created by luoziyihao on 6/12/17. + */ + +public class Product { + private String productID; + private String productDesc; + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/ProductParser.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/ProductParser.java new file mode 100644 index 0000000000..080c999ffa --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/ProductParser.java @@ -0,0 +1,37 @@ +package com.coderising.ood.srp.optimize; + +import java.util.List; +import java.util.stream.Collectors; + +import static com.coding.common.util.FileUtils2.openStream; +import static com.coding.common.util.IOUtils2.readToStringList; + +/** + * 产品文件解析器 + * Created by luoziyihao on 6/12/17. + */ +public class ProductParser { + + public List parse(String productClassPath) { + List stringList = readToStringList(openStream(productClassPath)); + return stringList.stream() + .map(String::trim) + .filter(s -> !s.isEmpty()) + .filter(s -> s.contains(SPLIT_STRING)) + .map(this::parseLine) + .collect(Collectors.toList()); + + } + + private static final String SPLIT_STRING = " "; + + private Product parseLine(String s) { + int index = s.indexOf(SPLIT_STRING); + String productID = s.substring(0, index); + String productDesc = s.substring(index); + Product product = new Product(); + product.setProductDesc(productDesc); + product.setProductID(productID); + return product; + } +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/PromotionMailApp.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/PromotionMailApp.java new file mode 100644 index 0000000000..6ee832307a --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/PromotionMailApp.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp.optimize; + +import java.util.List; + +/** + * main 函数启动类 + * Created by luoziyihao on 6/12/17. + */ +public class PromotionMailApp { + + public static void main(String args[]) { + List products = new ProductParser().parse("product_promotion.txt"); + + List users = new UserService().loadMailingList(); + + List promotionMailClaims = new PromotionMailClaim() + .load(products, users, new SmptPropeties(), true); + + new PromotionMailableBehavior().send(promotionMailClaims); + + } + +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/PromotionMailClaim.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/PromotionMailClaim.java new file mode 100644 index 0000000000..189b3ced17 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/PromotionMailClaim.java @@ -0,0 +1,99 @@ +package com.coderising.ood.srp.optimize; + +import java.util.ArrayList; +import java.util.List; + +/** + * 发发送邮件的必要参数 vo + * Created by luoziyihao on 6/12/17. + */ +public class PromotionMailClaim { + private String toAddress; + private String fromAddress; + private String subject; + private String message; + private String smtpHost; + private String altSmtpHost; + private Boolean mailDebug; + + private PromotionMailClaim init(Product product, User user, SmptPropeties smptPropeties, Boolean mailDebug) { + this.toAddress = user.getEmail(); + this.fromAddress = smptPropeties.getFromAddress(); + this.subject = "您关注的产品降价了"; + this.message = "尊敬的 " + user.getName() + ", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!"; + this.smtpHost = smptPropeties.getSmtpHost(); + this.altSmtpHost = smptPropeties.getAltSmtpHost(); + this.mailDebug = mailDebug; + return this; + } + + public List load(List products, List users, SmptPropeties smptPropeties + , boolean mailDebug) { + List promotionMailClaims = new ArrayList<>(); + for (Product product : products) { + for (User user : users) { + PromotionMailClaim promotionMailClaim = new PromotionMailClaim() + .init(product, user, smptPropeties, mailDebug); + promotionMailClaims.add(promotionMailClaim); + } + } + return promotionMailClaims; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + + public Boolean getMailDebug() { + return mailDebug; + } + + public void setMailDebug(Boolean mailDebug) { + this.mailDebug = mailDebug; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getSmtpHost() { + return smtpHost; + } + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/PromotionMailableBehavior.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/PromotionMailableBehavior.java new file mode 100644 index 0000000000..ad37998e45 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/PromotionMailableBehavior.java @@ -0,0 +1,41 @@ +package com.coderising.ood.srp.optimize; + +import java.util.List; + +/** + * 发邮件的行为类 + * Created by luoziyihao on 6/12/17. + */ +public class PromotionMailableBehavior { + + public void send(List emailSendClaimList) { + for (PromotionMailClaim promotionMailClaim : emailSendClaimList) { + sendEmailForOneClaim(promotionMailClaim); + } + } + + private void sendEmailForOneClaim(PromotionMailClaim promotionMailClaim) { + System.out.println("开始发送邮件"); + + try { + doSendMail(promotionMailClaim); + } catch (Exception e) { + try { + promotionMailClaim.setSmtpHost(promotionMailClaim.getAltSmtpHost()); + doSendMail(promotionMailClaim); + } catch (Exception e1) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e.getMessage()); + } + } + } + + private void doSendMail(PromotionMailClaim promotionMailClaim) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(promotionMailClaim.getFromAddress()).append("\n"); + buffer.append("To:").append(promotionMailClaim.getToAddress()).append("\n"); + buffer.append("Subject:").append(promotionMailClaim.getSubject()).append("\n"); + buffer.append("Content:").append(promotionMailClaim.getMessage()).append("\n"); + System.out.println(buffer.toString()); + } +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/SmptPropeties.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/SmptPropeties.java new file mode 100644 index 0000000000..c6664fafc3 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/SmptPropeties.java @@ -0,0 +1,35 @@ +package com.coderising.ood.srp.optimize; + +/** + * 邮件服务器配置类 + * Created by luoziyihao on 6/12/17. + */ +public class SmptPropeties { + private String smtpHost = "smtp.server";; + private String altSmtpHost = "smtp1.163.com"; + private String fromAddress = " admin@company.com"; + + public String getSmtpHost() { + return smtpHost; + } + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/User.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/User.java new file mode 100644 index 0000000000..996efadbb6 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/User.java @@ -0,0 +1,26 @@ +package com.coderising.ood.srp.optimize; + +/** + * 用户类 + * Created by luoziyihao on 6/12/17. + */ +public class User { + private String name; + private String email; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/UserService.java b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/UserService.java new file mode 100644 index 0000000000..f5da2d3908 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/java/com/coderising/ood/srp/optimize/UserService.java @@ -0,0 +1,22 @@ +package com.coderising.ood.srp.optimize; + +import java.util.ArrayList; +import java.util.List; + +/** + * 用户service, 管理用户的数据 + * Created by luoziyihao on 6/12/17. + */ +public class UserService { + + List loadMailingList() { + List userList = new ArrayList<>(); + for (int i = 1; i <= 3; i++) { + User user = new User(); + user.setName("User" + i); + user.setEmail("aa@bb.com"); + userList.add(user); + } + return userList; + } +} diff --git a/students/1204187480/code/homework/coderising/src/main/resources/product_promotion.txt b/students/1204187480/code/homework/coderising/src/main/resources/product_promotion.txt new file mode 100644 index 0000000000..a98917f829 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/resources/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo R15 +P4955 Vivo X20 \ No newline at end of file diff --git a/students/1204187480/code/homework/coderising/src/main/resources/struts.xml b/students/1204187480/code/homework/coderising/src/main/resources/struts.xml new file mode 100644 index 0000000000..876156eb4d --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/main/resources/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/students/1204187480/code/homework/coderising/src/test/java/com/coderising/api/ComputeTest.java b/students/1204187480/code/homework/coderising/src/test/java/com/coderising/api/ComputeTest.java new file mode 100644 index 0000000000..f02816a555 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/test/java/com/coderising/api/ComputeTest.java @@ -0,0 +1,21 @@ +package com.coderising.api; + +import org.junit.Test; + +/** + * Created by luoziyihao on 3/5/17. + */ +public class ComputeTest { + + @Test + public void testDivisionExactly(){ + System.out.println( 7 >> 1); + System.out.println( -5 >> 2); + System.out.println( -5 << 2); + } + + @Test + public void testSqrt() { + System.out.println(Math.sqrt(10)); + } +} diff --git a/students/1204187480/code/homework/coderising/src/test/java/com/coderising/api/CycleTest.java b/students/1204187480/code/homework/coderising/src/test/java/com/coderising/api/CycleTest.java new file mode 100644 index 0000000000..6abb5d925d --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/test/java/com/coderising/api/CycleTest.java @@ -0,0 +1,25 @@ +package com.coderising.api; + +import org.junit.Test; + +/** + * Created by luoziyihao on 3/5/17. + */ +public class CycleTest { + + /** + * checkIndex will be excuted in each cycle + */ + @Test + public void testForSize() { + int[] arr = new int[]{1, 2, 3, 4, 54}; + for (int i = 0; checkIndex(i, arr); i++ ) { + + } + } + + private boolean checkIndex(int i, int[] arr) { + System.out.println(i); + return i < arr.length; + } +} diff --git a/students/1204187480/code/homework/coderising/src/test/java/com/coderising/api/FileTest.java b/students/1204187480/code/homework/coderising/src/test/java/com/coderising/api/FileTest.java new file mode 100644 index 0000000000..bd918a011c --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/test/java/com/coderising/api/FileTest.java @@ -0,0 +1,32 @@ +package com.coderising.api; + +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; + +/** + * Created by luoziyihao on 4/28/17. + */ +@Slf4j +public class FileTest { + + @Test + public void testFile() { + File file = new File("./hahah"); + Assert.assertFalse(file.isDirectory()); + + } + + @Test + public void testAbsolutePath() throws IOException { + File file = new File("../src"); + log.info("isDirectory={}", file.isDirectory()); + log.info(file.getAbsolutePath()); + log.info(file.getCanonicalPath()); + log.info(file.getName()); + log.info(file.getPath()); + } +} diff --git a/students/1204187480/code/homework/coderising/src/test/java/com/coderising/api/ObjectTest.java b/students/1204187480/code/homework/coderising/src/test/java/com/coderising/api/ObjectTest.java new file mode 100644 index 0000000000..06cd373de5 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/test/java/com/coderising/api/ObjectTest.java @@ -0,0 +1,18 @@ +package com.coderising.api; + +import lombok.extern.slf4j.Slf4j; +import org.junit.Test; + +/** + * Created by luoziyihao on 5/2/17. + */ +@Slf4j +public class ObjectTest { + @Test + public void test(){ + Object a[] = {1}; + log.info(a.getClass().getName()); + log.info(a.getClass().getCanonicalName()); + log.info(a.getClass().getSimpleName()); + } +} diff --git a/students/1204187480/code/homework/coderising/src/test/java/com/coderising/api/StrmanTest.java b/students/1204187480/code/homework/coderising/src/test/java/com/coderising/api/StrmanTest.java new file mode 100644 index 0000000000..6831eb0ad6 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/test/java/com/coderising/api/StrmanTest.java @@ -0,0 +1,17 @@ +package com.coderising.api; + +import org.junit.Test; +import strman.Strman; + +/** + * Created by luoziyihao on 5/3/17. + */ +public class StrmanTest { + + @Test + public void testFormat() { + + System.out.println(Strman.format("className is not found in classpath, className={1}", ",333 ","cccc")); + + } +} diff --git a/students/1204187480/code/homework/coderising/src/test/java/com/coderising/jvm/test/ClassFileloaderTest.java b/students/1204187480/code/homework/coderising/src/test/java/com/coderising/jvm/test/ClassFileloaderTest.java new file mode 100644 index 0000000000..b7c5bab54e --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/test/java/com/coderising/jvm/test/ClassFileloaderTest.java @@ -0,0 +1,354 @@ +package com.coderising.jvm.test; + +import java.io.File; +import java.util.List; + +import ch.qos.logback.core.encoder.ByteArrayUtil; +import com.coding.common.util.ByteUtils; +import com.coding.common.util.FileUtils2; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +//import com.coderising.jvm.clz.ClassFile; +//import com.coderising.jvm.clz.ClassIndex; +//import com.coderising.jvm.cmd.BiPushCmd; +//import com.coderising.jvm.cmd.ByteCodeCommand; +//import com.coderising.jvm.cmd.OneOperandCmd; +//import com.coderising.jvm.cmd.TwoOperandCmd; +//import com.coderising.jvm.constant.ClassInfo; +//import com.coderising.jvm.constant.ConstantPool; +//import com.coderising.jvm.constant.MethodRefInfo; +//import com.coderising.jvm.constant.NameAndTypeInfo; +//import com.coderising.jvm.constant.UTF8Info; +//import com.coderising.jvm.field.Field; +import com.coderising.jvm.loader.ClassFileLoader; + +import static com.coding.common.util.FileUtils2.getCanonicalPath; +//import com.coderising.jvm.method.Method; + + + + + +public class ClassFileloaderTest { + + + private static final String FULL_QUALIFIED_CLASS_NAME = "com/coderising/jvm/test/EmployeeV1"; + + static String path1 = "target/classes"; + static String path2 = "target/test-classes"; + +// static ClassFile clzFile = null; +// static { +// ClassFileLoader loader = new ClassFileLoader(); +// loader.addClassPath(path1); +// String className = "com.coderising.jvm.test.EmployeeV1"; +// +// clzFile = loader.loadClass(className); +// +// } + + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + private void addClassPath(ClassFileLoader loader) { + loader.addClassPath(path1); + loader.addClassPath(path2); + } + + @Test + public void testClassPath(){ + + ClassFileLoader loader = new ClassFileLoader(); + addClassPath(loader); + String clzPath = loader.getClassPath(); + + Assert.assertEquals(getCanonicalPath(new File(path1))+";"+getCanonicalPath(new File(path2)),clzPath); + + } + + @Test + public void testClassFileLength() { + + ClassFileLoader loader = new ClassFileLoader(); + addClassPath(loader); + + String className = "com.coderising.jvm.test.EmployeeV1"; + + byte[] byteCodes = loader.readBinaryCode(className); + + // 注意:这个字节数可能和你的JVM版本有关系, 你可以看看编译好的类到底有多大 + Assert.assertEquals(1056, byteCodes.length); + + } + + + @Test + public void testMagicNumber(){ + ClassFileLoader loader = new ClassFileLoader(); + addClassPath(loader); + String className = "com.coderising.jvm.test.EmployeeV1"; + byte[] byteCodes = loader.readBinaryCode(className); + byte[] codes = new byte[]{byteCodes[0],byteCodes[1],byteCodes[2],byteCodes[3]}; + + + String acctualValue = this.byteToHexString(codes); + + Assert.assertEquals("cafebabe", acctualValue); + } + + + + private String byteToHexString(byte[] codes ){ + return ByteUtils.byteToHexString(codes); + } + +// add comment for behind test +// /** +// * ---------------------------------------------------------------------- +// */ +// +// +// @Test +// public void testVersion(){ +// +// Assert.assertEquals(0, clzFile.getMinorVersion()); +// Assert.assertEquals(52, clzFile.getMajorVersion()); +// +// } +// +// @Test +// public void testConstantPool(){ +// +// +// ConstantPool pool = clzFile.getConstantPool(); +// +// Assert.assertEquals(53, pool.getSize()); +// +// { +// ClassInfo clzInfo = (ClassInfo) pool.getConstantInfo(1); +// Assert.assertEquals(2, clzInfo.getUtf8Index()); +// +// UTF8Info utf8Info = (UTF8Info) pool.getConstantInfo(2); +// Assert.assertEquals(FULL_QUALIFIED_CLASS_NAME, utf8Info.getValue()); +// } +// { +// ClassInfo clzInfo = (ClassInfo) pool.getConstantInfo(3); +// Assert.assertEquals(4, clzInfo.getUtf8Index()); +// +// UTF8Info utf8Info = (UTF8Info) pool.getConstantInfo(4); +// Assert.assertEquals("java/lang/Object", utf8Info.getValue()); +// } +// { +// UTF8Info utf8Info = (UTF8Info) pool.getConstantInfo(5); +// Assert.assertEquals("name", utf8Info.getValue()); +// +// utf8Info = (UTF8Info) pool.getConstantInfo(6); +// Assert.assertEquals("Ljava/lang/String;", utf8Info.getValue()); +// +// utf8Info = (UTF8Info) pool.getConstantInfo(7); +// Assert.assertEquals("age", utf8Info.getValue()); +// +// utf8Info = (UTF8Info) pool.getConstantInfo(8); +// Assert.assertEquals("I", utf8Info.getValue()); +// +// utf8Info = (UTF8Info) pool.getConstantInfo(9); +// Assert.assertEquals("", utf8Info.getValue()); +// +// utf8Info = (UTF8Info) pool.getConstantInfo(10); +// Assert.assertEquals("(Ljava/lang/String;I)V", utf8Info.getValue()); +// +// utf8Info = (UTF8Info) pool.getConstantInfo(11); +// Assert.assertEquals("Code", utf8Info.getValue()); +// } +// +// { +// MethodRefInfo methodRef = (MethodRefInfo)pool.getConstantInfo(12); +// Assert.assertEquals(3, methodRef.getClassInfoIndex()); +// Assert.assertEquals(13, methodRef.getNameAndTypeIndex()); +// } +// +// { +// NameAndTypeInfo nameAndType = (NameAndTypeInfo) pool.getConstantInfo(13); +// Assert.assertEquals(9, nameAndType.getIndex1()); +// Assert.assertEquals(14, nameAndType.getIndex2()); +// } +// //抽查几个吧 +// { +// MethodRefInfo methodRef = (MethodRefInfo)pool.getConstantInfo(45); +// Assert.assertEquals(1, methodRef.getClassInfoIndex()); +// Assert.assertEquals(46, methodRef.getNameAndTypeIndex()); +// } +// +// { +// UTF8Info utf8Info = (UTF8Info) pool.getConstantInfo(53); +// Assert.assertEquals("EmployeeV1.java", utf8Info.getValue()); +// } +// } +// @Test +// public void testClassIndex(){ +// +// ClassIndex clzIndex = clzFile.getClzIndex(); +// ClassInfo thisClassInfo = (ClassInfo)clzFile.getConstantPool().getConstantInfo(clzIndex.getThisClassIndex()); +// ClassInfo superClassInfo = (ClassInfo)clzFile.getConstantPool().getConstantInfo(clzIndex.getSuperClassIndex()); +// +// +// Assert.assertEquals(FULL_QUALIFIED_CLASS_NAME, thisClassInfo.getClassName()); +// Assert.assertEquals("java/lang/Object", superClassInfo.getClassName()); +// } +// +// /** +// * 下面是第三次JVM课应实现的测试用例 +// */ +// @Test +// public void testReadFields(){ +// +// List fields = clzFile.getFields(); +// Assert.assertEquals(2, fields.size()); +// { +// Field f = fields.get(0); +// Assert.assertEquals("name:Ljava/lang/String;", f.toString()); +// } +// { +// Field f = fields.get(1); +// Assert.assertEquals("age:I", f.toString()); +// } +// } +// @Test +// public void testMethods(){ +// +// List methods = clzFile.getMethods(); +// ConstantPool pool = clzFile.getConstantPool(); +// +// { +// Method m = methods.get(0); +// assertMethodEquals(pool,m, +// "", +// "(Ljava/lang/String;I)V", +// "2ab7000c2a2bb5000f2a1cb50011b1"); +// +// } +// { +// Method m = methods.get(1); +// assertMethodEquals(pool,m, +// "setName", +// "(Ljava/lang/String;)V", +// "2a2bb5000fb1"); +// +// } +// { +// Method m = methods.get(2); +// assertMethodEquals(pool,m, +// "setAge", +// "(I)V", +// "2a1bb50011b1"); +// } +// { +// Method m = methods.get(3); +// assertMethodEquals(pool,m, +// "sayHello", +// "()V", +// "b2001c1222b60024b1"); +// +// } +// { +// Method m = methods.get(4); +// assertMethodEquals(pool,m, +// "main", +// "([Ljava/lang/String;)V", +// "bb000159122b101db7002d4c2bb6002fb1"); +// } +// } +// +// private void assertMethodEquals(ConstantPool pool,Method m , String expectedName, String expectedDesc,String expectedCode){ +// String methodName = pool.getUTF8String(m.getNameIndex()); +// String methodDesc = pool.getUTF8String(m.getDescriptorIndex()); +// String code = m.getCodeAttr().getCode(); +// Assert.assertEquals(expectedName, methodName); +// Assert.assertEquals(expectedDesc, methodDesc); +// Assert.assertEquals(expectedCode, code); +// } +// +// @Test +// public void testByteCodeCommand(){ +// { +// Method initMethod = this.clzFile.getMethod("", "(Ljava/lang/String;I)V"); +// ByteCodeCommand [] cmds = initMethod.getCmds(); +// +// assertOpCodeEquals("0: aload_0", cmds[0]); +// assertOpCodeEquals("1: invokespecial #12", cmds[1]); +// assertOpCodeEquals("4: aload_0", cmds[2]); +// assertOpCodeEquals("5: aload_1", cmds[3]); +// assertOpCodeEquals("6: putfield #15", cmds[4]); +// assertOpCodeEquals("9: aload_0", cmds[5]); +// assertOpCodeEquals("10: iload_2", cmds[6]); +// assertOpCodeEquals("11: putfield #17", cmds[7]); +// assertOpCodeEquals("14: return", cmds[8]); +// } +// +// { +// Method setNameMethod = this.clzFile.getMethod("setName", "(Ljava/lang/String;)V"); +// ByteCodeCommand [] cmds = setNameMethod.getCmds(); +// +// assertOpCodeEquals("0: aload_0", cmds[0]); +// assertOpCodeEquals("1: aload_1", cmds[1]); +// assertOpCodeEquals("2: putfield #15", cmds[2]); +// assertOpCodeEquals("5: return", cmds[3]); +// +// } +// +// { +// Method sayHelloMethod = this.clzFile.getMethod("sayHello", "()V"); +// ByteCodeCommand [] cmds = sayHelloMethod.getCmds(); +// +// assertOpCodeEquals("0: getstatic #28", cmds[0]); +// assertOpCodeEquals("3: ldc #34", cmds[1]); +// assertOpCodeEquals("5: invokevirtual #36", cmds[2]); +// assertOpCodeEquals("8: return", cmds[3]); +// +// } +// +// { +// Method mainMethod = this.clzFile.getMainMethod(); +// +// ByteCodeCommand [] cmds = mainMethod.getCmds(); +// +// assertOpCodeEquals("0: new #1", cmds[0]); +// assertOpCodeEquals("3: dup", cmds[1]); +// assertOpCodeEquals("4: ldc #43", cmds[2]); +// assertOpCodeEquals("6: bipush 29", cmds[3]); +// assertOpCodeEquals("8: invokespecial #45", cmds[4]); +// assertOpCodeEquals("11: astore_1", cmds[5]); +// assertOpCodeEquals("12: aload_1", cmds[6]); +// assertOpCodeEquals("13: invokevirtual #47", cmds[7]); +// assertOpCodeEquals("16: return", cmds[8]); +// } +// +// } +// +// private void assertOpCodeEquals(String expected, ByteCodeCommand cmd){ +// +// String acctual = cmd.getOffset()+": "+cmd.getReadableCodeText(); +// +// if(cmd instanceof OneOperandCmd){ +// if(cmd instanceof BiPushCmd){ +// acctual += " " + ((OneOperandCmd)cmd).getOperand(); +// } else{ +// acctual += " #" + ((OneOperandCmd)cmd).getOperand(); +// } +// } +// if(cmd instanceof TwoOperandCmd){ +// acctual += " #" + ((TwoOperandCmd)cmd).getIndex(); +// } +// Assert.assertEquals(expected, acctual); +// } + +} diff --git a/students/1204187480/code/homework/coderising/src/test/java/com/coderising/jvm/test/EmployeeV1.java b/students/1204187480/code/homework/coderising/src/test/java/com/coderising/jvm/test/EmployeeV1.java new file mode 100644 index 0000000000..12e3d7efdd --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/test/java/com/coderising/jvm/test/EmployeeV1.java @@ -0,0 +1,28 @@ +package com.coderising.jvm.test; + +public class EmployeeV1 { + + + private String name; + private int age; + + public EmployeeV1(String name, int age) { + this.name = name; + this.age = age; + } + + public void setName(String name) { + this.name = name; + } + public void setAge(int age){ + this.age = age; + } + public void sayHello() { + System.out.println("Hello , this is class Employee "); + } + public static void main(String[] args){ + EmployeeV1 p = new EmployeeV1("Andy",29); + p.sayHello(); + + } +} \ No newline at end of file diff --git a/students/1204187480/code/homework/coderising/src/test/java/com/coderising/litestruts/parser/StructsParserTest.java b/students/1204187480/code/homework/coderising/src/test/java/com/coderising/litestruts/parser/StructsParserTest.java new file mode 100644 index 0000000000..72e841a230 --- /dev/null +++ b/students/1204187480/code/homework/coderising/src/test/java/com/coderising/litestruts/parser/StructsParserTest.java @@ -0,0 +1,14 @@ +package com.coderising.litestruts.parser; + +import org.junit.Test; + +/** + * Created by luoziyihao on 3/5/17. + */ +public class StructsParserTest { + @Test + public void parser() throws Exception { + new DefaultStrutsParser().parser("struts.xml"); + } + +} \ No newline at end of file diff --git a/students/1204187480/code/homework/coding/pom.xml b/students/1204187480/code/homework/coding/pom.xml new file mode 100644 index 0000000000..08acfc3528 --- /dev/null +++ b/students/1204187480/code/homework/coding/pom.xml @@ -0,0 +1,12 @@ + + 4.0.0 + coding + + com.coding + parent + 1.0-SNAPSHOT + ../parent/pom.xml + + + \ No newline at end of file diff --git a/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/BinaryTreeNode.java b/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/BinaryTreeNode.java new file mode 100644 index 0000000000..d7ac820192 --- /dev/null +++ b/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/BinaryTreeNode.java @@ -0,0 +1,32 @@ +package com.coding.basic; + +public class BinaryTreeNode { + + private Object data; + private BinaryTreeNode left; + private BinaryTreeNode right; + + public Object getData() { + return data; + } + public void setData(Object data) { + this.data = data; + } + public BinaryTreeNode getLeft() { + return left; + } + public void setLeft(BinaryTreeNode left) { + this.left = left; + } + public BinaryTreeNode getRight() { + return right; + } + public void setRight(BinaryTreeNode right) { + this.right = right; + } + + public BinaryTreeNode insert(Object o){ + return null; + } + +} diff --git a/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/Iterator.java b/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/Iterator.java new file mode 100644 index 0000000000..06ef6311b2 --- /dev/null +++ b/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/Iterator.java @@ -0,0 +1,7 @@ +package com.coding.basic; + +public interface Iterator { + public boolean hasNext(); + public Object next(); + +} diff --git a/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/List.java b/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/List.java new file mode 100644 index 0000000000..ef939ae2cc --- /dev/null +++ b/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/List.java @@ -0,0 +1,10 @@ +package com.coding.basic; + +public interface List { + public void add(Object o); + public void add(int index, Object o); + public Object get(int index); + public Object remove(int index); + public int size(); + public Iterator iterator(); +} diff --git a/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/Queue.java b/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/Queue.java new file mode 100644 index 0000000000..e333496198 --- /dev/null +++ b/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/Queue.java @@ -0,0 +1,24 @@ +package com.coding.basic; + +import com.coding.basic.linklist.LinkedList; + +public class Queue { + + private LinkedList elementData = new LinkedList(); + + public void enQueue(Object o){ + elementData.add(o); + } + + public Object deQueue(){ + return elementData.remove(0); + } + + public boolean isEmpty(){ + return size() == 0; + } + + public int size(){ + return elementData.size(); + } +} diff --git a/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/Stack.java b/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/Stack.java new file mode 100644 index 0000000000..7336dccfe9 --- /dev/null +++ b/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/Stack.java @@ -0,0 +1,32 @@ +package com.coding.basic; + +import com.coding.basic.array.ArrayList; + +public class Stack { + private ArrayList elementData = new ArrayList(); + + public void push(Object o){ + elementData.add(o); + } + + public Object pop(){ + if (isEmpty()) { + throw new IllegalStateException("the stack is empty"); + } + return elementData.remove(elementData.size() - 1); + } + + public Object peek(){ + if (isEmpty()) { + throw new IllegalStateException("the stack is empty"); + } + return elementData.get(elementData.size() - 1); + } + + public boolean isEmpty(){ + return size() == 0; + } + public int size(){ + return elementData.size(); + } +} diff --git a/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/array/ArrayList.java b/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/array/ArrayList.java new file mode 100644 index 0000000000..cbe1f87a05 --- /dev/null +++ b/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/array/ArrayList.java @@ -0,0 +1,111 @@ +package com.coding.basic.array; + +import com.coding.basic.Iterator; +import com.coding.basic.List; + +import java.util.Arrays; + +public class ArrayList implements List { + + private int size = 0; + + private Object[] elementData = new Object[100]; + + private Iterator iterator = new ArrayListIterator(); + + private int length() { + return elementData.length; + } + + private static final int ENLARGE_LENGTH = 100; + + private Object[] enlarge(Object[] origin) { + return Arrays.copyOf(origin, origin.length + ENLARGE_LENGTH); + } + + private void enLargeElementData() { + if (size == length()) { + elementData = enlarge(elementData); + } + } + + public void add(Object o) { + enLargeElementData(); + elementData[size] = o; + size++; + } + + public void add(int index, Object o) { + checkForAdd(index); + enLargeElementData(); + // 备份 index 处及后面的数据 + Object[] elementsBehindIndex = backBehindElements(elementData, index); + // 给index处 设值 + elementData[index] = o; + // 追加 备份的数据 + appendElement(elementData, index, elementsBehindIndex); + size++; + } + + private void appendElement(Object[] origin, int pos, Object[] append) { + System.arraycopy(append, 0, origin, pos, append.length); + } + + private Object[] backBehindElements(Object[] elementData, int index) { + int backSize = size - index; + Object[] back = new Object[backSize]; + System.arraycopy(elementData, index, back, 0, backSize); + return back; + } + + public Object get(int index) { + checkIndex(index); + return elementData[index]; + } + + private void checkIndex(int index) { + if (index < 0 || index >= size) { + throw new ArrayIndexOutOfBoundsException(String.format("index=%s, size=%s", index, size)); + } + } + + private void checkForAdd(int index) { + if (index < 0 || index > size) { + throw new ArrayIndexOutOfBoundsException(String.format("index=%s, size=%s", index, size)); + } + } + + public Object remove(int index) { + checkIndex(index); + Object[] back = backBehindElements(elementData, index + 1); + System.arraycopy(back, 0, elementData, index, back.length); + Object ret = elementData[index]; + elementData[index] = null; + size--; + return ret; + } + + public int size() { + return size; + } + + public Iterator iterator() { + return iterator; + } + + private class ArrayListIterator implements Iterator { + + int next = 0; + + @Override + public boolean hasNext() { + return next < size; + } + + @Override + public Object next() { + return elementData[next++]; + } + } + +} diff --git a/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/array/ArrayUtil.java b/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/array/ArrayUtil.java new file mode 100644 index 0000000000..42ec6efe57 --- /dev/null +++ b/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/array/ArrayUtil.java @@ -0,0 +1,252 @@ +package com.coding.basic.array; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ArrayUtil { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + /** + * 给定一个整形数组a , 对该数组的值进行置换 + 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * @param origin + * @return + */ + public void reverseArray(int[] origin){ + int length = origin.length; + int mid = length >> 1; + for (int i = 0; i < mid; i++) { + int hIndex = length - 1 -i; + int l = origin[i]; + int h = origin[hIndex]; + origin[hIndex] = l; + origin[i] = h; + } + + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: + * {1,3,4,5,6,6,5,4,7,6,7,5} + * @param oldArray + * @return + */ + + public int[] removeZero(int[] oldArray){ + int removeValue = 0; + return removeValue(oldArray, removeValue); + } + + private int[] removeValue(int[] oldArray, int removeValue) { + int length = oldArray.length; + int[] dest = new int[length]; + int j = 0; + for(int i = 0; i < length; i++) { + int v = oldArray[i]; + if (v != removeValue) { + dest[j++] = v; + } + } + + int[] retArray = new int[j]; + System.arraycopy(dest, 0, retArray, 0, j); + return retArray; + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 + * 例如 a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * todo 数组 a1, b1 自身去重 + * @param array1 + * @param array2 + * @return + */ + + public int[] merge(int[] array1, int[] array2){ + int length1 = array1.length; + int length2 = array2.length; + int length = length1 + length2; + int[] newArray = new int[length]; + + return findAndSetLeastWithOutDuplicate(array1, array2, 0, 0, 0, 0, newArray); + } + + /** + * todo 优化递归出口判断, 优化三个条件判断为一个 + * @param array1 + * @param array2 + * @param i + * @param j + * @param k + * @param duplicate + * @param newArray + * @return + */ + private int[] findAndSetLeastWithOutDuplicate(int[] array1, int[] array2, int i, int j, int k, int duplicate, int[] newArray) { + + if (i == array1.length && j < array2.length) { + System.arraycopy(array2, j, newArray, k, array2.length - j); + return copyLastValues(newArray, duplicate); + } + if (j == array2.length && i < array1.length) { + System.arraycopy(array1, i, newArray, k, array1.length - i); + return copyLastValues(newArray, duplicate); + } + if (j == array2.length && i == array1.length) { + return copyLastValues(newArray, duplicate); + } + + int v1 = array1[i]; + int v2 = array2[j]; + if (v1 < v2) { + newArray [k] = v1; + return findAndSetLeastWithOutDuplicate(array1, array2, ++i, j, ++k, duplicate, newArray); + } else if (v1 > v2){ + newArray [k] = v2; + return findAndSetLeastWithOutDuplicate(array1, array2, i, ++j, ++k, duplicate, newArray); + } else { + newArray [k] = v2; + return findAndSetLeastWithOutDuplicate(array1, array2, ++i, ++j, ++k, ++duplicate, newArray); + } + + } + + private int[] copyLastValues(int[] newArray, int duplicate) { + int[] retArray = new int[newArray.length - duplicate]; + System.arraycopy(newArray, 0, retArray, 0, retArray.length); + return retArray; + } + + + /** + * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size + * 注意,老数组的元素在新数组中需要保持 + * 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 + * [2,3,6,0,0,0] + * @param oldArray + * @param size + * @return + */ + public int[] grow(int [] oldArray, int size){ + int[] newArray = new int[oldArray.length + size]; + System.arraycopy(oldArray, 0, newArray, 0, oldArray.length); + return newArray; + } + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 + * 例如, max = 15 , 则返回的数组应该为 [1,1,2,3,5,8,13] + * max = 1, 则返回空数组 [] + * @param max + * @return + */ + public int[] fibonacci(int max){ + if (max <= 1) { + return new int[]{}; + } + int [] newArray = new int[max]; + newArray[0] = 1; + return fibonacciN(1, 1, 1, max, newArray); + } + + private int[] fibonacciN(int size, int current, int next, int max, int[] newArray) { + if (next >= max) { + int[] retArray = new int[size]; + System.arraycopy(newArray, 0, retArray, 0, size); + return retArray; + } else { + newArray[++size - 1] = next; + return fibonacciN(size, next, current + next, max, newArray); + } + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * todo 使用已有的质数序列 优化质数验证 + * @param max + * @return + */ + public int[] getPrimes(int max){ + if (max <= 2) { + return new int[]{}; + } + + int[] newArray = new int[max]; + int j = 0; + for (int i = 2; i < max; i++) { + if (isPrime(i)) { + newArray[j++] = i; + } + } + int[] retArray = new int[j]; + System.arraycopy(newArray, 0, retArray, 0, j); + return retArray; + } + + private boolean isPrime(int number) { + int limit = Double.valueOf(Math.sqrt(number)).intValue(); + for(int i = 2; i <= limit; i++) { + if (number % i == 0 ) { + return false; + } + } + return true; + + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public int[] getPerfectNumbers(int max){ + int[] newArray = new int[48]; // 经过不少数学家研究,到2013年2月6日为止,一共找到了48个完全数。 + int j = 0; + for (int i = 2; i < max; i++) { + if (isPerfectNumber(i)) { + if (j >= newArray.length) { + newArray = this.grow(newArray, 1); + } + newArray[j++] = i; + + } + } + int[] retArray = new int[j]; + System.arraycopy(newArray, 0, retArray, 0, j); + return retArray; + } + + private boolean isPerfectNumber(int number) { + int sum = 0; + for (int i = 1; i < number; i++) { + if (number % i == 0) { + sum += i; + } + } + + return sum == number; + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * @param array + * @param seperator + * @return + */ + public String join(int[] array, String seperator){ + StringBuilder builder = new StringBuilder(20); + int length = array.length; + for (int i = 0; i< length; i++) { + builder.append(array[i]).append(seperator); + } + builder.deleteCharAt(builder.length() - seperator.length()); + return builder.toString(); + } + + +} diff --git a/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/linklist/LRUPageFrame.java b/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/linklist/LRUPageFrame.java new file mode 100644 index 0000000000..96c2e2cdab --- /dev/null +++ b/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/linklist/LRUPageFrame.java @@ -0,0 +1,169 @@ +package com.coding.basic.linklist; + +import lombok.extern.slf4j.Slf4j; + +/** + * 定长链表 + * 命中后更新 pageNumber的位置 + * 随时要考虑 first, node 的变化 + */ +@Slf4j +public class LRUPageFrame { + + private static class Node { + + Node prev; + Node next; + int pageNum; + + public Node(Node next, int pageNum) { + this.next = next; + this.pageNum = pageNum; + } + + public Node(int pageNum) { + this.pageNum = pageNum; + } + + Node() { + } + + public String debug() { + return new StringBuilder(). + append("\n##########################pre: ") + .append(prev) + .append("\n##########################node: ") + .append(this) + .append("\n##########################next: ") + .append(next) + .append("\n##########################pageNum: ") + .append(pageNum) + + .toString(); + } + } + + + private int capacity; + + private int currentSize; + private Node first;// 链表头 + private Node last;// 链表尾 + + + public LRUPageFrame(int capacity) { + this.currentSize = 0; + this.capacity = capacity; + + } + + /** + * 获取缓存中对象 + * 新的对象应该放在前面 + * + * @param pageNum + * @return + */ + public void access(int pageNum) { + if (capacity == 0) { + return; + } + + // 如果已经存在, 删除已经存在的 + removeContainedNode(pageNum); + + /** + * 向前追加 + */ + // 如果 first 为空, first=last=newNode + if (first == null && last == null) { + first = last = new Node(pageNum); + // 如果不为空 , first=newNode, first.next.pre = first + } else { + first = new Node(first, pageNum); + first.next.prev = first; + } + // 修改 size + currentSize++; + debugContent("addNewNode"); + + // 如果 size = capacity + 1, 去除last (额外考虑 capacity 为 1 的情况), last.next=null + if (currentSize == capacity + 1) { + last = last.prev; + last.next = null; + currentSize--; + debugContent("rmSpareNode"); + } + } + + private Node removeContainedNode(int pageNum) { + Node node = first; + while (node != null) { + + if (node.pageNum == pageNum) { + Node nodePre = node.prev; + Node nodeNext = node.next; + if (nodePre == null) { // 说明在第一个节点就 hit了 + first = nodeNext; + first.prev = null; + } else { + nodePre.next = nodeNext; + if (nodeNext != null) { + nodeNext.prev = nodePre; + } else { + last = nodePre; // 如果 nodeNext 为空, 说明原先 last 是 node, 现在是 nodePre + } + } + currentSize--; + return node; + } + node = node.next; + } + debugContent("removeContainedNode"); + return null; + } + + private void debugContent(String tag) { + log.debug("tag={}, currentSize={}, toString={}", tag, currentSize, debug()); + } + + + public String toString() { + StringBuilder buffer = new StringBuilder(); + Node node = first; + while (node != null) { + buffer.append(node.pageNum); + + node = node.next; + if (node != null) { + buffer.append(","); + } + } + return buffer.toString(); + } + + public String debug() { + StringBuilder buffer = new StringBuilder(); + Node node = first; + while (node != null) { + buffer + .append(node.debug()) + .append("\n##########################last: ") + .append(last) + .append("\n##########################capacity: ") + .append(capacity) + .append("\n##########################toString: ") + .append(toString()) + + ; + + node = node.next; + if (node != null) { + buffer.append("\n,"); + } + } + return buffer.toString() + "\n"; + } + + +} diff --git a/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/linklist/LRUPageFrameTest.java b/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/linklist/LRUPageFrameTest.java new file mode 100644 index 0000000000..7fd72fc2b4 --- /dev/null +++ b/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/linklist/LRUPageFrameTest.java @@ -0,0 +1,34 @@ +package com.coding.basic.linklist; + +import org.junit.Assert; + +import org.junit.Test; + + +public class LRUPageFrameTest { + + @Test + public void testAccess() { + LRUPageFrame frame = new LRUPageFrame(3); + frame.access(7); + frame.access(0); + frame.access(1); + Assert.assertEquals("1,0,7", frame.toString()); + frame.access(2); + Assert.assertEquals("2,1,0", frame.toString()); + frame.access(0); + Assert.assertEquals("0,2,1", frame.toString()); + frame.access(0); + Assert.assertEquals("0,2,1", frame.toString()); + frame.access(3); + Assert.assertEquals("3,0,2", frame.toString()); + frame.access(0); + Assert.assertEquals("0,3,2", frame.toString()); + frame.access(4); + Assert.assertEquals("4,0,3", frame.toString()); + frame.access(5); + Assert.assertEquals("5,4,0", frame.toString()); + + } + +} diff --git a/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/linklist/LinkedList.java b/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/linklist/LinkedList.java new file mode 100644 index 0000000000..d9c4ee3c7b --- /dev/null +++ b/students/1204187480/code/homework/coding/src/main/java/com/coding/basic/linklist/LinkedList.java @@ -0,0 +1,351 @@ +package com.coding.basic.linklist; + +import com.coding.basic.Iterator; +import com.coding.basic.List; + +public class LinkedList implements List { + + private Node head; + private int size = 0; + + public void add(Object o) { + Node newNode = new Node(o, null); + if (head == null) { + head = newNode; + } else { + node(size - 1).next = newNode; + } + size++; + } + + public void add(int index, Object o) { + checkForAdd(index); + if (index == size) { + add(o); + } else { + Node newNode = new Node(o, null); + if (index == 0) { + addFirst(o); + } else { + Node preNode = node(index - 1); + Node now = preNode.next; + preNode.next = newNode; + newNode.next = now; + size++; + } + } + + } + + private Node node(int index) { + Node x = head; + for (int i = 0; i < index; i++) { + x = x.next; + } + return x; + } + + public Object get(int index) { + checkIndex(index); + return node(index).data; + } + + /** + * 让被删除的引用的持有者指向下一个节点 + * + * @param index + * @return + */ + public Object remove(int index) { + final Object ret; + checkIndex(index); + if (index == 0) { + Node removeNode = head; + ret = head.data; + head = removeNode.next; + } else { + Node pre = node(index - 1); + Node removeNode = pre.next; + ret = removeNode.data; + pre.next = removeNode.next; + } + size--; + return ret; + } + + public int size() { + return size; + } + + public void addFirst(Object o) { + head = new Node(o, head); + ; + size++; + } + + public void addLast(Object o) { + add(o); + } + + public Object removeFirst() { + if (size == 0) { + return null; + } else { + return remove(0); + } + } + + public Object removeLast() { + return remove(size - 1); + } + + public LinkedListIterator iterator() { + return new LinkedListIterator(head); + } + + private void checkIndex(int index) { + if (index < 0 || index >= size) { + throw new ArrayIndexOutOfBoundsException(String.format("index=%s, size=%s", index, size)); + } + } + + private void checkForAdd(int index) { + if (index < 0 || index > size) { + throw new ArrayIndexOutOfBoundsException(String.format("index=%s, size=%s", index, size)); + } + } + + + @Override + public String toString() { + Iterator iterator = iterator(); + StringBuilder builder = new StringBuilder("["); + while ((iterator.hasNext())) { + builder.append(iterator.next()).append(','); + } + if (size() > 0) { + builder.deleteCharAt(builder.length() - 1); + } + return builder + .append(']') + .toString(); + } + + /** + * 把该链表逆置 + * 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse() { + if (size == 0) { + return; + } + Object[] datas = new Object[size]; + int i = 0; + // 迭代链表的数据生成数组 + Iterator iterator = iterator(); + while (iterator.hasNext()) { + datas[i++] = iterator.next(); + } + // 遍历数组越生成新的 链表 + Node newHead = new Node(datas[--i], null); + Node next = newHead; + for (int j = --i; j >= 0; j--) { + next.next = new Node(datas[j], null); + next = next.next; + + } + this.head = newHead; + + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + */ + public void removeFirstHalf() { + removeFirstSize(size >> 1); + } + + public void removeFirstSize(int firstSize) { + firstSize = firstSize > size() ? size() : firstSize; + LinkedListIterator iterator = iterator(); + int i = 1; + while (i++ <= firstSize) { + iterator.nextNode(); + } + if (size > 0) { + head = iterator.nextNode(); + size = size() - firstSize; + } + } + + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * + * @param i + * @param length + */ + public void remove(int i, int length) { + if (i == 0) { + removeFirstSize(length); + return; + } + if (i >= size || length == 0) { + return; + } + + int lastLenth = size - i; + length = length <= lastLenth ? length : lastLenth; + Node pre = node(i - 1); + int j = 0; + + Node next = pre; + while (j++ < length) { + next = next.next; + } + pre.next = next.next; + size = size - length; + + + } + + /** + * 假定当前链表和listB均包含已升序排列的整数 + * 从当前链表中取出那些listB所指定的元素 + * 例如当前链表 = 11->101->201->301->401->501->601->701 + * listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + * + * @param list + */ + public int[] getElements(LinkedList list) { + if (size() == 0) { + return new int[0]; + } + Iterator iterator = list.iterator(); + Node fromNode = iterator().nextNode(); + int fromIndex = 0; + + int[] retArray = new int[list.size()]; + int retIndex = 0; + while (iterator.hasNext()) { + int index = (int) iterator.next(); + Node node = node(fromNode, fromIndex, index); + fromIndex = index; + fromNode = node; + if (node == null) { + return retArray; + } else { + retArray[retIndex++] = (int)node.data; + } + } + return retArray; + } + + private Node node(Node fromNode, int fromIndex, int index) { + Node next = fromNode; + int nextIndex = fromIndex; + while (next != null && nextIndex < index) { + next = next.next; + nextIndex++; + } + if (nextIndex == index) { + return next; + } else { + return null; + } + } + + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 从当前链表中中删除在listB中出现的元素 + * + * @param list + */ + + public void subtract(LinkedList list) { + + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues() { + + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * + * @param min + * @param max + */ + public void removeRange(int min, int max) { + + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * + * @param list + */ + public LinkedList intersection(LinkedList list) { + return null; + } + + private static class Node { + Object data; + Node next; + + public Node() { + } + + public Node(Object data, Node next) { + this.data = data; + this.next = next; + } + } + + private class LinkedListIterator implements Iterator { + + private Node next; + + public LinkedListIterator() { + } + + private LinkedListIterator(Node next) { + this.next = next; + } + + @Override + public boolean hasNext() { + return next != null; + } + + @Override + public Object next() { + if (next == null) { + throw new IndexOutOfBoundsException("there is no node in list"); + } + Node ret = next; + next = next.next; + return ret.data; + } + + + private Node nextNode() { + if (next == null) { + throw new IndexOutOfBoundsException("there is no node in list"); + } + Node ret = next; + next = next.next; + return ret; + } + } +} diff --git a/students/1204187480/code/homework/coding/src/test/java/com/coding/api/ArraysTest.java b/students/1204187480/code/homework/coding/src/test/java/com/coding/api/ArraysTest.java new file mode 100644 index 0000000000..eb41a7e262 --- /dev/null +++ b/students/1204187480/code/homework/coding/src/test/java/com/coding/api/ArraysTest.java @@ -0,0 +1,22 @@ +package com.coding.api; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; + +/** + * Created by luoziyihao on 2/25/17. + */ +public class ArraysTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + + @Test + public void testCopyOf(){ + Object[] a = new Object[]{1, 2, 3, 4}; + Object[] b = Arrays.copyOf(a, 10); + logger.info("a={}, b={}", Arrays.toString(a), Arrays.toString(b)); + } +} diff --git a/students/1204187480/code/homework/coding/src/test/java/com/coding/api/SystemTest.java b/students/1204187480/code/homework/coding/src/test/java/com/coding/api/SystemTest.java new file mode 100644 index 0000000000..efc4022378 --- /dev/null +++ b/students/1204187480/code/homework/coding/src/test/java/com/coding/api/SystemTest.java @@ -0,0 +1,24 @@ +package com.coding.api; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; + +/** + * Created by luoziyihao on 2/25/17. + */ +public class SystemTest { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Test + public void testArrayCopy() { + int[] a = new int[]{1, 2, 3, 4, 5, 6, 7}; + int[] b = new int[]{11, 22, 33, 44, 55, 66, 77}; + System.arraycopy(a, 2, b, 4, 3); + logger.info("b={}", Arrays.toString(b)); + + } +} diff --git a/students/1204187480/code/homework/coding/src/test/java/com/coding/basic/LinkedListTest.java b/students/1204187480/code/homework/coding/src/test/java/com/coding/basic/LinkedListTest.java new file mode 100644 index 0000000000..9e951354ef --- /dev/null +++ b/students/1204187480/code/homework/coding/src/test/java/com/coding/basic/LinkedListTest.java @@ -0,0 +1,202 @@ +package com.coding.basic; + +import com.coding.basic.linklist.LinkedList; +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; + +/** + * Created by luoziyihao on 3/23/17. + */ +public class LinkedListTest { + + @Test + public void add() throws Exception { + + } + + @Test + public void add1() throws Exception { + + } + + @Test + public void get() throws Exception { + + } + + @Test + public void remove() throws Exception { + + } + + @Test + public void size() throws Exception { + + } + + @Test + public void addFirst() throws Exception { + + } + + @Test + public void addLast() throws Exception { + + } + + @Test + public void removeFirst() throws Exception { + + } + + @Test + public void removeLast() throws Exception { + + } + + @Test + public void removeFirstHalf() throws Exception { + LinkedList linkedList = createAndFillLinkedList(0); + linkedList.removeFirstHalf(); + Assert.assertEquals("[]", linkedList.toString()); + } + + @Test + public void removeFirstHalf1() throws Exception { + LinkedList linkedList = createAndFillLinkedList(1); + linkedList.removeFirstHalf(); + Assert.assertEquals("[1]", linkedList.toString()); + } + + @Test + public void removeFirstHalf2() throws Exception { + LinkedList linkedList = createAndFillLinkedList(2); + linkedList.removeFirstHalf(); + Assert.assertEquals("[2]", linkedList.toString()); + } + + @Test + public void removeFirstHalf3() throws Exception { + LinkedList linkedList = createAndFillLinkedList(3); + linkedList.removeFirstHalf(); + Assert.assertEquals("[2,3]", linkedList.toString()); + } + + private LinkedList createAndFillLinkedList() { + return createAndFillLinkedList(4); + } + + private LinkedList createAndFillLinkedList(int length) { + return createAndFillLinkedList(1, length); + } + + private LinkedList createAndFillLinkedList(int start, int length) { + LinkedList linkedList = new LinkedList(); + for (int i = start; i <= length; i++) { + linkedList.add(i); + } + return linkedList; + } + + @Test + public void remove1() throws Exception { + LinkedList list = createAndFillLinkedList(4); + list.remove(0, 0); + Assert.assertEquals("[1,2,3,4]", list.toString()); + } + + @Test + public void remove2() throws Exception { + LinkedList list = createAndFillLinkedList(4); + list.remove(0, 1); + Assert.assertEquals("[2,3,4]", list.toString()); + } + + @Test + public void remove3() throws Exception { + LinkedList list = createAndFillLinkedList(4); + list.remove(1, 0); + Assert.assertEquals("[1,2,3,4]", list.toString()); + } + + @Test + public void remove4() throws Exception { + LinkedList list = createAndFillLinkedList(4); + list.remove(1, 1); + Assert.assertEquals("[1,3,4]", list.toString()); + } + + @Test + public void remove5() throws Exception { + LinkedList list = createAndFillLinkedList(4); + list.remove(1, 3); + Assert.assertEquals("[1]", list.toString()); + } + + @Test + public void remove6() throws Exception { + LinkedList list = createAndFillLinkedList(4); + list.remove(1, 4); + Assert.assertEquals("[1]", list.toString()); + } + + @Test + public void remove7() throws Exception { + LinkedList list = createAndFillLinkedList(4); + list.remove(1, 5); + Assert.assertEquals("[1]", list.toString()); + } + + @Test + public void getElements() throws Exception { +// LinkedList listA = createAndFillLinkedList(0, 8); +// LinkedList listB = createAndFillLinkedList(4, 4); +// Assert.assertEquals("[4,5,6,7]", Arrays.toString(listA.getElements(listB))); + + } + + @Test + public void subtract() throws Exception { + + } + + @Test + public void removeDuplicateValues() throws Exception { + + } + + @Test + public void removeRange() throws Exception { + + } + + @Test + public void intersection() throws Exception { + + } + + @Test + public void iterator() throws Exception { + + List linkedList = new LinkedList(); + linkedList.add("1"); + linkedList.add("2"); + linkedList.add("3"); + linkedList.add("4"); + Assert.assertEquals("[1,2,3,4]", linkedList.toString()); + } + + @Test + public void reverse() throws Exception { + LinkedList linkedList = new LinkedList(); + linkedList.add("1"); + linkedList.add("2"); + linkedList.add("3"); + linkedList.add("4"); + linkedList.reverse(); + Assert.assertEquals("[4,3,2,1]", linkedList.toString()); + } + +} \ No newline at end of file diff --git a/students/1204187480/code/homework/coding/src/test/java/com/coding/basic/array/ArrayListTest.java b/students/1204187480/code/homework/coding/src/test/java/com/coding/basic/array/ArrayListTest.java new file mode 100644 index 0000000000..e70c52a725 --- /dev/null +++ b/students/1204187480/code/homework/coding/src/test/java/com/coding/basic/array/ArrayListTest.java @@ -0,0 +1,37 @@ +package com.coding.basic.array; + +import com.coding.basic.List; +import com.coding.basic.array.ArrayList; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * Created by luoziyihao on 2/25/17. + */ +public class ArrayListTest { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + + private List list = new ArrayList(); + + @Before + public void before() { + + } + + @Test + public void add() throws Exception { + list.add(1); + } + + @Test + public void get() throws Exception { + add(); + logger.info("{}", list.get(0)); + } + +} \ No newline at end of file diff --git a/students/1204187480/code/homework/coding/src/test/java/com/coding/basic/array/ArrayUtilTest.java b/students/1204187480/code/homework/coding/src/test/java/com/coding/basic/array/ArrayUtilTest.java new file mode 100644 index 0000000000..04c8b51547 --- /dev/null +++ b/students/1204187480/code/homework/coding/src/test/java/com/coding/basic/array/ArrayUtilTest.java @@ -0,0 +1,76 @@ +package com.coding.basic.array; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; + +import static org.junit.Assert.*; + +/** + * Created by luoziyihao on 3/5/17. + */ +public class ArrayUtilTest { + + private ArrayUtil creatArrayUtil(){ + return new ArrayUtil(); + } + + @Test + public void reverseArray() throws Exception { + int[] origin = new int[]{1, 2, 3}; + int[] destArray = new int[]{3, 2, 1}; + creatArrayUtil().reverseArray(origin); + Assert.assertArrayEquals(destArray, origin); + } + + @Test + public void removeZero() throws Exception { + int[] origin = new int[]{1, 2, 3, 0, 10}; + int[] destArray = new int[]{1, 2, 3, 10}; + int[] retArray = creatArrayUtil().removeZero(origin); + Assert.assertArrayEquals(destArray, retArray); + } + + @Test + public void merge() throws Exception { + int[] a = new int[]{1, 2, 3}; + int[] b = new int[]{2, 3}; + + int[] newArray = creatArrayUtil().merge(a, b); + info(newArray); + assertArrayEquals(new int[]{1, 2, 3}, newArray); + } + + @Test + public void grow() throws Exception { + assertArrayEquals(new int[]{1, 2, 0, 0}, creatArrayUtil().grow(new int[]{1, 2}, 2)); + } + + @Test + public void fibonacci() throws Exception { + assertArrayEquals(new int[]{1, 1, 2, 3, 5, 8}, creatArrayUtil().fibonacci(10)); + } + + @Test + public void getPrimes() throws Exception { + int max = Double.valueOf(Math.pow(2, 4)).intValue(); + assertArrayEquals(new int[]{2, 3, 5, 7, 11, 13}, creatArrayUtil().getPrimes(max)); + } + + @Test + public void getPerfectNumbers() throws Exception { + int max = Double.valueOf(Math.pow(2, 8)).intValue(); + assertArrayEquals(new int[]{6, 28}, creatArrayUtil().getPerfectNumbers(max)); + + } + + @Test + public void join() throws Exception { + assertEquals("1_2_3_10", creatArrayUtil().join(new int[]{1, 2, 3, 10}, "_")); + } + + private void info(int[] array) { + System.out.println(Arrays.toString(array)); + } +} \ No newline at end of file diff --git a/students/1204187480/code/homework/common/pom.xml b/students/1204187480/code/homework/common/pom.xml new file mode 100644 index 0000000000..3cbad444b6 --- /dev/null +++ b/students/1204187480/code/homework/common/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + common + jar + + com.coding + parent-dependencies + 1.0-SNAPSHOT + ../parent-dependencies/pom.xml + + + \ No newline at end of file diff --git a/students/1204187480/code/homework/common/src/main/java/com/coding/common/util/BeanUtils.java b/students/1204187480/code/homework/common/src/main/java/com/coding/common/util/BeanUtils.java new file mode 100755 index 0000000000..67dd8fd1f1 --- /dev/null +++ b/students/1204187480/code/homework/common/src/main/java/com/coding/common/util/BeanUtils.java @@ -0,0 +1,144 @@ +package com.coding.common.util; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.math.BigDecimal; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +/** + * Created by luoziyihao on 5/25/16. + */ +public class BeanUtils { + + + public static final String SET = "set"; + public static final String GET = "get"; + // 日志输出类 + private final Logger log = LoggerFactory.getLogger(this.getClass()); + private final StringUtils2 stringUtils = new StringUtils2(); + + public Object setInvoke(Object para, String methodName, Object obj) { + Method method = null; + Object returnObj = null; + try { + + method = obj.getClass().getMethod(methodName, para.getClass()); + returnObj = method.invoke(obj, para); + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return returnObj; + } + + public Object getInvoke(String methodName, Object obj) { + Method method = null; + Object returnObj = null; + try { + method = obj.getClass().getMethod(methodName); + returnObj = method.invoke(obj); + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return returnObj; + } + + public Object invokeWithNoParamter(String methodName, Object obj) { + Method method; + Object returnObj = null; + try { + method = obj.getClass().getMethod(methodName); + returnObj = method.invoke(obj); + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return returnObj; + } + + + + public Object getPara(String paraName, Object object) { + if (stringUtils.isSpaceOrNull(paraName)) { + throw new RuntimeException("paraname is null or space"); + } + String methodName = new StringBuilder().append(GET).append(stringUtils.toUpperCase(paraName, 0)).toString(); + return getInvoke(methodName, object); + } + + + + public Object setPara(Object para, String paraName, Object object) { + if (stringUtils.isSpaceOrNull(paraName)) { + throw new RuntimeException("paraname is null or space"); + } + String methodName = new StringBuilder().append(SET).append(stringUtils.toUpperCase(paraName, 0)).toString(); + return setInvoke(para, methodName, object); + } + + public T get(String paraName, Object object, Class clazz) { + return (T) getPara(paraName, object); + } + + public Integer getInt(String paraName, Object object) { + return (Integer) getPara(paraName, object); + } + + public Long getLong(String paraName, Object object) { + return (Long) getPara(paraName, object); + } + + public Double getDouble(String paraName, Object object) { + return (Double) getPara(paraName, object); + } + + public BigDecimal getBigDecimal(String paraName, Object object) { + return (BigDecimal) getPara(paraName, object); + } + + public String getString(String paraName, Object object) { + return getPara(paraName, object).toString(); + } + + public Date getDate(String paraName, Object object) { + return (Date) getPara(paraName, object); + } + + public Long getLongByString(String paraName, Object object) { + return Long.parseLong(getString(paraName, object)); + } + + public Integer getIntByString(String paraName, Object object) { + return Integer.parseInt(getString(paraName, object)); + } + + public Double getDoubleByString(String paraName, Object object) { + return Double.parseDouble(getString(paraName, object)); + } + + public BigDecimal getBigDecimalByString(String paraName, Object object) { + return new BigDecimal(getString(paraName, object)); + } + + private final static String GETTER_PRE = "get"; + public Map describe(Object model) { + Method[] methods = model.getClass().getDeclaredMethods(); //获取实体类的所有属性,返回Field数组 + Map properties = new HashMap<>(); + for (Method method : methods) { + String methodName = method.getName(); + if (methodName.startsWith(GETTER_PRE)) { + try { + Object o = method.invoke(model); + String valueName = stringUtils.toLowwerCase(methodName.substring(GETTER_PRE.length()), 0); + properties.put(valueName, o); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException(e); + } + } + } + return properties; + } +} diff --git a/students/1204187480/code/homework/common/src/main/java/com/coding/common/util/ByteUtils.java b/students/1204187480/code/homework/common/src/main/java/com/coding/common/util/ByteUtils.java new file mode 100644 index 0000000000..4126765ff1 --- /dev/null +++ b/students/1204187480/code/homework/common/src/main/java/com/coding/common/util/ByteUtils.java @@ -0,0 +1,21 @@ +package com.coding.common.util; + +/** + * Created by luoziyihao on 5/2/17. + */ +public abstract class ByteUtils { + + public static String byteToHexString(byte[] codes ){ + StringBuffer buffer = new StringBuffer(); + for(int i=0;i listAllFiles(File directory) { + Preconditions.checkNotNull(directory); + Preconditions.checkArgument(directory.isDirectory() + , "file=%s is not directory", directory.getPath()); + return listAllFiles(new ArrayList<>(), directory); + } + + private static List listAllFiles(List files, File directory) { + File[] fileArr = directory.listFiles(); + if (fileArr == null) { + return files; + } + for (File file : fileArr) { + if (file.isDirectory()) { + files = listAllFiles(files, file); + } else { + files.add(file); + } + } + return files; + } + + + public static String getCanonicalPath(File file) { + Preconditions.checkNotNull(file); + try { + return file.getCanonicalPath(); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + + + public static byte[] getBytes(File classFile) { + // byteArrayOutputStream, 可写的动长数组 + ByteArrayOutputStream baos = null; + BufferedInputStream bis = null; + try { + baos = new ByteArrayOutputStream(); + bis = new BufferedInputStream(new FileInputStream(classFile)); + int intTmp = bis.read(); + while (intTmp != -1) { + baos.write(intTmp); + intTmp = bis.read(); + } + return baos.toByteArray(); + } catch (IOException e) { + throw new IllegalStateException(e); + } finally { + IOUtils2.close(baos); + IOUtils2.close(bis); + } + } + + public static InputStream openStream(String classPath) { + return ClassLoader.getSystemResourceAsStream(classPath); + } + +} diff --git a/students/1204187480/code/homework/common/src/main/java/com/coding/common/util/IOUtils2.java b/students/1204187480/code/homework/common/src/main/java/com/coding/common/util/IOUtils2.java new file mode 100644 index 0000000000..889c6cefb6 --- /dev/null +++ b/students/1204187480/code/homework/common/src/main/java/com/coding/common/util/IOUtils2.java @@ -0,0 +1,35 @@ +package com.coding.common.util; + +import java.io.*; +import java.util.List; +import java.util.stream.Collectors; + +/** + * Created by luoziyihao on 5/2/17. + */ +public abstract class IOUtils2 { + + public static void close(Closeable closeable) { + if (closeable != null) { + try { + closeable.close(); + } catch (IOException e) { + throw new IllegalStateException(e); + + } + } + } + + + public static List readToStringList(InputStream inputStream) { + BufferedReader br = null; + try { + br = new BufferedReader(new InputStreamReader(inputStream)); + return br.lines().collect(Collectors.toList()); + } finally { + close(br); + } + + } + +} diff --git a/students/1204187480/code/homework/common/src/main/java/com/coding/common/util/StringUtils2.java b/students/1204187480/code/homework/common/src/main/java/com/coding/common/util/StringUtils2.java new file mode 100644 index 0000000000..0883351690 --- /dev/null +++ b/students/1204187480/code/homework/common/src/main/java/com/coding/common/util/StringUtils2.java @@ -0,0 +1,34 @@ +package com.coding.common.util; + +/** + * Created by luoziyihao on 3/5/17. + */ +public class StringUtils2 { + + /** + * 改变指定位置的 char的大小写 + */ + public String toUpperCase(String str, int index) { + char[] chars = str.toCharArray(); + if (index + 1 > chars.length) { + throw new RuntimeException("the char at the index don't exist"); + } + chars[index] = Character.toUpperCase(chars[index]); + return new String(chars); + } + + /** + * 改变指定位置的 char的大小写 + */ + public String toLowwerCase(String str, int index) { + char[] chars = str.toCharArray(); + if (index + 1 > chars.length ) {throw new RuntimeException("the char at the index don't exist");} + chars[index] = Character.toLowerCase(chars[index]); + return new String(chars); + } + + public boolean isSpaceOrNull(String paraName) { + return (paraName == null || paraName.trim().isEmpty()); + } + +} diff --git a/students/1204187480/code/homework/common/src/test/java/com/coding/api/ArraysTest.java b/students/1204187480/code/homework/common/src/test/java/com/coding/api/ArraysTest.java new file mode 100644 index 0000000000..eb41a7e262 --- /dev/null +++ b/students/1204187480/code/homework/common/src/test/java/com/coding/api/ArraysTest.java @@ -0,0 +1,22 @@ +package com.coding.api; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; + +/** + * Created by luoziyihao on 2/25/17. + */ +public class ArraysTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + + @Test + public void testCopyOf(){ + Object[] a = new Object[]{1, 2, 3, 4}; + Object[] b = Arrays.copyOf(a, 10); + logger.info("a={}, b={}", Arrays.toString(a), Arrays.toString(b)); + } +} diff --git a/students/1204187480/code/homework/common/src/test/java/com/coding/api/SystemTest.java b/students/1204187480/code/homework/common/src/test/java/com/coding/api/SystemTest.java new file mode 100644 index 0000000000..efc4022378 --- /dev/null +++ b/students/1204187480/code/homework/common/src/test/java/com/coding/api/SystemTest.java @@ -0,0 +1,24 @@ +package com.coding.api; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; + +/** + * Created by luoziyihao on 2/25/17. + */ +public class SystemTest { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Test + public void testArrayCopy() { + int[] a = new int[]{1, 2, 3, 4, 5, 6, 7}; + int[] b = new int[]{11, 22, 33, 44, 55, 66, 77}; + System.arraycopy(a, 2, b, 4, 3); + logger.info("b={}", Arrays.toString(b)); + + } +} diff --git a/students/1204187480/code/homework/common/src/test/java/com/coding/common/util/ByteUtilsTest.java b/students/1204187480/code/homework/common/src/test/java/com/coding/common/util/ByteUtilsTest.java new file mode 100644 index 0000000000..62dd4907cc --- /dev/null +++ b/students/1204187480/code/homework/common/src/test/java/com/coding/common/util/ByteUtilsTest.java @@ -0,0 +1,20 @@ +package com.coding.common.util; + +import org.junit.Test; + +/** + * Created by luoziyihao on 5/2/17. + */ +public class ByteUtilsTest { + + @Test + public void testByteToHexString(){ + byte[] bytes = new byte[]{ + 1, + (byte) 255 + }; + System.out.println(ByteUtils.byteToHexString(bytes)); + System.out.println(Integer.toHexString(255)); + } + +} \ No newline at end of file diff --git a/students/1204187480/code/homework/common/src/test/java/com/coding/common/util/FileUtils2Test.java b/students/1204187480/code/homework/common/src/test/java/com/coding/common/util/FileUtils2Test.java new file mode 100644 index 0000000000..cb58cf99c5 --- /dev/null +++ b/students/1204187480/code/homework/common/src/test/java/com/coding/common/util/FileUtils2Test.java @@ -0,0 +1,35 @@ +package com.coding.common.util; + +import org.junit.Test; + +import java.io.File; +import java.util.List; + +/** + * Created by luoziyihao on 4/28/17. + */ +public class FileUtils2Test { + @Test + public void getCanonicalPath() throws Exception { + System.out.println(FileUtils2.getCanonicalPath(new File(""))); + } + + @Test + public void getBytes() throws Exception { + byte[] bytes = FileUtils2.getBytes(new File("pom.xml")); + System.out.println(new String(bytes)); + System.out.println(ByteUtils.byteToHexString(bytes)); + + } + + + @Test + public void listAllFiles() throws Exception { + String currentPath = new File("").getCanonicalPath(); + List files = FileUtils2.listAllFiles(new File(currentPath )); + for (File file : files) { + System.out.println(file.getCanonicalPath()); + } + } + +} \ No newline at end of file diff --git a/students/1204187480/code/homework/common/src/test/java/com/coding/common/util/IOUtils2Test.java b/students/1204187480/code/homework/common/src/test/java/com/coding/common/util/IOUtils2Test.java new file mode 100644 index 0000000000..6870919037 --- /dev/null +++ b/students/1204187480/code/homework/common/src/test/java/com/coding/common/util/IOUtils2Test.java @@ -0,0 +1,26 @@ +package com.coding.common.util; + +import org.junit.Test; + +import java.util.List; + +import static com.coding.common.util.FileUtils2.openStream; +import static com.coding.common.util.IOUtils2.readToStringList; +import static org.junit.Assert.*; + +/** + *

+ *

+ * + * @author raoxiang + * @version 6/13/17 + * @since 1.8 + */ +public class IOUtils2Test { + @Test + public void readToStringListTest() throws Exception { + List poms = readToStringList(openStream("test.json")); + System.out.println(poms); + } + +} \ No newline at end of file diff --git a/students/1204187480/code/homework/common/src/test/resources/test.json b/students/1204187480/code/homework/common/src/test/resources/test.json new file mode 100644 index 0000000000..ccc0682ac2 --- /dev/null +++ b/students/1204187480/code/homework/common/src/test/resources/test.json @@ -0,0 +1,4 @@ +{ + "key1": "value1" + , "key2": "value2" +} \ No newline at end of file diff --git a/students/1204187480/code/homework/parent-dependencies/pom.xml b/students/1204187480/code/homework/parent-dependencies/pom.xml new file mode 100644 index 0000000000..b961e90c59 --- /dev/null +++ b/students/1204187480/code/homework/parent-dependencies/pom.xml @@ -0,0 +1,169 @@ + + 4.0.0 + + com.coding + parent-dependencies + pom + 1.0-SNAPSHOT + https://github.com/luoziyihao/coding2017 + + + + alimaven + aliyun maven + http://maven.aliyun.com/nexus/content/groups/public/ + + true + + + true + + + + + + alimaven + aliyun maven + http://maven.aliyun.com/nexus/content/groups/public/ + + true + + + true + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/libs-snapshot + + true + + + + + + + UTF-8 + UTF-8 + 1.8 + UTF-8 + 1.8 + 1.8 + 3.0 + 1.1.7 + 1.1.7 + 1.2 + 1.2.17 + 4.12 + 3.4 + 4.1 + 2.5 + 1.9.2 + 19.0 + 1.1.6 + 1.16.10 + 1.2.22 + 0.2.0 + 2.9.4 + + + + + + + ch.qos.logback + logback-classic + ${logback-classic.version} + + + + commons-logging + commons-logging + ${commons-logging.version} + + + log4j + log4j + ${log4j.version} + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + commons-io + commons-io + ${commons-io.version} + + + commons-beanutils + commons-beanutils + ${commons-beanutils.version} + + + com.google.guava + guava + ${guava.version} + + + org.projectlombok + lombok + ${lombok.version} + + + joda-time + joda-time + ${joda-time.version} + + + io.reactivex + rxjava + ${rxjava.version} + + + com.alibaba + fastjson + ${fastjson.version} + + + com.shekhargulati + strman + ${strman.version} + + + + + + junit + junit + ${junit.version} + + + + + ${project.artifactId} + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + \ No newline at end of file diff --git a/students/1204187480/code/homework/parent/pom.xml b/students/1204187480/code/homework/parent/pom.xml new file mode 100644 index 0000000000..e6a94a2e4f --- /dev/null +++ b/students/1204187480/code/homework/parent/pom.xml @@ -0,0 +1,23 @@ + + + 4.0.0 + parent + pom + manage the dependencies for modules + + com.coding + parent-dependencies + 1.0-SNAPSHOT + ../parent-dependencies/pom.xml + + + + + com.coding + common + 1.0-SNAPSHOT + + + + \ No newline at end of file diff --git a/students/1204187480/code/homework/pom.xml b/students/1204187480/code/homework/pom.xml new file mode 100644 index 0000000000..28ac74f159 --- /dev/null +++ b/students/1204187480/code/homework/pom.xml @@ -0,0 +1,18 @@ + + + 4.0.0 + com.coding + coding2017 + 1.0-SNAPSHOT + pom + + parent-dependencies + common + parent + coding + coderising + + + + diff --git "a/students/1204187480/note/homework/cpu, \345\206\205\345\255\230, \347\243\201\347\233\230, \346\214\207\344\273\244-\346\274\253\350\260\210\350\256\241\347\256\227\346\234\272" "b/students/1204187480/note/homework/cpu, \345\206\205\345\255\230, \347\243\201\347\233\230, \346\214\207\344\273\244-\346\274\253\350\260\210\350\256\241\347\256\227\346\234\272" new file mode 100644 index 0000000000..e69de29bb2 diff --git a/students/1204187480/note/todo/homework.md b/students/1204187480/note/todo/homework.md new file mode 100644 index 0000000000..5f111a9ea6 --- /dev/null +++ b/students/1204187480/note/todo/homework.md @@ -0,0 +1,8 @@ +# 0326 操作系统中的lru算法 + +ClassFileLoader + +LRUPageFrame + +深入理解java虚拟机 第6章 + diff --git a/students/1241588932/design-patterns-enan/pom.xml b/students/1241588932/design-patterns-enan/pom.xml new file mode 100644 index 0000000000..fd2c597497 --- /dev/null +++ b/students/1241588932/design-patterns-enan/pom.xml @@ -0,0 +1,54 @@ + + 4.0.0 + + com.coderising + design-patterns-enan + 0.0.1-SNAPSHOT + jar + + design-patterns-enan + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + org.projectlombok + lombok + 1.16.16 + true + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 1.8 + 1.8 + ${project.build.sourceEncoding} + + + + + diff --git a/students/1241588932/design-patterns-enan/src/main/java/first/TagBuilder.java b/students/1241588932/design-patterns-enan/src/main/java/first/TagBuilder.java new file mode 100644 index 0000000000..586cbf37ef --- /dev/null +++ b/students/1241588932/design-patterns-enan/src/main/java/first/TagBuilder.java @@ -0,0 +1,39 @@ +package first; + +public class TagBuilder { + + private TagNode tagNode; + private TagNode currentTagNode; + private TagNode superTagNode; + + public TagBuilder(String tagName) { + this.tagNode = new TagNode(tagName); + this.currentTagNode = this.tagNode; + this.superTagNode = null; + } + + public TagBuilder addChild(String childTagName) { + this.superTagNode = this.currentTagNode; + TagNode tagNode = new TagNode(childTagName); + this.currentTagNode.add(tagNode); + this.currentTagNode = tagNode; + return this; + } + + public TagBuilder setAttribute(String key, String value) { + this.currentTagNode.setAttribute(key, value); + return this; + } + + public TagBuilder addSibling(String siblingTagName) { + TagNode tagNode = new TagNode(siblingTagName); + this.superTagNode.add(tagNode); + this.currentTagNode = tagNode; + return this; + } + + public TagNode build() { + return tagNode; + } + +} diff --git a/students/1241588932/design-patterns-enan/src/main/java/first/TagBuilderTest.java b/students/1241588932/design-patterns-enan/src/main/java/first/TagBuilderTest.java new file mode 100644 index 0000000000..d17f0592f2 --- /dev/null +++ b/students/1241588932/design-patterns-enan/src/main/java/first/TagBuilderTest.java @@ -0,0 +1,41 @@ +package first; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class TagBuilderTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testToXML() { + + TagBuilder builder = new TagBuilder("order"); + + String xml = builder.addChild("line-items") + .addChild("line-item").setAttribute("pid", "P3677").setAttribute("qty", "3") + .addSibling("line-item").setAttribute("pid", "P9877").setAttribute("qty", "10") + .build() + .toXML(); + + String expected = "" + + "" + + "" + + "" + + "" + + ""; + + System.out.println(xml); + assertEquals(expected, xml); + } + +} diff --git a/students/1241588932/design-patterns-enan/src/main/java/first/TagNode.java b/students/1241588932/design-patterns-enan/src/main/java/first/TagNode.java new file mode 100644 index 0000000000..f27f48db82 --- /dev/null +++ b/students/1241588932/design-patterns-enan/src/main/java/first/TagNode.java @@ -0,0 +1,83 @@ +package first; + +import java.util.ArrayList; +import java.util.List; + +public class TagNode { + private String tagName; + private String tagValue; + private List children = new ArrayList<>(); + private List attributes = new ArrayList<>(); + + public TagNode(String name){ + this.tagName = name; + } + public void add(TagNode child){ + this.children.add(child); + } + public void setAttribute(String name, String value) { + Attribute attr = findAttribute(name); + if(attr != null){ + attr.value = value; + return; + } + + attributes.add(new Attribute(name,value)); + } + private Attribute findAttribute(String name){ + for(Attribute attr : attributes){ + if(attr.name.equals(name)){ + return attr; + } + } + return null; + } + public void setValue(String value) { + this.tagValue = value; + + } + public String getTagName() { + return tagName; + } + public List getChildren() { + return children; + } + + private static class Attribute{ + public Attribute(String name, String value) { + this.name = name; + this.value = value; + } + String name; + String value; + + } + public String toXML(){ + return toXML(this); + } + private String toXML(TagNode node){ + StringBuilder buffer = new StringBuilder(); + buffer.append("<").append(node.tagName); + if(node.attributes.size()> 0){ + for(int i=0;i"); + return buffer.toString(); + } + buffer.append(">"); + for(TagNode childNode : node.children){ + buffer.append(toXML(childNode)); + } + buffer.append(""); + + + return buffer.toString(); + } + private String toXML(Attribute attr){ + return attr.name+"=\""+attr.value + "\""; + } +} diff --git a/students/1241588932/ood-assignment-enan/pom.xml b/students/1241588932/ood-assignment-enan/pom.xml new file mode 100644 index 0000000000..ad245eee9f --- /dev/null +++ b/students/1241588932/ood-assignment-enan/pom.xml @@ -0,0 +1,54 @@ + + 4.0.0 + + com.coderising + ood-assignment-enan + 0.0.1-SNAPSHOT + jar + + ood-assignment-enan + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + org.projectlombok + lombok + 1.16.16 + true + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 1.8 + 1.8 + ${project.build.sourceEncoding} + + + + + diff --git a/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/config/Configuration.java b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/config/Configuration.java new file mode 100644 index 0000000000..e468795316 --- /dev/null +++ b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/config/Configuration.java @@ -0,0 +1,27 @@ +package com.coderising.ood.srp.config; + +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + private static final String CONFIG_FILE_NAME = "email_config.properties"; + + static Map configurations = new HashMap<>(); + static{ + // TODO 从配置文件中加载配置到 map 中 + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public static String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/config/ConfigurationKeys.java b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/config/ConfigurationKeys.java new file mode 100644 index 0000000000..7fe226d1bd --- /dev/null +++ b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/config/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp.config; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/dao/UserDao.java b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/dao/UserDao.java new file mode 100644 index 0000000000..fb6970cee5 --- /dev/null +++ b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/dao/UserDao.java @@ -0,0 +1,32 @@ +package com.coderising.ood.srp.dao; + +import com.coderising.ood.srp.entity.User; +import com.coderising.ood.srp.util.DBUtil; + +import java.util.List; + +/** + * Created by Enan on 17/6/14. + */ +public class UserDao { + + private static UserDao INSTANCE; + + public static UserDao getInstance() { + if (INSTANCE == null) { + synchronized (UserDao.class) { + INSTANCE = new UserDao(); + } + } + return INSTANCE; + } + + private UserDao() {} + + public List querySubscriptedUsersByProductID(String productID) { + String sql = "Select name, email from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + return DBUtil.query(sql); + } +} diff --git a/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/entity/Product.java b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/entity/Product.java new file mode 100644 index 0000000000..70b2c7870c --- /dev/null +++ b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/entity/Product.java @@ -0,0 +1,15 @@ +package com.coderising.ood.srp.entity; + +import lombok.Builder; +import lombok.Data; + +/** + * Created by Enan on 17/6/14. + */ +@Data +@Builder +public class Product { + + private String productID; + private String productDesc; +} diff --git a/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/entity/User.java b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/entity/User.java new file mode 100644 index 0000000000..0f79352cf4 --- /dev/null +++ b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/entity/User.java @@ -0,0 +1,13 @@ +package com.coderising.ood.srp.entity; + +import lombok.Data; + +/** + * Created by Enan on 17/6/14. + */ +@Data +public class User { + + private String name; + private String email; +} diff --git a/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/main.java b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/main.java new file mode 100644 index 0000000000..af2b5ce8f1 --- /dev/null +++ b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/main.java @@ -0,0 +1,21 @@ +package com.coderising.ood.srp; + +import com.coderising.ood.srp.service.IPromotionMail; +import com.coderising.ood.srp.service.impl.PromotionMailImpl; +import com.coderising.ood.srp.service.impl.ReadProductConfigImpl; +import com.coderising.ood.srp.service.impl.UserServiceImpl; + +import java.io.File; +import java.net.URL; + +/** + * Created by Enan on 17/6/18. + */ +public class main { + + public static void main(String[] args) { + IPromotionMail promotionMail = new PromotionMailImpl(new UserServiceImpl(), new ReadProductConfigImpl()); + URL base = Thread.currentThread().getContextClassLoader().getResource(""); + promotionMail.send(new File(base.getFile(), "product_promotion.txt")); + } +} diff --git a/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/service/IPromotionMail.java b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/service/IPromotionMail.java new file mode 100644 index 0000000000..ba940b09d8 --- /dev/null +++ b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/service/IPromotionMail.java @@ -0,0 +1,11 @@ +package com.coderising.ood.srp.service; + +import java.io.File; + +/** + * Created by Enan on 17/6/18. + */ +public interface IPromotionMail { + + void send(File file); +} diff --git a/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/service/IReadProductConfig.java b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/service/IReadProductConfig.java new file mode 100644 index 0000000000..1b2c45d1ee --- /dev/null +++ b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/service/IReadProductConfig.java @@ -0,0 +1,16 @@ +package com.coderising.ood.srp.service; + +import com.coderising.ood.srp.entity.Product; + +import java.io.File; +import java.io.IOException; +import java.util.Collection; + +/** + * Created by Enan on 17/6/18. + */ +public interface IReadProductConfig { + + Collection read(File file) throws IOException; + +} diff --git a/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/service/IUserService.java b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/service/IUserService.java new file mode 100644 index 0000000000..652ba08fbb --- /dev/null +++ b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/service/IUserService.java @@ -0,0 +1,13 @@ +package com.coderising.ood.srp.service; + +import com.coderising.ood.srp.entity.User; + +import java.util.Collection; + +/** + * Created by Enan on 17/6/18. + */ +public interface IUserService { + + Collection querySubscriptedUsersByProductID(String productID); +} diff --git a/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/service/impl/PromotionMailImpl.java b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/service/impl/PromotionMailImpl.java new file mode 100644 index 0000000000..497f16ccfd --- /dev/null +++ b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/service/impl/PromotionMailImpl.java @@ -0,0 +1,66 @@ +package com.coderising.ood.srp.service.impl; + +import com.coderising.ood.srp.config.Configuration; +import com.coderising.ood.srp.config.ConfigurationKeys; +import com.coderising.ood.srp.entity.Product; +import com.coderising.ood.srp.entity.User; +import com.coderising.ood.srp.service.IPromotionMail; +import com.coderising.ood.srp.service.IReadProductConfig; +import com.coderising.ood.srp.service.IUserService; +import com.coderising.ood.srp.util.MailUtil; + +import java.io.File; +import java.io.IOException; +import java.util.Collection; +import java.util.List; + +/** + * Created by Enan on 17/6/18. + */ +public class PromotionMailImpl implements IPromotionMail { + + private IUserService userService; + private IReadProductConfig readProductConfig; + + private static final String SUBJECT = "您关注的产品降价了"; + private static final String MESSAGE = "尊敬的 %s, 您关注的产品 %s 降价了,欢迎购买!"; + + public PromotionMailImpl (IUserService iUserService, IReadProductConfig iReadProductConfig) { + this.userService = iUserService; + this.readProductConfig = iReadProductConfig; + } + + @Override + public void send(File file) { + Collection products; + try { + products = readProductConfig.read(file); + } catch (IOException e) { + throw new RuntimeException("读取降价商品失败,终止发送降价邮件提醒"); + } + for (Product product : products) { + List users = (List) userService.querySubscriptedUsersByProductID(product.getProductID()); + + for (User user : users) { + try { + if (user.getEmail().length() > 0) + MailUtil.sendEmail(user.getEmail(), + Configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN), + SUBJECT, + String.format(MESSAGE, user.getName(), product.getProductDesc()), + Configuration.getProperty(ConfigurationKeys.SMTP_SERVER)); + } catch (Exception e) { + try { + MailUtil.sendEmail(user.getEmail(), + Configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN), + SUBJECT, + String.format(MESSAGE, user.getName(), product.getProductDesc()), + Configuration.getProperty(ConfigurationKeys.ALT_SMTP_SERVER)); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + } + } +} diff --git a/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/service/impl/ReadProductConfigImpl.java b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/service/impl/ReadProductConfigImpl.java new file mode 100644 index 0000000000..9360be24ad --- /dev/null +++ b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/service/impl/ReadProductConfigImpl.java @@ -0,0 +1,40 @@ +package com.coderising.ood.srp.service.impl; + +import com.coderising.ood.srp.entity.Product; +import com.coderising.ood.srp.service.IReadProductConfig; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * Created by Enan on 17/6/18. + */ +public class ReadProductConfigImpl implements IReadProductConfig { + @Override + public Collection read(File file) throws IOException { + List products = new ArrayList<>(); + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp; + while ((temp = br.readLine()) != null) { + String[] data = temp.split(" "); + + System.out.println("产品ID = " + data[0] + "\n"); + System.out.println("产品描述 = " + data[1] + "\n"); + + products.add(Product.builder().productID(data[0]).productDesc(data[1]).build()); + } + return products; + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } +} diff --git a/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/service/impl/UserServiceImpl.java b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/service/impl/UserServiceImpl.java new file mode 100644 index 0000000000..f38ce0f773 --- /dev/null +++ b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/service/impl/UserServiceImpl.java @@ -0,0 +1,20 @@ +package com.coderising.ood.srp.service.impl; + +import com.coderising.ood.srp.dao.UserDao; +import com.coderising.ood.srp.entity.User; +import com.coderising.ood.srp.service.IUserService; + +import java.util.List; + +/** + * Created by Enan on 17/6/18. + */ +public class UserServiceImpl implements IUserService { + + private UserDao userDao = UserDao.getInstance(); + + @Override + public List querySubscriptedUsersByProductID(String productID) { + return userDao.querySubscriptedUsersByProductID(productID); + } +} diff --git a/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/util/DBUtil.java b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/util/DBUtil.java new file mode 100644 index 0000000000..a6e495ab07 --- /dev/null +++ b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/util/DBUtil.java @@ -0,0 +1,26 @@ +package com.coderising.ood.srp.util; +import com.coderising.ood.srp.entity.User; + +import java.util.ArrayList; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + User user = new User(); + user.setName("User" + i); + user.setEmail("aa@bb.com"); + userList.add(user); + } + + return userList; + } +} diff --git a/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/util/MailUtil.java b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/util/MailUtil.java new file mode 100644 index 0000000000..dd640423c9 --- /dev/null +++ b/students/1241588932/ood-assignment-enan/src/main/java/com/coderising/ood/srp/util/MailUtil.java @@ -0,0 +1,17 @@ +package com.coderising.ood.srp.util; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/1241588932/ood-assignment-enan/src/main/resources/email_config.properties b/students/1241588932/ood-assignment-enan/src/main/resources/email_config.properties new file mode 100644 index 0000000000..6f5615d18b --- /dev/null +++ b/students/1241588932/ood-assignment-enan/src/main/resources/email_config.properties @@ -0,0 +1,3 @@ +smtp.server=smtp.163.com +alt.smtp.server=smtp1.163.com +email.admin=admin@company.com \ No newline at end of file diff --git a/students/1241588932/ood-assignment-enan/src/main/resources/product_promotion.txt b/students/1241588932/ood-assignment-enan/src/main/resources/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/1241588932/ood-assignment-enan/src/main/resources/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/1299310140/src/com/coderising/junit/AllTest.java b/students/1299310140/src/com/coderising/junit/AllTest.java new file mode 100644 index 0000000000..f9c715efbf --- /dev/null +++ b/students/1299310140/src/com/coderising/junit/AllTest.java @@ -0,0 +1,36 @@ +package com.coderising.junit; + +public class AllTest { + +// public static Test suite(){ +// TestSuite suite = new TestSuite("All Test"); +// suite.addTestSuite(CalculatorTest.class); +// suite.addTestSuite(CalculatorTest.class); +// return suite; +// } + + public static Test suite(){ + TestSuite suite = new TestSuite("All Test"); + suite.addTest(CalculatorSuite.suite()); +// suite.addTestSuite(CalculatorTest.class); + suite.addTest(new RepeatedTest(new TestSuite(CalculatorTest.class),3)); + return new OverallTestSetup(suite); + } + + static class OverallTestSetup extends TestSetUp{ + + public OverallTestSetup(Test test) { + super(test); + } + + @Override + public void setUp(){ + System.out.println("this is overall testsetup"); + } + + @Override + public void tearDown(){ + System.out.println("this is overall testteardown"); + } + } +} diff --git a/students/1299310140/src/com/coderising/junit/Assert.java b/students/1299310140/src/com/coderising/junit/Assert.java new file mode 100644 index 0000000000..089a14bf55 --- /dev/null +++ b/students/1299310140/src/com/coderising/junit/Assert.java @@ -0,0 +1,19 @@ +package com.coderising.junit; + +public class Assert { + + public static void assertEquals(int expected,int actual){ + if(expected == actual) + return; + failNotEquals(expected,actual); + } + + private static void failNotEquals(int expected, int actual) { + String message = "expected:<" + expected + "> but was:<" + actual + ">"; + fail(message); + } + + private static void fail(String message) { + throw new AssertionFailedError(message); + } +} diff --git a/students/1299310140/src/com/coderising/junit/AssertionFailedError.java b/students/1299310140/src/com/coderising/junit/AssertionFailedError.java new file mode 100644 index 0000000000..599dffc70f --- /dev/null +++ b/students/1299310140/src/com/coderising/junit/AssertionFailedError.java @@ -0,0 +1,12 @@ +package com.coderising.junit; + +public class AssertionFailedError extends Error { + + public AssertionFailedError(){ + + } + + public AssertionFailedError(String message){ + super(message); + } +} diff --git a/students/1299310140/src/com/coderising/junit/BaseTestRunner.java b/students/1299310140/src/com/coderising/junit/BaseTestRunner.java new file mode 100644 index 0000000000..271da28e12 --- /dev/null +++ b/students/1299310140/src/com/coderising/junit/BaseTestRunner.java @@ -0,0 +1,51 @@ +package com.coderising.junit; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +public abstract class BaseTestRunner implements TestListener { + + public static final String SUITE_METHODNAME = "suite"; + + public Test getTest(String suiteClassName) { + Class testClass = null; + try { + testClass = loadSuiteClass(suiteClassName); + } catch (ClassNotFoundException e) { + + e.printStackTrace(); + } + + Method suiteMethod = null; + try { + suiteMethod = testClass.getMethod(SUITE_METHODNAME, new Class[0]); + } catch (NoSuchMethodException e) { + + e.printStackTrace(); + } catch (SecurityException e) { + + e.printStackTrace(); + } + + Test test = null; + try { + test = (Test) suiteMethod.invoke(null, new Class[0]); + } catch (IllegalAccessException e) { + + e.printStackTrace(); + } catch (IllegalArgumentException e) { + + e.printStackTrace(); + } catch (InvocationTargetException e) { + + e.printStackTrace(); + } + + return test; + } + + private Class loadSuiteClass(String suiteClassName) throws ClassNotFoundException { + + return Class.forName(suiteClassName); + } +} diff --git a/students/1299310140/src/com/coderising/junit/Calculator.java b/students/1299310140/src/com/coderising/junit/Calculator.java new file mode 100644 index 0000000000..a9bd36bb30 --- /dev/null +++ b/students/1299310140/src/com/coderising/junit/Calculator.java @@ -0,0 +1,30 @@ +package com.coderising.junit; + +public class Calculator { + + private int result = 0; + + public void add(int x){ + result += x; + } + + public void subtract(int x){ + result -= x; + } + + public int getResult(){ + return result; + } + + public static void main(String[] args){ + TestSuite ts = new TestSuite(CalculatorTest.class); + TestResult tr = new TestResult(); + ts.run(tr); + for(TestFailure testFailure:tr.getFailures()){ + System.out.println(testFailure.thrownException()); + } + for(TestFailure testFailure:tr.getErrors()){ + System.out.println(testFailure.thrownException()); + } + } +} diff --git a/students/1299310140/src/com/coderising/junit/CalculatorSuite.java b/students/1299310140/src/com/coderising/junit/CalculatorSuite.java new file mode 100644 index 0000000000..a5205c0a5c --- /dev/null +++ b/students/1299310140/src/com/coderising/junit/CalculatorSuite.java @@ -0,0 +1,10 @@ +package com.coderising.junit; + +public class CalculatorSuite { + + public static Test suite(){ + TestSuite suite = new TestSuite("Calculator All Test"); + suite.addTestSuite(CalculatorTest.class); + return suite; + } +} diff --git a/students/1299310140/src/com/coderising/junit/CalculatorTest.java b/students/1299310140/src/com/coderising/junit/CalculatorTest.java new file mode 100644 index 0000000000..0a9c24f742 --- /dev/null +++ b/students/1299310140/src/com/coderising/junit/CalculatorTest.java @@ -0,0 +1,29 @@ +package com.coderising.junit; + +public class CalculatorTest extends TestCase { + + public CalculatorTest(String name) { + super(name); + } + + Calculator calculator = null; + + public void setUp(){ + calculator = new Calculator(); + } + + public void tearDown(){ + calculator = null; + } + + public void testAdd(){ + calculator.add(10); + Assert.assertEquals(10, calculator.getResult()); + } + + public void testSubtract(){ + calculator.add(10); + calculator.subtract(5); + Assert.assertEquals(10, calculator.getResult()); + } +} diff --git a/students/1299310140/src/com/coderising/junit/Protectable.java b/students/1299310140/src/com/coderising/junit/Protectable.java new file mode 100644 index 0000000000..d7238b5f39 --- /dev/null +++ b/students/1299310140/src/com/coderising/junit/Protectable.java @@ -0,0 +1,5 @@ +package com.coderising.junit; + +public interface Protectable { + public void protect() throws Throwable; +} diff --git a/students/1299310140/src/com/coderising/junit/RepeatedTest.java b/students/1299310140/src/com/coderising/junit/RepeatedTest.java new file mode 100644 index 0000000000..c281758586 --- /dev/null +++ b/students/1299310140/src/com/coderising/junit/RepeatedTest.java @@ -0,0 +1,23 @@ +package com.coderising.junit; + +public class RepeatedTest extends TestDecorator { + + private int fTimesRepeat; + + public RepeatedTest(Test test,int repeat) { + super(test); + if(repeat < 0) + throw new IllegalArgumentException("repeation count must be > 0"); + this.fTimesRepeat = repeat; + } + + public int countTestCases(){ + return super.countTestCases() * fTimesRepeat; + } + + public void run(TestResult testResult){ + for(int i = 0;i < fTimesRepeat;i++){ + super.run(testResult); + } + } +} diff --git a/students/1299310140/src/com/coderising/junit/Test.java b/students/1299310140/src/com/coderising/junit/Test.java new file mode 100644 index 0000000000..5144d296a1 --- /dev/null +++ b/students/1299310140/src/com/coderising/junit/Test.java @@ -0,0 +1,8 @@ +package com.coderising.junit; + +public interface Test { + + public void run(TestResult tr); + + public int countTestCases(); +} diff --git a/students/1299310140/src/com/coderising/junit/TestCase.java b/students/1299310140/src/com/coderising/junit/TestCase.java new file mode 100644 index 0000000000..2c6f41b55a --- /dev/null +++ b/students/1299310140/src/com/coderising/junit/TestCase.java @@ -0,0 +1,50 @@ +package com.coderising.junit; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +public abstract class TestCase extends Assert implements Test { + + private String name; + + public TestCase(String name){ + this.name = name; + } + + @Override + public void run(TestResult tr){ + tr.run(this); + } + + public void doRun() throws Throwable{ + setUp(); + try{ + runTest(); + }finally{ + tearDown(); + } + } + + protected void runTest() throws Throwable{ + Method runMethod = this.getClass().getMethod(name, null); + try { + runMethod.invoke(this, new Class[0]); + } catch (InvocationTargetException e) { + e.fillInStackTrace(); + throw e.getTargetException(); + } + } + + protected void setUp(){ + + } + + protected void tearDown(){ + + } + + @Override + public int countTestCases() { + return 1; + } +} diff --git a/students/1299310140/src/com/coderising/junit/TestDecorator.java b/students/1299310140/src/com/coderising/junit/TestDecorator.java new file mode 100644 index 0000000000..75f74cbcc7 --- /dev/null +++ b/students/1299310140/src/com/coderising/junit/TestDecorator.java @@ -0,0 +1,26 @@ +package com.coderising.junit; + +public class TestDecorator implements Test { + + protected Test test; + + public TestDecorator(Test test){ + this.test = test; + } + + @Override + public void run(TestResult tr) { + basicRun(tr); + } + + public void basicRun(TestResult tr) { + this.test.run(tr); + } + + @Override + public int countTestCases() { + + return test.countTestCases(); + } + +} diff --git a/students/1299310140/src/com/coderising/junit/TestFailure.java b/students/1299310140/src/com/coderising/junit/TestFailure.java new file mode 100644 index 0000000000..28fdbc18a7 --- /dev/null +++ b/students/1299310140/src/com/coderising/junit/TestFailure.java @@ -0,0 +1,21 @@ +package com.coderising.junit; + +public class TestFailure { + + private Test failedTest; + private Throwable thrownException; + + public TestFailure(Test failedTest, Throwable thrownException) { + super(); + this.failedTest = failedTest; + this.thrownException = thrownException; + } + + public Test failedTest(){ + return this.failedTest; + } + + public Throwable thrownException(){ + return this.thrownException; + } +} diff --git a/students/1299310140/src/com/coderising/junit/TestListener.java b/students/1299310140/src/com/coderising/junit/TestListener.java new file mode 100644 index 0000000000..0813b0e9ef --- /dev/null +++ b/students/1299310140/src/com/coderising/junit/TestListener.java @@ -0,0 +1,12 @@ +package com.coderising.junit; + +public interface TestListener { + + public void addError(Test test, Throwable t); + + public void addFailure(Test test, AssertionFailedError t); + + public void startTest(Test test); + + public void endTest(Test test); +} diff --git a/students/1299310140/src/com/coderising/junit/TestRunner.java b/students/1299310140/src/com/coderising/junit/TestRunner.java new file mode 100644 index 0000000000..69b67bc0d5 --- /dev/null +++ b/students/1299310140/src/com/coderising/junit/TestRunner.java @@ -0,0 +1,62 @@ +package com.coderising.junit; + +import java.io.PrintStream; + +public class TestRunner extends BaseTestRunner { + + PrintStream write = System.out; + int column = 0; + + @Override + public void addError(Test test, Throwable t) { + write.print("E"); + } + + @Override + public void addFailure(Test test, AssertionFailedError t) { + write.print("F"); + } + + @Override + public void startTest(Test test) { + write.print("."); + if(column++ >= 40){ + write.println(); + column = 0; + } + } + + @Override + public void endTest(Test test) { + + } + + public static void main(String[] args) { + TestRunner testRunner = new TestRunner(); + try { + TestResult testResult = testRunner.start(args); + } catch (Exception e) { + + e.printStackTrace(); + } + } + + private TestResult start(String[] args) throws Exception { + if(args.length == 0){ + throw new Exception("Usage : TestRunner TestCaseName"); + } + + String testCase = args[0]; + Test suite = getTest(testCase); + + return doRun(suite); + } + + private TestResult doRun(Test suite) { + TestResult testResult = new TestResult(); + testResult.addListener(this); + suite.run(testResult); + return testResult; + } + +} diff --git a/students/1299310140/src/com/coderising/junit/TestSetUp.java b/students/1299310140/src/com/coderising/junit/TestSetUp.java new file mode 100644 index 0000000000..5ad6e22394 --- /dev/null +++ b/students/1299310140/src/com/coderising/junit/TestSetUp.java @@ -0,0 +1,30 @@ +package com.coderising.junit; + +public class TestSetUp extends TestDecorator { + + public TestSetUp(Test test) { + super(test); + } + + public void run(final TestResult testResult){ + Protectable p = new Protectable() { + @Override + public void protect() throws Throwable { + setUp(); + basicRun(testResult); + tearDown(); + } + }; + + testResult.runProtected(this, p); + } + + protected void tearDown() { + + } + + protected void setUp() { + + } + +} diff --git a/students/1299310140/src/com/coderising/junit/TestSuite.java b/students/1299310140/src/com/coderising/junit/TestSuite.java new file mode 100644 index 0000000000..48af3a92e9 --- /dev/null +++ b/students/1299310140/src/com/coderising/junit/TestSuite.java @@ -0,0 +1,96 @@ +package com.coderising.junit; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class TestSuite implements Test { + + private List tests = new ArrayList(); + + private String name = ""; + + @Override + public void run(TestResult tr) { + for(Iterator iterator = tests.iterator();iterator.hasNext();){ + Test test = iterator.next(); + test.run(tr); + } + } + + public void addTest(Test test){ + tests.add(test); + } + + public void addTestSuite(Class theClass){ + addTest(new TestSuite(theClass)); + } + + public TestSuite(){ + + } + + public TestSuite(String name){ + this.name = name; + } + + public TestSuite(final Class theClass){ + this.name = theClass.getName(); + Constructor constructor = null; + try { + constructor = theClass.getConstructor(String.class); + } catch (Exception e) { + e.printStackTrace(); + } + + List names = new ArrayList(); + Method[] method = theClass.getDeclaredMethods(); + for(int i = 0;i < method.length;i++){ + addTestMethod(method[i],names,constructor); + } + + if(tests.size() == 0){ + System.out.println("No tests found in" + theClass.getName()); + } + } + + private void addTestMethod(Method method, List names, + Constructor constructor) { + String name = method.getName(); + if(names.contains(name)){ + return; + } + + if(isPublicTestMethod(method)){ + names.add(name); + + try { + addTest((Test)constructor.newInstance(name)); + } catch (Exception e) { + e.printStackTrace(); + } + + } + } + + private boolean isPublicTestMethod(Method method) { + String name = method.getName(); + Class[] parameters = method.getParameterTypes(); + Class returnType = method.getReturnType(); + return Modifier.isPublic(method.getModifiers()) && name.startsWith("test") + && parameters.length == 0 && returnType.equals(Void.TYPE); + } + + @Override + public int countTestCases() { + int count = 0; + for(Iterator iterator = tests.iterator();iterator.hasNext();){ + Test test = iterator.next(); + count += test.countTestCases(); + } + return count; + } +} diff --git a/students/1299310140/src/com/coderising/ood/srp/CheckUtil.java b/students/1299310140/src/com/coderising/ood/srp/CheckUtil.java new file mode 100644 index 0000000000..657c4c8102 --- /dev/null +++ b/students/1299310140/src/com/coderising/ood/srp/CheckUtil.java @@ -0,0 +1,11 @@ +package com.coderising.ood.srp; + +public class CheckUtil { + protected static boolean checkEmail(String emailAddress){ + if(emailAddress.length() > 0){ + return true; + }else{ + return false; + } + } +} diff --git a/students/1299310140/src/com/coderising/ood/srp/Configuration.java b/students/1299310140/src/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..927c7155cc --- /dev/null +++ b/students/1299310140/src/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/1299310140/src/com/coderising/ood/srp/ConfigurationKeys.java b/students/1299310140/src/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..868a03ff83 --- /dev/null +++ b/students/1299310140/src/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/1299310140/src/com/coderising/ood/srp/DBUtil.java b/students/1299310140/src/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..65383e4dba --- /dev/null +++ b/students/1299310140/src/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/1299310140/src/com/coderising/ood/srp/MailUtil.java b/students/1299310140/src/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..373f3ee306 --- /dev/null +++ b/students/1299310140/src/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/1299310140/src/com/coderising/ood/srp/Product.java b/students/1299310140/src/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..4d1706b42b --- /dev/null +++ b/students/1299310140/src/com/coderising/ood/srp/Product.java @@ -0,0 +1,24 @@ +package com.coderising.ood.srp; + +public class Product { + + private String id; + + private String desc; + + public Product(String id, String desc) { + super(); + this.id = id; + this.desc = desc; + } + + public String getId() { + return id; + } + + public String getDesc() { + return desc; + } + + +} diff --git a/students/1299310140/src/com/coderising/ood/srp/PromotionMail.java b/students/1299310140/src/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..aa40bc6251 --- /dev/null +++ b/students/1299310140/src/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,96 @@ +package com.coderising.ood.srp; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + //C:\\my Program Files\\mygit\\second\\coding2017\\students\\1299310140\\src\\com\\coderising\\ood\\srp + String productFilePath = "C:\\my Program Files\\mygit\\second\\coding2017\\students\\1299310140\\src\\com\\coderising\\ood\\srp\\product_promotion.txt"; + Product product = ReadFile.readProductFile(productFilePath); + + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + product.getId() +"' " + + "and send_mail=1 "; + List list = DBUtil.query(sendMailQuery); + + if(list == null){ + System.out.println("没有邮件发送"); + return; + } + + Configuration config = new Configuration(); + PromotionMail pe = new PromotionMail(config); + boolean emailDebug = false; + + Iterator iter = list.iterator(); + while (iter.hasNext()) { + HashMap userInfo = (HashMap) iter.next(); + if(CheckUtil.checkEmail((String) userInfo.get(EMAIL_KEY))){ + pe.setMessageAndToAddress(userInfo,product); + pe.sendEMails(emailDebug); + } + } + + } + + + public PromotionMail(Configuration config){ + + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + + } + + protected void setMessageAndToAddress(HashMap userInfo,Product product) + { + toAddress = (String) userInfo.get(EMAIL_KEY); + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + product.getDesc() + " 降价了,欢迎购买!" ; + + } + + protected void sendEMails(boolean debug) throws IOException + { + + System.out.println("开始发送邮件"); + try + { + + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } +} diff --git a/students/1299310140/src/com/coderising/ood/srp/ReadFile.java b/students/1299310140/src/com/coderising/ood/srp/ReadFile.java new file mode 100644 index 0000000000..15aadf91b8 --- /dev/null +++ b/students/1299310140/src/com/coderising/ood/srp/ReadFile.java @@ -0,0 +1,34 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +public class ReadFile { + + protected static Product readProductFile(String productFilePath) throws IOException + { + File file = new File(productFilePath); + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + Product product = new Product(data[0],data[1]); + + System.out.println("产品ID = " + product.getId() + "\n"); + System.out.println("产品描述 = " + product.getDesc() + "\n"); + + return product; + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } +} diff --git a/students/1299310140/src/com/coderising/ood/srp/product_promotion.txt b/students/1299310140/src/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/1299310140/src/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/1299310140/src/com/coderising/payroll/AddEmployee.java b/students/1299310140/src/com/coderising/payroll/AddEmployee.java new file mode 100644 index 0000000000..48341143d9 --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/AddEmployee.java @@ -0,0 +1,57 @@ +package com.coderising.payroll; + +public class AddEmployee { + public static Employee addHourlyEmployee(String name,String address,double rate,String[] timeCardDates,int[] timeCardhours){ + Employee e = new Employee(name,address); + HourlyClassification classification = new HourlyClassification(rate); + for(int i = 0;i < timeCardDates.length;i++){ + TimeCard tc = new TimeCard(DateUtil.parseDate(timeCardDates[i]),timeCardhours[i]); + classification.addTimeCard(tc); + } + Affiliation affiliation = new NonAffiliation(); + PaymentMethod paymentMethod = new HoldMethod(); + PaymentSchedule paymentSchedule = new WeeklySchedule(); + + e.setClassification(classification); + e.setAffiliation(affiliation); + e.setPaymentMethod(paymentMethod); + e.setSchedule(paymentSchedule); + return e; + } + + public static Employee addSalariedEmployee(String name,String address,double salary,String[] serviceChargeDates,int[] serviceChargeAmount){ + Employee e = new Employee(name,address); + SalariedClassification sc = new SalariedClassification(salary); + UnionAffiliation ua = new UnionAffiliation(name); + for(int i = 0;i < serviceChargeDates.length;i++){ + ServiceCharge serviceCharge = new ServiceCharge(DateUtil.parseDate(serviceChargeDates[i]),serviceChargeAmount[i]); + ua.addServiceCharge(serviceCharge); + } + PaymentMethod pm = new MailMethod(address); + PaymentSchedule ps = new MonthlySchedule(); + + e.setClassification(sc); + e.setAffiliation(ua); + e.setPaymentMethod(pm); + e.setSchedule(ps); + return e; + } + + public static Employee addCommissionEmployee(String name,String address,String bank, String account,double salary,double rate,String[] salesReceiptDates,int[] salesReceiptAmount){ + Employee e = new Employee(name,address); + CommissionedClassification classification = new CommissionedClassification(salary,rate); + for(int i = 0;i < salesReceiptDates.length;i++){ + SalesReceipt sr = new SalesReceipt(DateUtil.parseDate(salesReceiptDates[i]),salesReceiptAmount[i]); + classification.addSalesReceipt(sr); + } + Affiliation affiliation = new NonAffiliation(); + PaymentMethod paymentMethod = new BankMethod(bank,account);//new HoldMethod(); + PaymentSchedule paymentSchedule = new BiWeeklySchedule(); + + e.setClassification(classification); + e.setAffiliation(affiliation); + e.setPaymentMethod(paymentMethod); + e.setSchedule(paymentSchedule); + return e; + } +} diff --git a/students/1299310140/src/com/coderising/payroll/Affiliation.java b/students/1299310140/src/com/coderising/payroll/Affiliation.java new file mode 100644 index 0000000000..e8f44acfa7 --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/Affiliation.java @@ -0,0 +1,5 @@ +package com.coderising.payroll; + +public interface Affiliation { + public double calculateDeductions(Paycheck pc); +} diff --git a/students/1299310140/src/com/coderising/payroll/BankMethod.java b/students/1299310140/src/com/coderising/payroll/BankMethod.java new file mode 100644 index 0000000000..8e2fac62c0 --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/BankMethod.java @@ -0,0 +1,21 @@ +package com.coderising.payroll; + +public class BankMethod implements PaymentMethod { + private String bank = ""; + private String account = ""; + + public BankMethod(String bank, String account) { + super(); + this.bank = bank; + this.account = account; + } + + @Override + public void pay(Paycheck pc) { + System.out.println("已将工资转入" + bank + "的" + account + "账户"); + System.out.println("应付" + pc.getGrossPay()); + System.out.println("扣除" + pc.getDeductions()); + System.out.println("实付" + pc.getNetPay()); + } + +} diff --git a/students/1299310140/src/com/coderising/payroll/BiWeeklySchedule.java b/students/1299310140/src/com/coderising/payroll/BiWeeklySchedule.java new file mode 100644 index 0000000000..28bfd31d52 --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/BiWeeklySchedule.java @@ -0,0 +1,20 @@ +package com.coderising.payroll; + +import java.util.Date; + +public class BiWeeklySchedule implements PaymentSchedule { + Date firstPayableFriday = DateUtil.parseDate("2017-6-2"); + + @Override + public boolean isPayDate(Date date) { + + long interval = DateUtil.getDaysBetween(firstPayableFriday,date); + return interval % 14 == 0; + } + + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.add(payPeriodEndDate, -13); + } + +} diff --git a/students/1299310140/src/com/coderising/payroll/CommissionedClassification.java b/students/1299310140/src/com/coderising/payroll/CommissionedClassification.java new file mode 100644 index 0000000000..cd70102ebd --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/CommissionedClassification.java @@ -0,0 +1,36 @@ +package com.coderising.payroll; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +public class CommissionedClassification implements PaymentClassification { + + double salary; + double rate; + Map receipts; + + public CommissionedClassification(double salary, double rate) { + super(); + this.salary = salary; + this.rate = rate; + this.receipts = new HashMap(); + } + + public void addSalesReceipt(SalesReceipt sr){ + receipts.put(sr.getSaleDate(), sr); + } + + @Override + public double calculatePay(Paycheck pc) { + double commission = 0; + for (SalesReceipt salesReceipt : receipts.values()) { + if(DateUtil.between(salesReceipt.getSaleDate(), + pc.getPayPeriodStartDate(), pc.getPayPeriodEndDate())) { + commission += salesReceipt.getAmount() * rate; + } + } + return commission + salary; + } + +} diff --git a/students/1299310140/src/com/coderising/payroll/DateUtil.java b/students/1299310140/src/com/coderising/payroll/DateUtil.java new file mode 100644 index 0000000000..52a999620d --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/DateUtil.java @@ -0,0 +1,85 @@ +package com.coderising.payroll; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +public class DateUtil { + + private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + + private static Calendar calendar = Calendar.getInstance(); + + public static boolean between(Date date, Date startDate, + Date endDate) { +// boolean result = date.after(startDate) && date.before(endDate);//不包括边界 + boolean result = getDaysBetween(startDate,date) >= 0 && getDaysBetween(date,endDate) >= 0;//包括边界 + return result; + } + + public static boolean isFriday(Date date) { + calendar.setTime(date); + int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); + return dayOfWeek == 6; + } + + public static Date add(Date date, int i) { + calendar.setTime(date); + calendar.add(Calendar.DATE, i); + return calendar.getTime(); + } + + public static boolean isLastDayOfMonth(Date date) { + calendar.setTime(date); + calendar.add(Calendar.MONTH, 1); + calendar.set(Calendar.DAY_OF_MONTH, 0); + return date.equals(calendar.getTime()); + } + + public static Date getFirstDay(Date date) { + calendar.setTime(date); + calendar.add(Calendar.MONTH, 0); + calendar.set(Calendar.DAY_OF_MONTH, 1); + return calendar.getTime(); + } + + public static Date parseDate(String dateString){ + try + { + Date date = format.parse(dateString); + return date; + } + catch (ParseException e) + { + System.out.println(e.getMessage()); + } + return null; + } + + public static long getDaysBetween(Date startDate, Date endDate) { + return (endDate.getTime() - startDate.getTime()) / (1000*3600*24); + } + + public static int fridaysNum(Date startDate, Date endDate) { + int interval = (int) getDaysBetween(startDate,endDate); + int fridaysNumber = interval / 7; + + startDate = add(startDate,fridaysNumber * 7); + interval = (int) getDaysBetween(startDate,endDate); + calendar.setTime(startDate); + int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); + for(int i = 0;i <= interval;i++){ + if(dayOfWeek == 6){ + fridaysNumber++; + break; + } + dayOfWeek++; + if(dayOfWeek == 8){ + dayOfWeek = 1; + } + } + return fridaysNumber; + } + +} diff --git a/students/1299310140/src/com/coderising/payroll/DateUtilTest.java b/students/1299310140/src/com/coderising/payroll/DateUtilTest.java new file mode 100644 index 0000000000..39c5099ee5 --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/DateUtilTest.java @@ -0,0 +1,113 @@ +package com.coderising.payroll; + +import static org.junit.Assert.fail; + +import java.util.Date; + +import junit.framework.Assert; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class DateUtilTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testBetween() { + Date dateOne = DateUtil.parseDate("2017-6-29"); + Date dateTwo = DateUtil.parseDate("2017-6-30"); + Date dateThree = DateUtil.parseDate("2017-7-1"); + Date dateFour = DateUtil.parseDate("2017-7-2"); + Date dateFive = DateUtil.parseDate("2017-7-3"); + + Date startDate = DateUtil.parseDate("2017-6-30"); + Date endDate = DateUtil.parseDate("2017-7-2"); + + Assert.assertEquals(false,DateUtil.between(dateOne, startDate, endDate)); + Assert.assertEquals(true,DateUtil.between(dateTwo, startDate, endDate)); + Assert.assertEquals(true,DateUtil.between(dateThree, startDate, endDate)); + Assert.assertEquals(true,DateUtil.between(dateFour, startDate, endDate)); + Assert.assertEquals(false,DateUtil.between(dateFive, startDate, endDate)); + } + + @Test + public void testIsFriday() { + Assert.assertEquals(true,DateUtil.isFriday(DateUtil.parseDate("2017-7-7"))); + Assert.assertEquals(true,DateUtil.isFriday(DateUtil.parseDate("2017-7-14"))); + Assert.assertEquals(false,DateUtil.isFriday(DateUtil.parseDate("2017-7-6"))); + Assert.assertEquals(false,DateUtil.isFriday(DateUtil.parseDate("2017-7-8"))); + } + + @Test + public void testAdd() { + Date dateOne = DateUtil.parseDate("2017-7-2"); + Date dateTwo = DateUtil.parseDate("2017-7-30"); + + Assert.assertEquals("Sun Jul 02 00:00:00 CST 2017", DateUtil.add(dateOne, 0).toString()); + Assert.assertEquals("Tue Jul 04 00:00:00 CST 2017", DateUtil.add(dateOne, 2).toString()); + Assert.assertEquals("Fri Jun 30 00:00:00 CST 2017", DateUtil.add(dateOne, -2).toString()); + + Assert.assertEquals("Wed Aug 02 00:00:00 CST 2017", DateUtil.add(dateTwo, 3).toString()); + Assert.assertEquals("Sat Jul 29 00:00:00 CST 2017", DateUtil.add(dateTwo, -1).toString()); + } + + @Test + public void testIsLastDayOfMonth() { + Assert.assertEquals(true, DateUtil.isLastDayOfMonth(DateUtil.parseDate("2017-6-30"))); + Assert.assertEquals(false,DateUtil.isLastDayOfMonth(DateUtil.parseDate("2017-6-31"))); + Assert.assertEquals(true, DateUtil.isLastDayOfMonth(DateUtil.parseDate("2017-7-31"))); + Assert.assertEquals(false,DateUtil.isLastDayOfMonth(DateUtil.parseDate("2017-7-32"))); + Assert.assertEquals(true, DateUtil.isLastDayOfMonth(DateUtil.parseDate("2017-12-31"))); + Assert.assertEquals(true, DateUtil.isLastDayOfMonth(DateUtil.parseDate("2017-2-28"))); + Assert.assertEquals(false, DateUtil.isLastDayOfMonth(DateUtil.parseDate("2017-2-29"))); + } + + @Test + public void testGetFirstDay() { + Assert.assertEquals("Sat Jul 01 00:00:00 CST 2017", DateUtil.getFirstDay(DateUtil.parseDate("2017-7-1")).toString()); + Assert.assertEquals("Sat Jul 01 00:00:00 CST 2017", DateUtil.getFirstDay(DateUtil.parseDate("2017-7-15")).toString()); + Assert.assertEquals("Sat Jul 01 00:00:00 CST 2017", DateUtil.getFirstDay(DateUtil.parseDate("2017-7-31")).toString()); + Assert.assertEquals("Tue Aug 01 00:00:00 CST 2017", DateUtil.getFirstDay(DateUtil.parseDate("2017-7-32")).toString()); + } + + @Test + public void testParseDate() { + Assert.assertEquals("Sat Jul 01 00:00:00 CST 2017", DateUtil.parseDate("2017-7-1").toString()); + Assert.assertEquals("Sat Jul 01 00:00:00 CST 2017", DateUtil.parseDate("2017-07-01").toString()); + Assert.assertEquals("Mon Jul 03 00:00:00 CST 2017", DateUtil.parseDate("2017-6-33").toString()); + Assert.assertEquals("Tue Aug 01 00:00:00 CST 2017", DateUtil.parseDate("2017-7-32").toString()); + Assert.assertEquals("Mon Jul 31 00:00:00 CST 2017", DateUtil.parseDate("2017-8-0").toString()); + } + + @Test + public void testGetDaysBetween() { + Assert.assertEquals(0, DateUtil.getDaysBetween(DateUtil.parseDate("2017-7-1"),DateUtil.parseDate("2017-7-1"))); + Assert.assertEquals(1, DateUtil.getDaysBetween(DateUtil.parseDate("2017-7-1"),DateUtil.parseDate("2017-7-2"))); + Assert.assertEquals(-1, DateUtil.getDaysBetween(DateUtil.parseDate("2017-7-2"),DateUtil.parseDate("2017-7-1"))); + Assert.assertEquals(3, DateUtil.getDaysBetween(DateUtil.parseDate("2017-6-29"),DateUtil.parseDate("2017-7-2"))); + } + + @Test + public void testFridaysNum() { + Assert.assertEquals(1, DateUtil.fridaysNum(DateUtil.parseDate("2017-7-7"),DateUtil.parseDate("2017-7-7"))); + Assert.assertEquals(0, DateUtil.fridaysNum(DateUtil.parseDate("2017-7-2"),DateUtil.parseDate("2017-7-3"))); + Assert.assertEquals(0, DateUtil.fridaysNum(DateUtil.parseDate("2017-7-5"),DateUtil.parseDate("2017-7-6"))); + Assert.assertEquals(1, DateUtil.fridaysNum(DateUtil.parseDate("2017-7-6"),DateUtil.parseDate("2017-7-7"))); + Assert.assertEquals(1, DateUtil.fridaysNum(DateUtil.parseDate("2017-7-7"),DateUtil.parseDate("2017-7-8"))); + Assert.assertEquals(0, DateUtil.fridaysNum(DateUtil.parseDate("2017-7-8"),DateUtil.parseDate("2017-7-9"))); + Assert.assertEquals(1, DateUtil.fridaysNum(DateUtil.parseDate("2017-7-6"),DateUtil.parseDate("2017-7-8"))); + Assert.assertEquals(2, DateUtil.fridaysNum(DateUtil.parseDate("2017-7-7"),DateUtil.parseDate("2017-7-14"))); + Assert.assertEquals(2, DateUtil.fridaysNum(DateUtil.parseDate("2017-7-6"),DateUtil.parseDate("2017-7-15"))); + Assert.assertEquals(2, DateUtil.fridaysNum(DateUtil.parseDate("2017-7-8"),DateUtil.parseDate("2017-7-21"))); + Assert.assertEquals(6, DateUtil.fridaysNum(DateUtil.parseDate("2017-6-30"),DateUtil.parseDate("2017-8-4"))); + } + +} diff --git a/students/1299310140/src/com/coderising/payroll/Employee.java b/students/1299310140/src/com/coderising/payroll/Employee.java new file mode 100644 index 0000000000..90cb38b343 --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/Employee.java @@ -0,0 +1,53 @@ +package com.coderising.payroll; + +import java.util.Date; + +public class Employee { + + String id; + String name; + String address; + + Affiliation affiliation; + PaymentClassification classification; + PaymentSchedule schedule; + PaymentMethod paymentMethod; + + public Employee(String name, String address){ + this.name = name; + this.address = address; + } + + public boolean isPayDay(Date d) { + return this.schedule.isPayDate(d); + } + + public Date getPayPeriodStartDate(Date d) { + return this.schedule.getPayPeriodStartDate(d); + } + + public void payDay(Paycheck pc){//重点,笼统说话 + double grossPay = this.classification.calculatePay(pc); + double deduction = this.affiliation.calculateDeductions(pc); + double netPay = grossPay - deduction; + pc.setGrossPay(grossPay); + pc.setDeductions(deduction); + pc.setNetPay(netPay); + this.paymentMethod.pay(pc); + } + + public void setClassification(PaymentClassification classification) { + this.classification = classification; + } + public void setSchedule(PaymentSchedule schedule) { + this.schedule = schedule; + } + public void setPaymentMethod(PaymentMethod paymentMethod) { + this.paymentMethod = paymentMethod; + } + public void setAffiliation(Affiliation affiliation) { + this.affiliation = affiliation; + } + +} + diff --git a/students/1299310140/src/com/coderising/payroll/HoldMethod.java b/students/1299310140/src/com/coderising/payroll/HoldMethod.java new file mode 100644 index 0000000000..74dea2d086 --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/HoldMethod.java @@ -0,0 +1,13 @@ +package com.coderising.payroll; + +public class HoldMethod implements PaymentMethod { + + @Override + public void pay(Paycheck pc) { + System.out.println("工资保存在财务那,可随时支取"); + System.out.println("应付" + pc.getGrossPay()); + System.out.println("扣除" + pc.getDeductions()); + System.out.println("实付" + pc.getNetPay()); + } + +} diff --git a/students/1299310140/src/com/coderising/payroll/HourlyClassification.java b/students/1299310140/src/com/coderising/payroll/HourlyClassification.java new file mode 100644 index 0000000000..a94bb65bef --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/HourlyClassification.java @@ -0,0 +1,43 @@ +package com.coderising.payroll; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +public class HourlyClassification implements PaymentClassification { + + private double rate; + private Map timeCards; + + public HourlyClassification(double rate) { + super(); + this.rate = rate; + timeCards = new HashMap(); + } + + public void addTimeCard(TimeCard tc){ + this.timeCards.put(tc.getDate(), tc); + } + + private double calculatePayForTimeCard(TimeCard tc){ + int hours = tc.getHours(); + if(hours > 8){ + return 8 * rate + (hours - 8) * rate * 1.5; + }else{ + return hours * rate; + } + } + + @Override + public double calculatePay(Paycheck pc) { + double totalPay = 0; + for (TimeCard timeCard : timeCards.values()) { + if (DateUtil.between(timeCard.getDate(), + pc.getPayPeriodStartDate(), pc.getPayPeriodEndDate())) { + totalPay += calculatePayForTimeCard(timeCard); + } + } + return totalPay; + } + +} diff --git a/students/1299310140/src/com/coderising/payroll/MailMethod.java b/students/1299310140/src/com/coderising/payroll/MailMethod.java new file mode 100644 index 0000000000..9ab07ff844 --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/MailMethod.java @@ -0,0 +1,19 @@ +package com.coderising.payroll; + +public class MailMethod implements PaymentMethod { + private String address = ""; + + public MailMethod(String address) { + super(); + this.address = address; + } + + @Override + public void pay(Paycheck pc) { + System.out.println("已将支票邮寄到"+address); + System.out.println("应付" + pc.getGrossPay()); + System.out.println("扣除" + pc.getDeductions()); + System.out.println("实付" + pc.getNetPay()); + } + +} diff --git a/students/1299310140/src/com/coderising/payroll/MonthlySchedule.java b/students/1299310140/src/com/coderising/payroll/MonthlySchedule.java new file mode 100644 index 0000000000..f110a4f8c4 --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/MonthlySchedule.java @@ -0,0 +1,17 @@ +package com.coderising.payroll; + +import java.util.Date; + +public class MonthlySchedule implements PaymentSchedule { + + @Override + public boolean isPayDate(Date date) { + return DateUtil.isLastDayOfMonth(date); + } + + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.getFirstDay(payPeriodEndDate); + } + +} diff --git a/students/1299310140/src/com/coderising/payroll/NonAffiliation.java b/students/1299310140/src/com/coderising/payroll/NonAffiliation.java new file mode 100644 index 0000000000..f540ccaade --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/NonAffiliation.java @@ -0,0 +1,11 @@ +package com.coderising.payroll; + +public class NonAffiliation implements Affiliation { + + @Override + public double calculateDeductions(Paycheck pc) { + + return 0; + } + +} diff --git a/students/1299310140/src/com/coderising/payroll/Paycheck.java b/students/1299310140/src/com/coderising/payroll/Paycheck.java new file mode 100644 index 0000000000..2367d03a7d --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/Paycheck.java @@ -0,0 +1,50 @@ +package com.coderising.payroll; + +import java.util.Date; + +public class Paycheck { + + private Date payPeriodStart; + private Date payPeriodEnd; + private double grossPay; + private double netPay; + private double deductions; + + public Paycheck(Date payPeriodStart, Date payPeriodEnd){ + this.payPeriodStart = payPeriodStart; + this.payPeriodEnd = payPeriodEnd; + } + + public void setGrossPay(double grossPay) { + this.grossPay = grossPay; + } + + public void setDeductions(double deductions) { + this.deductions = deductions; + } + + public void setNetPay(double netPay){ + this.netPay = netPay; + } + + public Date getPayPeriodEndDate() { + return this.payPeriodEnd; + } + + public Date getPayPeriodStartDate() { + return this.payPeriodStart; + } + + public double getGrossPay() { + return grossPay; + } + + public double getNetPay() { + return netPay; + } + + public double getDeductions() { + return deductions; + } + +} diff --git a/students/1299310140/src/com/coderising/payroll/PaymentClassification.java b/students/1299310140/src/com/coderising/payroll/PaymentClassification.java new file mode 100644 index 0000000000..8dcd324551 --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/PaymentClassification.java @@ -0,0 +1,5 @@ +package com.coderising.payroll; + +public interface PaymentClassification { + public double calculatePay(Paycheck pc); +} diff --git a/students/1299310140/src/com/coderising/payroll/PaymentMethod.java b/students/1299310140/src/com/coderising/payroll/PaymentMethod.java new file mode 100644 index 0000000000..cd36151ec7 --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/PaymentMethod.java @@ -0,0 +1,5 @@ +package com.coderising.payroll; + +public interface PaymentMethod { + public void pay(Paycheck pc); +} diff --git a/students/1299310140/src/com/coderising/payroll/PaymentSchedule.java b/students/1299310140/src/com/coderising/payroll/PaymentSchedule.java new file mode 100644 index 0000000000..f2aff3c46b --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/PaymentSchedule.java @@ -0,0 +1,8 @@ +package com.coderising.payroll; + +import java.util.Date; + +public interface PaymentSchedule { + public boolean isPayDate(Date date); + public Date getPayPeriodStartDate( Date payPeriodEndDate); +} diff --git a/students/1299310140/src/com/coderising/payroll/SalariedClassification.java b/students/1299310140/src/com/coderising/payroll/SalariedClassification.java new file mode 100644 index 0000000000..cb3ce5c9d1 --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/SalariedClassification.java @@ -0,0 +1,16 @@ +package com.coderising.payroll; + +public class SalariedClassification implements PaymentClassification { + private double salary; + + public SalariedClassification(double salary) { + super(); + this.salary = salary; + } + + @Override + public double calculatePay(Paycheck pc) { + return salary; + } + +} diff --git a/students/1299310140/src/com/coderising/payroll/SalesReceipt.java b/students/1299310140/src/com/coderising/payroll/SalesReceipt.java new file mode 100644 index 0000000000..2d492f51da --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/SalesReceipt.java @@ -0,0 +1,20 @@ +package com.coderising.payroll; + +import java.util.Date; + +public class SalesReceipt { + private Date saleDate; + private double amount; + + public SalesReceipt(Date saleDate, double amount) { + super(); + this.saleDate = saleDate; + this.amount = amount; + } + public Date getSaleDate() { + return saleDate; + } + public double getAmount() { + return amount; + } +} diff --git a/students/1299310140/src/com/coderising/payroll/ServiceCharge.java b/students/1299310140/src/com/coderising/payroll/ServiceCharge.java new file mode 100644 index 0000000000..1e1e2b2c23 --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/ServiceCharge.java @@ -0,0 +1,23 @@ +package com.coderising.payroll; + +import java.util.Date; + +public class ServiceCharge { + private Date date; + private int amount; + + public ServiceCharge(Date date, int amount) { + super(); + this.date = date; + this.amount = amount; + } + + public Date getDate() { + return date; + } + + public int getAmount() { + return amount; + } + +} diff --git a/students/1299310140/src/com/coderising/payroll/Test.java b/students/1299310140/src/com/coderising/payroll/Test.java new file mode 100644 index 0000000000..42cc3941aa --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/Test.java @@ -0,0 +1,40 @@ +package com.coderising.payroll; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +public class Test { + + public static void main(String[] args) { + List employeeList = getEmployees(); + Date date = DateUtil.parseDate("2017-6-30"); + for(Employee e : employeeList){ + if(e.isPayDay(date)){//可以加上是否已经发过工资的判断 + Paycheck pc = new Paycheck(e.getPayPeriodStartDate(date),date); + e.payDay(pc); + //保存pc + } + } + } + + public static List getEmployees(){ + String[] timeCardDates = {"2017-6-23","2017-6-24","2017-6-28","2017-6-29","2017-6-30","2017-7-1"}; + int[] timeCardhours = {7,8,7,9,6,7}; + Employee e1 = AddEmployee.addHourlyEmployee("Hourly1", "a", 10, timeCardDates, timeCardhours); + + String[] serviceChargeDates = {"2017-5-31","2017-6-1","2017-6-15","2017-6-20","2017-6-30","2017-7-1"}; + int[] serviceChargeAmount = {5,3,2,4,5,5}; + Employee e2 = AddEmployee.addSalariedEmployee("Salaried1", "b", 6000, serviceChargeDates, serviceChargeAmount); + + String[] salesReceiptDates = {"2017-6-16","2017-6-17","2017-6-20","2017-6-25","2017-6-30","2017-7-1"}; + int[] salesReceiptAmount = {50000,90000,80000,50000,80000,90000}; + Employee e3 = AddEmployee.addCommissionEmployee("Commission1", "c", "中国农业银行", "0010", 2500, 0.01, salesReceiptDates, salesReceiptAmount); + + List result = new ArrayList(); + result.add(e1); + result.add(e2); + result.add(e3); + return result; + } +} diff --git a/students/1299310140/src/com/coderising/payroll/TimeCard.java b/students/1299310140/src/com/coderising/payroll/TimeCard.java new file mode 100644 index 0000000000..256915ede4 --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/TimeCard.java @@ -0,0 +1,21 @@ +package com.coderising.payroll; + +import java.util.Date; + +public class TimeCard { + private Date date; + private int hours; + + public TimeCard(Date date, int hours) { + super(); + this.date = date; + this.hours = hours; + } + + public Date getDate() { + return date; + } + public int getHours() { + return hours; + } +} diff --git a/students/1299310140/src/com/coderising/payroll/UnionAffiliation.java b/students/1299310140/src/com/coderising/payroll/UnionAffiliation.java new file mode 100644 index 0000000000..b95af11bdc --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/UnionAffiliation.java @@ -0,0 +1,35 @@ +package com.coderising.payroll; + +import java.util.ArrayList; +import java.util.List; + +public class UnionAffiliation implements Affiliation { + private String memberID = ""; + private int weeklyDue = 5; + private List serviceCharges = new ArrayList(); + + public UnionAffiliation(String memberID) { + super(); + this.memberID = memberID; + } + + public void addServiceCharge(ServiceCharge sc){ + this.serviceCharges.add(sc); + } + + @Override + public double calculateDeductions(Paycheck pc) { + int fridays = DateUtil.fridaysNum(pc.getPayPeriodStartDate(), + pc.getPayPeriodEndDate()); + int totalDue = fridays * this.weeklyDue; + int totalCharge = 0; + for (ServiceCharge sc : serviceCharges) { + if (DateUtil.between(sc.getDate(), pc.getPayPeriodStartDate(), + pc.getPayPeriodEndDate())) { + totalCharge += sc.getAmount(); + } + } + return totalDue + totalCharge; + } + +} diff --git a/students/1299310140/src/com/coderising/payroll/WeeklySchedule.java b/students/1299310140/src/com/coderising/payroll/WeeklySchedule.java new file mode 100644 index 0000000000..a59fdda127 --- /dev/null +++ b/students/1299310140/src/com/coderising/payroll/WeeklySchedule.java @@ -0,0 +1,17 @@ +package com.coderising.payroll; + +import java.util.Date; + +public class WeeklySchedule implements PaymentSchedule { + + @Override + public boolean isPayDate(Date date) { + return DateUtil.isFriday(date); + } + + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.add(payPeriodEndDate,-6); + } + +} diff --git a/students/1363044717/ood-assignment/pom.xml b/students/1363044717/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/1363044717/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..dbf48911d3 --- /dev/null +++ b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * + * @param sql + * @return + */ + public static List query(String sql) { + List userList = new ArrayList<>(); + for (int i = 1; i <= 3; i++) { + User userInfo = new User("User" + i, "aa@bb.com"); + userList.add(userInfo); + } + return userList; + } +} diff --git a/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtil.java b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtil.java new file mode 100644 index 0000000000..e7b12edd30 --- /dev/null +++ b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtil.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +/** + * Created by Mori on 2017/6/15. + */ +public class FileUtil { + + public static String readFile(File file) throws IOException { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + return temp; + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } +} diff --git a/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java new file mode 100644 index 0000000000..c18227852c --- /dev/null +++ b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java @@ -0,0 +1,28 @@ +package com.coderising.ood.srp; + +/** + * Created by Mori on 2017/6/15. + */ +public class Mail { + private String subject; + private String message; + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + protected void setPromotionMessage(String userName, String productDesc) { + this.setSubject("您关注的产品降价了"); + this.setMessage("尊敬的 " + userName + ", 您关注的产品 " + productDesc + " 降价了,欢迎购买!"); + } +} diff --git a/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..129ffdd207 --- /dev/null +++ b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,16 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress,Mail mail, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(mail.getSubject()).append("\n"); + buffer.append("Content:").append(mail.getMessage()).append("\n"); + System.out.println(buffer.toString()); + } + +} diff --git a/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..5ff6a9665f --- /dev/null +++ b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,34 @@ +package com.coderising.ood.srp; + +/** + * Created by Mori on 2017/6/15. + */ +public class Product { + + private String productID; + private String productDesc; + + public Product() { + } + + public Product(String productID, String productDesc) { + this.productID = productID; + this.productDesc = productDesc; + } + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git a/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..43d0b264bc --- /dev/null +++ b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,97 @@ +package com.coderising.ood.srp; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +public class PromotionMail { + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected Mail mail = new Mail(); + protected Product product = null; + protected boolean debug = false; + protected List mailingList = null; + + private static Configuration config; + + public static void main(String[] args) throws Exception { + File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + boolean emailDebug = false; + PromotionMail pe = new PromotionMail(f, emailDebug); + pe.sendEMails(); + } + + public PromotionMail(File file, boolean mailDebug) throws Exception { + debug = mailDebug; + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + loadProduct(file); + loadConfig(); + loadMailingList(); + } + + protected void loadProduct(File file) throws Exception { + String fileStr = FileUtil.readFile(file); + String data[] = fileStr.split(" "); + product = new Product(data[0], data[1]); + } + + protected void loadMailingList() { + mailingList = UserService.loadMailingListByProductId(product.getProductID()); + } + + protected void loadConfig() { + config = new Configuration(); + setSMTPHost(); + setAltSMTPHost(); + setFromAddress(); + } + + protected void setSMTPHost() { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + protected void setAltSMTPHost() { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + protected void setFromAddress() { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected boolean validateToAddress() { + return toAddress.length() > 0; + } + + protected void setToAddress(String address) { + toAddress = address; + } + + protected void sendEMails() throws IOException { + System.out.println("开始发送邮件"); + if (mailingList == null) { + System.out.println("没有邮件发送"); + return; + } + for (User user : mailingList) { + this.setToAddress(user.getEmail()); + if (!this.validateToAddress()) { + continue; + } + //设置促销消息 + mail.setPromotionMessage(user.getName(), product.getProductDesc()); + try { + MailUtil.sendEmail(toAddress, fromAddress, mail, smtpHost, debug); + } catch (Exception e) { + try { + MailUtil.sendEmail(toAddress, fromAddress, mail, altSmtpHost, debug); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + } +} diff --git a/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/User.java b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/User.java new file mode 100644 index 0000000000..71fcd1ea85 --- /dev/null +++ b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/User.java @@ -0,0 +1,34 @@ +package com.coderising.ood.srp; + +/** + * Created by Mori on 2017/6/15. + */ +public class User { + + private String email; + private String name; + + public User() { + } + + public User(String email, String name) { + this.email = email; + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/UserService.java b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/UserService.java new file mode 100644 index 0000000000..3b2bd5aac5 --- /dev/null +++ b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/UserService.java @@ -0,0 +1,17 @@ +package com.coderising.ood.srp; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by Mori on 2017/6/15. + */ +public class UserService { + + public static List loadMailingListByProductId(String productID) { + String sql = "Select name from subscriptions " + + "where product_id= '" + productID + "' " + + "and send_mail=1 "; + return DBUtil.query(sql); + } +} diff --git a/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/1363044717/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/136427763/ood/ood-assignment/pom.xml b/students/136427763/ood/ood-assignment/pom.xml new file mode 100644 index 0000000000..1be81576cc --- /dev/null +++ b/students/136427763/ood/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/config/Configuration.java b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/config/Configuration.java new file mode 100644 index 0000000000..7787c10665 --- /dev/null +++ b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/config/Configuration.java @@ -0,0 +1,25 @@ +package com.coderising.ood.config; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/config/ConfigurationKeys.java b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/config/ConfigurationKeys.java new file mode 100644 index 0000000000..a3595d3252 --- /dev/null +++ b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/config/ConfigurationKeys.java @@ -0,0 +1,13 @@ +package com.coderising.ood.config; + +public class ConfigurationKeys { + + public static final String NAME_KEY = "NAME"; + public static final String EMAIL_KEY = "EMAIL"; + + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/config/product_promotion.txt b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/config/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/config/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/mail/PromotionMail.java b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/mail/PromotionMail.java new file mode 100644 index 0000000000..df9965be08 --- /dev/null +++ b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/mail/PromotionMail.java @@ -0,0 +1,23 @@ +package com.coderising.ood.mail; + +import java.io.File; +import java.util.List; + +import com.coderising.ood.model.MailSender; +import com.coderising.ood.model.MailSetting; +import com.coderising.ood.model.Product; +import com.coderising.ood.model.SubcribeMailReciver; +import com.coderising.ood.util.FileUtil; + +public class PromotionMail { + + public static void main(String[] args) throws Exception { + File file = new File("D:\\homework\\coding2017\\students\\136427763\\ood\\ood-assignment\\src\\main\\java\\com\\coderising\\ood\\config\\product_promotion.txt"); + Product product=FileUtil.readProductFile(file); + SubcribeMailReciver subcribeMailReciver=new SubcribeMailReciver(); + List UserList=subcribeMailReciver.getMailReciverList(product); + boolean emailDebug = false; + MailSender mailSender=new MailSender(); + mailSender.sendEMails(emailDebug, UserList, product); + } +} diff --git a/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/model/MailMessage.java b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/model/MailMessage.java new file mode 100644 index 0000000000..23bbd87935 --- /dev/null +++ b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/model/MailMessage.java @@ -0,0 +1,38 @@ + +package com.coderising.ood.model; + +import java.util.HashMap; + +/** + * @author 作者 E-mail: + * @version 创建时间:2017年6月17日 下午9:13:21 + * 类说明 + */ +public class MailMessage { + + private String subject; + + private String message; + + private String toAddress; + + + public void createProductMessage(Product product,HashMap userInfo) { + subject = "您关注的产品降价了"; + message = "尊敬的 "+userInfo.get("NAME")+", 您关注的产品 " + product.getmProductDesc() + " 降价了,欢迎购买!" ; + toAddress=(String) userInfo.get("EMAIL"); + } + + public String getSubject() { + return subject; + } + + public String getToAddress() { + return toAddress; + } + + public String getMessage() { + return message; + } +} + \ No newline at end of file diff --git a/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/model/MailSender.java b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/model/MailSender.java new file mode 100644 index 0000000000..0c51fa5ce3 --- /dev/null +++ b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/model/MailSender.java @@ -0,0 +1,51 @@ +package com.coderising.ood.model; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import com.coderising.ood.util.DBUtil; +import com.coderising.ood.util.MailUtil; +import com.sun.jndi.cosnaming.IiopUrl.Address; + +/** + * @author 作者 E-mail: + * @version 创建时间:2017年6月17日 下午9:11:59 类说明 + */ +public class MailSender { + + public void sendEMails(boolean debug, List mailingList, Product product)throws IOException { + MailMessage mailMessage = new MailMessage(); + System.out.println("开始发送邮件"); + HashMap hashMap; + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + hashMap = (HashMap) iter.next(); + mailMessage.createProductMessage(product, hashMap); + try { + if (mailMessage.getToAddress().length() > 0) + MailUtil.sendEmail(mailMessage.getToAddress(), MailSetting + .getInstannce().getmFromAddress(), mailMessage + .getSubject(), mailMessage.getMessage(), MailSetting + .getInstannce().getmSmtpHost(), debug); + } catch (Exception e) { + try { + MailUtil.sendEmail(mailMessage.getToAddress(), MailSetting + .getInstannce().getmFromAddress(), mailMessage + .getSubject(), mailMessage.getMessage(), MailSetting + .getInstannce().getmSmtpHost(), debug); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2 + .getMessage()); + } + } + } + } + else { + System.out.println("没有邮件发送"); + } + } + +} diff --git a/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/model/MailSetting.java b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/model/MailSetting.java new file mode 100644 index 0000000000..57d33d6c91 --- /dev/null +++ b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/model/MailSetting.java @@ -0,0 +1,68 @@ +package com.coderising.ood.model; + +import com.coderising.ood.config.Configuration; +import com.coderising.ood.config.ConfigurationKeys; + +/** + * @author 作者 E-mail: + * @version 创建时间:2017年6月17日 下午9:50:47 类说明 + */ +public class MailSetting { + private String mSmtpHost; + + private String mAltmSmtpHost; + + private Configuration mConfig; + + private String mFromAddress; + + public String getmFromAddress() { + return mFromAddress; + } + + private static MailSetting mailSetting=null; + + private static final Object mObject=new Object(); + + public static MailSetting getInstannce(){ + synchronized (mObject) { + if(null==mailSetting){ + mailSetting =new MailSetting(); + return mailSetting; + } + return mailSetting; + } + } + + public MailSetting() { + mConfig=new Configuration(); + init(); + } + + private void init() { + setmAltmSmtpHost(); + setmFromAddress(); + setmSmtpHost(); + } + + public String getmSmtpHost() { + return mSmtpHost; + } + + public String getmAltmSmtpHost() { + return mAltmSmtpHost; + } + + protected void setmAltmSmtpHost() { + mAltmSmtpHost = mConfig.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + } + + protected void setmFromAddress() { + mFromAddress = mConfig.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setmSmtpHost() { + mSmtpHost = mConfig.getProperty(ConfigurationKeys.SMTP_SERVER); + } + +} diff --git a/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/model/Product.java b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/model/Product.java new file mode 100644 index 0000000000..c2d2a5887d --- /dev/null +++ b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/model/Product.java @@ -0,0 +1,39 @@ + +package com.coderising.ood.model; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +/** + * @author 作者 E-mail: + * @version 创建时间:2017年6月17日 下午9:13:21 + * 类说明 + */ +public class Product { + + private String mProductId; + + private String mProductDesc; + + public String getmProductId() { + return mProductId; + } + + public void setmProductId(String mProductId) { + this.mProductId = mProductId; + } + + public String getmProductDesc() { + return mProductDesc; + } + + public void setmProductDesc(String mProductDesc) { + this.mProductDesc = mProductDesc; + } + + + +} + \ No newline at end of file diff --git a/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/model/SubcribeMailReciver.java b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/model/SubcribeMailReciver.java new file mode 100644 index 0000000000..913e9164e2 --- /dev/null +++ b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/model/SubcribeMailReciver.java @@ -0,0 +1,27 @@ +package com.coderising.ood.model; + +import java.util.List; + +import com.coderising.ood.util.DBUtil; + +/** + * @author 作者 E-mail: + * @version 创建时间:2017年6月17日 下午10:51:43 类说明 + */ +public class SubcribeMailReciver { + + private String sendMailQuery; + + private void setLoadQuery(Product product) throws Exception { + + sendMailQuery = "Select name from subscriptions " + "where product_id= '" + product + .getmProductId() + "' " + "and send_mail=1 "; + System.out.println("loadQuery set"); + } + + public List getMailReciverList(Product product) throws Exception { + setLoadQuery(product); + return DBUtil.query(this.sendMailQuery); + } + +} diff --git a/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/util/DBUtil.java b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/util/DBUtil.java new file mode 100644 index 0000000000..9d33edbd40 --- /dev/null +++ b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/util/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.util; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/util/FileUtil.java b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/util/FileUtil.java new file mode 100644 index 0000000000..c57721fa6e --- /dev/null +++ b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/util/FileUtil.java @@ -0,0 +1,39 @@ + +package com.coderising.ood.util; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import com.coderising.ood.model.Product; + +/** + * @author 作者 E-mail: + * @version 创建时间:2017年6月17日 下午9:39:03 + * 类说明 + */ +public class FileUtil { + + public static Product readProductFile(File file) throws IOException + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + Product product=new Product(); + product.setmProductId(data[0]); + product.setmProductDesc(data[1]); + return product; + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + if(br!=null){ + br.close(); + } + } + } + +} + \ No newline at end of file diff --git a/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/util/MailUtil.java b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/util/MailUtil.java new file mode 100644 index 0000000000..913f83aba9 --- /dev/null +++ b/students/136427763/ood/ood-assignment/src/main/java/com/coderising/ood/util/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.util; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/1377699408/README.md b/students/1377699408/README.md new file mode 100644 index 0000000000..bf3d9bbc98 --- /dev/null +++ b/students/1377699408/README.md @@ -0,0 +1,2 @@ +## 1377699408的文件夹 +测试 diff --git a/students/1377699408/data-structure/answer/pom.xml b/students/1377699408/data-structure/answer/pom.xml new file mode 100644 index 0000000000..ac6ba882df --- /dev/null +++ b/students/1377699408/data-structure/answer/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ds-answer + 0.0.1-SNAPSHOT + jar + + ds-answer + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/DownloadThread.java b/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/DownloadThread.java new file mode 100644 index 0000000000..900a3ad358 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/DownloadThread.java @@ -0,0 +1,20 @@ +package com.coderising.download; + +import com.coderising.download.api.Connection; + +public class DownloadThread extends Thread{ + + Connection conn; + int startPos; + int endPos; + + public DownloadThread( Connection conn, int startPos, int endPos){ + + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + } + public void run(){ + + } +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/FileDownloader.java b/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/FileDownloader.java new file mode 100644 index 0000000000..c3c8a3f27d --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/FileDownloader.java @@ -0,0 +1,73 @@ +package com.coderising.download; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionException; +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; + + +public class FileDownloader { + + String url; + + DownloadListener listener; + + ConnectionManager cm; + + + public FileDownloader(String _url) { + this.url = _url; + + } + + public void execute(){ + // 在这里实现你的代码, 注意: 需要用多线程实现下载 + // 这个类依赖于其他几个接口, 你需要写这几个接口的实现代码 + // (1) ConnectionManager , 可以打开一个连接,通过Connection可以读取其中的一段(用startPos, endPos来指定) + // (2) DownloadListener, 由于是多线程下载, 调用这个类的客户端不知道什么时候结束,所以你需要实现当所有 + // 线程都执行完以后, 调用listener的notifiedFinished方法, 这样客户端就能收到通知。 + // 具体的实现思路: + // 1. 需要调用ConnectionManager的open方法打开连接, 然后通过Connection.getContentLength方法获得文件的长度 + // 2. 至少启动3个线程下载, 注意每个线程需要先调用ConnectionManager的open方法 + // 然后调用read方法, read方法中有读取文件的开始位置和结束位置的参数, 返回值是byte[]数组 + // 3. 把byte数组写入到文件中 + // 4. 所有的线程都下载完成以后, 需要调用listener的notifiedFinished方法 + + // 下面的代码是示例代码, 也就是说只有一个线程, 你需要改造成多线程的。 + Connection conn = null; + try { + + conn = cm.open(this.url); + + int length = conn.getContentLength(); + + new DownloadThread(conn,0,length-1).start(); + + } catch (ConnectionException e) { + e.printStackTrace(); + }finally{ + if(conn != null){ + conn.close(); + } + } + + + + + } + + public void setListener(DownloadListener listener) { + this.listener = listener; + } + + + + public void setConnectionManager(ConnectionManager ucm){ + this.cm = ucm; + } + + public DownloadListener getListener(){ + return this.listener; + } + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/FileDownloaderTest.java b/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/FileDownloaderTest.java new file mode 100644 index 0000000000..4ff7f46ae0 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/FileDownloaderTest.java @@ -0,0 +1,59 @@ +package com.coderising.download; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; +import com.coderising.download.impl.ConnectionManagerImpl; + +public class FileDownloaderTest { + boolean downloadFinished = false; + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testDownload() { + + String url = "http://localhost:8080/test.jpg"; + + FileDownloader downloader = new FileDownloader(url); + + + ConnectionManager cm = new ConnectionManagerImpl(); + downloader.setConnectionManager(cm); + + downloader.setListener(new DownloadListener() { + @Override + public void notifyFinished() { + downloadFinished = true; + } + + }); + + + downloader.execute(); + + // 等待多线程下载程序执行完毕 + while (!downloadFinished) { + try { + System.out.println("还没有下载完成,休眠五秒"); + //休眠5秒 + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + System.out.println("下载完成!"); + + + + } + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/api/Connection.java b/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/api/Connection.java new file mode 100644 index 0000000000..0957eaf7f4 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/api/Connection.java @@ -0,0 +1,23 @@ +package com.coderising.download.api; + +import java.io.IOException; + +public interface Connection { + /** + * 给定开始和结束位置, 读取数据, 返回值是字节数组 + * @param startPos 开始位置, 从0开始 + * @param endPos 结束位置 + * @return + */ + public byte[] read(int startPos,int endPos) throws IOException; + /** + * 得到数据内容的长度 + * @return + */ + public int getContentLength(); + + /** + * 关闭连接 + */ + public void close(); +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/api/ConnectionException.java b/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/api/ConnectionException.java new file mode 100644 index 0000000000..1551a80b3d --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/api/ConnectionException.java @@ -0,0 +1,5 @@ +package com.coderising.download.api; + +public class ConnectionException extends Exception { + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/api/ConnectionManager.java b/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/api/ConnectionManager.java new file mode 100644 index 0000000000..ce045393b1 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/api/ConnectionManager.java @@ -0,0 +1,10 @@ +package com.coderising.download.api; + +public interface ConnectionManager { + /** + * 给定一个url , 打开一个连接 + * @param url + * @return + */ + public Connection open(String url) throws ConnectionException; +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/api/DownloadListener.java b/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/api/DownloadListener.java new file mode 100644 index 0000000000..bf9807b307 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/api/DownloadListener.java @@ -0,0 +1,5 @@ +package com.coderising.download.api; + +public interface DownloadListener { + public void notifyFinished(); +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/impl/ConnectionImpl.java b/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..36a9d2ce15 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/impl/ConnectionImpl.java @@ -0,0 +1,27 @@ +package com.coderising.download.impl; + +import java.io.IOException; + +import com.coderising.download.api.Connection; + +public class ConnectionImpl implements Connection{ + + @Override + public byte[] read(int startPos, int endPos) throws IOException { + + return null; + } + + @Override + public int getContentLength() { + + return 0; + } + + @Override + public void close() { + + + } + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/impl/ConnectionManagerImpl.java b/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..172371dd55 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coderising/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,15 @@ +package com.coderising.download.impl; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionException; +import com.coderising.download.api.ConnectionManager; + +public class ConnectionManagerImpl implements ConnectionManager { + + @Override + public Connection open(String url) throws ConnectionException { + + return null; + } + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coderising/litestruts/LoginAction.java b/students/1377699408/data-structure/answer/src/main/java/com/coderising/litestruts/LoginAction.java new file mode 100644 index 0000000000..dcdbe226ed --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coderising/litestruts/LoginAction.java @@ -0,0 +1,39 @@ +package com.coderising.litestruts; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * @author liuxin + * + */ +public class LoginAction{ + private String name ; + private String password; + private String message; + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String execute(){ + if("test".equals(name) && "1234".equals(password)){ + this.message = "login successful"; + return "success"; + } + this.message = "login failed,please check your user/pwd"; + return "fail"; + } + + public void setName(String name){ + this.name = name; + } + public void setPassword(String password){ + this.password = password; + } + public String getMessage(){ + return this.message; + } +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coderising/litestruts/Struts.java b/students/1377699408/data-structure/answer/src/main/java/com/coderising/litestruts/Struts.java new file mode 100644 index 0000000000..85e2e22de3 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coderising/litestruts/Struts.java @@ -0,0 +1,34 @@ +package com.coderising.litestruts; + +import java.util.Map; + + + +public class Struts { + + public static View runAction(String actionName, Map parameters) { + + /* + + 0. 读取配置文件struts.xml + + 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + ("name"="test" , "password"="1234") , + 那就应该调用 setName和setPassword方法 + + 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + + 3. 通过反射找到对象的所有getter方法(例如 getMessage), + 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + 放到View对象的parameters + + 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + 放到View对象的jsp字段中。 + + */ + + return null; + } + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coderising/litestruts/StrutsTest.java b/students/1377699408/data-structure/answer/src/main/java/com/coderising/litestruts/StrutsTest.java new file mode 100644 index 0000000000..b8c81faf3c --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coderising/litestruts/StrutsTest.java @@ -0,0 +1,43 @@ +package com.coderising.litestruts; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + + + + + +public class StrutsTest { + + @Test + public void testLoginActionSuccess() { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coderising/litestruts/View.java b/students/1377699408/data-structure/answer/src/main/java/com/coderising/litestruts/View.java new file mode 100644 index 0000000000..07df2a5dab --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coderising/litestruts/View.java @@ -0,0 +1,23 @@ +package com.coderising.litestruts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coderising/litestruts/struts.xml b/students/1377699408/data-structure/answer/src/main/java/com/coderising/litestruts/struts.xml new file mode 100644 index 0000000000..e5d9aebba8 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coderising/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/Iterator.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/Iterator.java new file mode 100644 index 0000000000..06ef6311b2 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/Iterator.java @@ -0,0 +1,7 @@ +package com.coding.basic; + +public interface Iterator { + public boolean hasNext(); + public Object next(); + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/List.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/List.java new file mode 100644 index 0000000000..10d13b5832 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/List.java @@ -0,0 +1,9 @@ +package com.coding.basic; + +public interface List { + public void add(Object o); + public void add(int index, Object o); + public Object get(int index); + public Object remove(int index); + public int size(); +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/array/ArrayList.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/array/ArrayList.java new file mode 100644 index 0000000000..4576c016af --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/array/ArrayList.java @@ -0,0 +1,35 @@ +package com.coding.basic.array; + +import com.coding.basic.Iterator; +import com.coding.basic.List; + +public class ArrayList implements List { + + private int size = 0; + + private Object[] elementData = new Object[100]; + + public void add(Object o){ + + } + public void add(int index, Object o){ + + } + + public Object get(int index){ + return null; + } + + public Object remove(int index){ + return null; + } + + public int size(){ + return -1; + } + + public Iterator iterator(){ + return null; + } + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/array/ArrayUtil.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/array/ArrayUtil.java new file mode 100644 index 0000000000..45740e6d57 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/array/ArrayUtil.java @@ -0,0 +1,96 @@ +package com.coding.basic.array; + +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 + 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * @param origin + * @return + */ + public void reverseArray(int[] origin){ + + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: + * {1,3,4,5,6,6,5,4,7,6,7,5} + * @param oldArray + * @return + */ + + public int[] removeZero(int[] oldArray){ + return null; + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 + * 例如 a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * @param array1 + * @param array2 + * @return + */ + + public int[] merge(int[] array1, int[] array2){ + return null; + } + /** + * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size + * 注意,老数组的元素在新数组中需要保持 + * 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 + * [2,3,6,0,0,0] + * @param oldArray + * @param size + * @return + */ + public int[] grow(int [] oldArray, int size){ + return null; + } + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 + * 例如, max = 15 , 则返回的数组应该为 [1,1,2,3,5,8,13] + * max = 1, 则返回空数组 [] + * @param max + * @return + */ + public int[] fibonacci(int max){ + return null; + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public int[] getPrimes(int max){ + return null; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public int[] getPerfectNumbers(int max){ + return null; + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * @param array + * @param s + * @return + */ + public String join(int[] array, String seperator){ + return null; + } + + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/linklist/LRUPageFrame.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/linklist/LRUPageFrame.java new file mode 100644 index 0000000000..24b9d8b155 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/linklist/LRUPageFrame.java @@ -0,0 +1,164 @@ +package com.coding.basic.linklist; + + +public class LRUPageFrame { + + private static class Node { + + Node prev; + Node next; + int pageNum; + + Node() { + } + } + + private int capacity; + + private int currentSize; + private Node first;// 链表头 + private Node last;// 链表尾 + + + public LRUPageFrame(int capacity) { + this.currentSize = 0; + this.capacity = capacity; + + } + + /** + * 获取缓存中对象 + * + * @param key + * @return + */ + public void access(int pageNum) { + + Node node = find(pageNum); + //在该队列中存在, 则提到队列头 + if (node != null) { + + moveExistingNodeToHead(node); + + } else{ + + node = new Node(); + node.pageNum = pageNum; + + // 缓存容器是否已经超过大小. + if (currentSize >= capacity) { + removeLast(); + + } + + addNewNodetoHead(node); + + + + + } + } + + private void addNewNodetoHead(Node node) { + + if(isEmpty()){ + + node.prev = null; + node.next = null; + first = node; + last = node; + + } else{ + node.prev = null; + node.next = first; + first.prev = node; + first = node; + } + this.currentSize ++; + } + + private Node find(int data){ + + Node node = first; + while(node != null){ + if(node.pageNum == data){ + return node; + } + node = node.next; + } + return null; + + } + + + + + + + /** + * 删除链表尾部节点 表示 删除最少使用的缓存对象 + */ + private void removeLast() { + Node prev = last.prev; + prev.next = null; + last.prev = null; + last = prev; + this.currentSize --; + } + + /** + * 移动到链表头,表示这个节点是最新使用过的 + * + * @param node + */ + private void moveExistingNodeToHead(Node node) { + + if (node == first) { + + return; + } + else if(node == last){ + //当前节点是链表尾, 需要放到链表头 + Node prevNode = node.prev; + prevNode.next = null; + last.prev = null; + last = prevNode; + + } else{ + //node 在链表的中间, 把node 的前后节点连接起来 + Node prevNode = node.prev; + prevNode.next = node.next; + + Node nextNode = node.next; + nextNode.prev = prevNode; + + + } + + node.prev = null; + node.next = first; + first.prev = node; + first = node; + + } + private boolean isEmpty(){ + return (first == null) && (last == null); + } + + public String toString(){ + StringBuilder buffer = new StringBuilder(); + Node node = first; + while(node != null){ + buffer.append(node.pageNum); + + node = node.next; + if(node != null){ + buffer.append(","); + } + } + return buffer.toString(); + } + + + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/linklist/LRUPageFrameTest.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/linklist/LRUPageFrameTest.java new file mode 100644 index 0000000000..7fd72fc2b4 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/linklist/LRUPageFrameTest.java @@ -0,0 +1,34 @@ +package com.coding.basic.linklist; + +import org.junit.Assert; + +import org.junit.Test; + + +public class LRUPageFrameTest { + + @Test + public void testAccess() { + LRUPageFrame frame = new LRUPageFrame(3); + frame.access(7); + frame.access(0); + frame.access(1); + Assert.assertEquals("1,0,7", frame.toString()); + frame.access(2); + Assert.assertEquals("2,1,0", frame.toString()); + frame.access(0); + Assert.assertEquals("0,2,1", frame.toString()); + frame.access(0); + Assert.assertEquals("0,2,1", frame.toString()); + frame.access(3); + Assert.assertEquals("3,0,2", frame.toString()); + frame.access(0); + Assert.assertEquals("0,3,2", frame.toString()); + frame.access(4); + Assert.assertEquals("4,0,3", frame.toString()); + frame.access(5); + Assert.assertEquals("5,4,0", frame.toString()); + + } + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/linklist/LinkedList.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/linklist/LinkedList.java new file mode 100644 index 0000000000..f4c7556a2e --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/linklist/LinkedList.java @@ -0,0 +1,125 @@ +package com.coding.basic.linklist; + +import com.coding.basic.Iterator; +import com.coding.basic.List; + +public class LinkedList implements List { + + private Node head; + + public void add(Object o){ + + } + public void add(int index , Object o){ + + } + public Object get(int index){ + return null; + } + public Object remove(int index){ + return null; + } + + public int size(){ + return -1; + } + + public void addFirst(Object o){ + + } + public void addLast(Object o){ + + } + public Object removeFirst(){ + return null; + } + public Object removeLast(){ + return null; + } + public Iterator iterator(){ + return null; + } + + + private static class Node{ + Object data; + Node next; + + } + + /** + * 把该链表逆置 + * 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + + */ + public void removeFirstHalf(){ + + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * @param i + * @param length + */ + public void remove(int i, int length){ + + } + /** + * 假定当前链表和listB均包含已升序排列的整数 + * 从当前链表中取出那些listB所指定的元素 + * 例如当前链表 = 11->101->201->301->401->501->601->701 + * listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + * @param list + */ + public int[] getElements(LinkedList list){ + return null; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 从当前链表中中删除在listB中出现的元素 + + * @param list + */ + + public void subtract(LinkedList list){ + + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues(){ + + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * @param min + * @param max + */ + public void removeRange(int min, int max){ + + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * @param list + */ + public LinkedList intersection( LinkedList list){ + return null; + } +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/queue/CircleQueue.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/queue/CircleQueue.java new file mode 100644 index 0000000000..f169d5f8e4 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/queue/CircleQueue.java @@ -0,0 +1,47 @@ +package com.coding.basic.queue; + +public class CircleQueue { + + //用数组来保存循环队列的元素 + private Object[] elementData ; + int size = 0; + //队头 + private int front = 0; + //队尾 + private int rear = 0; + + public CircleQueue(int capacity){ + elementData = new Object[capacity]; + } + public boolean isEmpty() { + return (front == rear) && !isFull(); + + } + + public boolean isFull(){ + return size == elementData.length; + } + public int size() { + return size; + } + + public void enQueue(E data) { + if(isFull()){ + throw new RuntimeException("The queue is full"); + } + rear = (rear+1) % elementData.length; + elementData[rear++] = data; + size++; + } + + public E deQueue() { + if(isEmpty()){ + throw new RuntimeException("The queue is empty"); + } + E data = (E)elementData[front]; + elementData[front] = null; + front = (front+1) % elementData.length; + size --; + return data; + } +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/queue/CircleQueueTest.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/queue/CircleQueueTest.java new file mode 100644 index 0000000000..7307eb77d4 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/queue/CircleQueueTest.java @@ -0,0 +1,44 @@ +package com.coding.basic.queue; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class CircleQueueTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void test() { + CircleQueue queue = new CircleQueue(5); + Assert.assertTrue(queue.isEmpty()); + Assert.assertFalse(queue.isFull()); + + queue.enQueue("a"); + queue.enQueue("b"); + queue.enQueue("c"); + queue.enQueue("d"); + queue.enQueue("e"); + + Assert.assertTrue(queue.isFull()); + Assert.assertFalse(queue.isEmpty()); + Assert.assertEquals(5, queue.size()); + + Assert.assertEquals("a", queue.deQueue()); + Assert.assertEquals("b", queue.deQueue()); + Assert.assertEquals("c", queue.deQueue()); + Assert.assertEquals("d", queue.deQueue()); + Assert.assertEquals("e", queue.deQueue()); + + } + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/queue/Josephus.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/queue/Josephus.java new file mode 100644 index 0000000000..36ec615d36 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/queue/Josephus.java @@ -0,0 +1,39 @@ +package com.coding.basic.queue; + +import java.util.ArrayList; +import java.util.List; + +/** + * 用Queue来实现Josephus问题 + * 在这个古老的问题当中, N个深陷绝境的人一致同意用这种方式减少生存人数: N个人围成一圈(位置记为0到N-1), 并且从第一个人报数, 报到M的人会被杀死, 直到最后一个人留下来 + * @author liuxin + * + */ +public class Josephus { + + public static List execute(int n, int m){ + + Queue queue = new Queue(); + for (int i = 0; i < n; i++){ + queue.enQueue(i); + } + + List result = new ArrayList(); + int i = 0; + + while (!queue.isEmpty()) { + + int x = queue.deQueue(); + + if (++i % m == 0){ + result.add(x); + } else{ + queue.enQueue(x); + } + } + + + return result; + } + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/queue/JosephusTest.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/queue/JosephusTest.java new file mode 100644 index 0000000000..7d90318b51 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/queue/JosephusTest.java @@ -0,0 +1,27 @@ +package com.coding.basic.queue; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class JosephusTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testExecute() { + + Assert.assertEquals("[1, 3, 5, 0, 4, 2, 6]", Josephus.execute(7, 2).toString()); + + } + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/queue/Queue.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/queue/Queue.java new file mode 100644 index 0000000000..c4c4b7325e --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/queue/Queue.java @@ -0,0 +1,61 @@ +package com.coding.basic.queue; + +import java.util.NoSuchElementException; + +public class Queue { + private Node first; + private Node last; + private int size; + + + private static class Node { + private E item; + private Node next; + } + + + public Queue() { + first = null; + last = null; + size = 0; + } + + + public boolean isEmpty() { + return first == null; + } + + public int size() { + return size; + } + + + + public void enQueue(E data) { + Node oldlast = last; + last = new Node(); + last.item = data; + last.next = null; + if (isEmpty()) { + first = last; + } + else{ + oldlast.next = last; + } + size++; + } + + public E deQueue() { + if (isEmpty()) { + throw new NoSuchElementException("Queue underflow"); + } + E item = first.item; + first = first.next; + size--; + if (isEmpty()) { + last = null; + } + return item; + } + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/queue/QueueWithTwoStacks.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/queue/QueueWithTwoStacks.java new file mode 100644 index 0000000000..bc97df0800 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/queue/QueueWithTwoStacks.java @@ -0,0 +1,55 @@ +package com.coding.basic.queue; + +import java.util.NoSuchElementException; +import java.util.Stack; + +public class QueueWithTwoStacks { + private Stack stack1; + private Stack stack2; + + + public QueueWithTwoStacks() { + stack1 = new Stack(); + stack2 = new Stack(); + } + + + private void moveStack1ToStack2() { + while (!stack1.isEmpty()){ + stack2.push(stack1.pop()); + } + + } + + + public boolean isEmpty() { + return stack1.isEmpty() && stack2.isEmpty(); + } + + + + public int size() { + return stack1.size() + stack2.size(); + } + + + + public void enQueue(E item) { + stack1.push(item); + } + + public E deQueue() { + if (isEmpty()) { + throw new NoSuchElementException("Queue is empty"); + } + if (stack2.isEmpty()) { + moveStack1ToStack2(); + } + + return stack2.pop(); + } + + + + } + diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/QuickMinStack.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/QuickMinStack.java new file mode 100644 index 0000000000..faf2644ab1 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/QuickMinStack.java @@ -0,0 +1,44 @@ +package com.coding.basic.stack; + +import java.util.Stack; +/** + * 设计一个栈,支持栈的push和pop操作,以及第三种操作findMin, 它返回改数据结构中的最小元素 + * finMin操作最坏的情形下时间复杂度应该是O(1) , 简单来讲,操作一次就可以得到最小值 + * @author liuxin + * + */ +public class QuickMinStack { + + private Stack normalStack = new Stack(); + private Stack minNumStack = new Stack(); + + public void push(int data){ + + normalStack.push(data); + + if(minNumStack.isEmpty()){ + minNumStack.push(data); + } else{ + if(minNumStack.peek() >= data) { + minNumStack.push(data); + } + } + + } + public int pop(){ + if(normalStack.isEmpty()){ + throw new RuntimeException("the stack is empty"); + } + int value = normalStack.pop(); + if(value == minNumStack.peek()){ + minNumStack.pop(); + } + return value; + } + public int findMin(){ + if(minNumStack.isEmpty()){ + throw new RuntimeException("the stack is empty"); + } + return minNumStack.peek(); + } +} \ No newline at end of file diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/QuickMinStackTest.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/QuickMinStackTest.java new file mode 100644 index 0000000000..efe41a9f8f --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/QuickMinStackTest.java @@ -0,0 +1,39 @@ +package com.coding.basic.stack; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + +public class QuickMinStackTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void test() { + QuickMinStack stack = new QuickMinStack(); + stack.push(5); + Assert.assertEquals(5, stack.findMin()); + stack.push(6); + Assert.assertEquals(5, stack.findMin()); + stack.push(4); + Assert.assertEquals(4, stack.findMin()); + stack.push(4); + Assert.assertEquals(4, stack.findMin()); + + stack.pop(); + Assert.assertEquals(4, stack.findMin()); + stack.pop(); + Assert.assertEquals(5, stack.findMin()); + stack.pop(); + Assert.assertEquals(5, stack.findMin()); + } + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/Stack.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/Stack.java new file mode 100644 index 0000000000..fedb243604 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/Stack.java @@ -0,0 +1,24 @@ +package com.coding.basic.stack; + +import com.coding.basic.array.ArrayList; + +public class Stack { + private ArrayList elementData = new ArrayList(); + + public void push(Object o){ + } + + public Object pop(){ + return null; + } + + public Object peek(){ + return null; + } + public boolean isEmpty(){ + return false; + } + public int size(){ + return -1; + } +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/StackUtil.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/StackUtil.java new file mode 100644 index 0000000000..7c86d22fe7 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/StackUtil.java @@ -0,0 +1,168 @@ +package com.coding.basic.stack; +import java.util.Stack; +public class StackUtil { + + public static void bad_reverse(Stack s) { + if(s == null || s.isEmpty()){ + return; + } + Stack tmpStack = new Stack(); + while(!s.isEmpty()){ + tmpStack.push(s.pop()); + } + + s = tmpStack; + + } + + + + public static void reverse_247565311(Stack s){ + if(s == null || s.isEmpty()) { + return; + } + + int size = s.size(); + Stack tmpStack = new Stack(); + + for(int i=0;ii){ + tmpStack.push(s.pop()); + } + s.push(top); + while(tmpStack.size()>0){ + s.push(tmpStack.pop()); + } + } + } + + + + /** + * 假设栈中的元素是Integer, 从栈顶到栈底是 : 5,4,3,2,1 调用该方法后, 元素次序变为: 1,2,3,4,5 + * 注意:只能使用Stack的基本操作,即push,pop,peek,isEmpty, 可以使用另外一个栈来辅助 + */ + public static void reverse(Stack s) { + if(s == null || s.isEmpty()){ + return; + } + + Stack tmp = new Stack(); + while(!s.isEmpty()){ + tmp.push(s.pop()); + } + while(!tmp.isEmpty()){ + Integer top = tmp.pop(); + addToBottom(s,top); + } + + + } + public static void addToBottom(Stack s, Integer value){ + if(s.isEmpty()){ + s.push(value); + } else{ + Integer top = s.pop(); + addToBottom(s,value); + s.push(top); + } + + } + /** + * 删除栈中的某个元素 注意:只能使用Stack的基本操作,即push,pop,peek,isEmpty, 可以使用另外一个栈来辅助 + * + * @param o + */ + public static void remove(Stack s,Object o) { + if(s == null || s.isEmpty()){ + return; + } + Stack tmpStack = new Stack(); + + while(!s.isEmpty()){ + Object value = s.pop(); + if(!value.equals(o)){ + tmpStack.push(value); + } + } + + while(!tmpStack.isEmpty()){ + s.push(tmpStack.pop()); + } + } + + /** + * 从栈顶取得len个元素, 原来的栈中元素保持不变 + * 注意:只能使用Stack的基本操作,即push,pop,peek,isEmpty, 可以使用另外一个栈来辅助 + * @param len + * @return + */ + public static Object[] getTop(Stack s,int len) { + + if(s == null || s.isEmpty() || s.size() stack = new Stack(); + for(int i=0;i s = new Stack(); + s.push(1); + s.push(2); + s.push(3); + + StackUtil.addToBottom(s, 0); + + Assert.assertEquals("[0, 1, 2, 3]", s.toString()); + + } + @Test + public void testReverse() { + Stack s = new Stack(); + s.push(1); + s.push(2); + s.push(3); + s.push(4); + s.push(5); + Assert.assertEquals("[1, 2, 3, 4, 5]", s.toString()); + StackUtil.reverse(s); + Assert.assertEquals("[5, 4, 3, 2, 1]", s.toString()); + } + @Test + public void testReverse_247565311() { + Stack s = new Stack(); + s.push(1); + s.push(2); + s.push(3); + + Assert.assertEquals("[1, 2, 3]", s.toString()); + StackUtil.reverse_247565311(s); + Assert.assertEquals("[3, 2, 1]", s.toString()); + } + @Test + public void testRemove() { + Stack s = new Stack(); + s.push(1); + s.push(2); + s.push(3); + StackUtil.remove(s, 2); + Assert.assertEquals("[1, 3]", s.toString()); + } + + @Test + public void testGetTop() { + Stack s = new Stack(); + s.push(1); + s.push(2); + s.push(3); + s.push(4); + s.push(5); + { + Object[] values = StackUtil.getTop(s, 3); + Assert.assertEquals(5, values[0]); + Assert.assertEquals(4, values[1]); + Assert.assertEquals(3, values[2]); + } + } + + @Test + public void testIsValidPairs() { + Assert.assertTrue(StackUtil.isValidPairs("([e{d}f])")); + Assert.assertFalse(StackUtil.isValidPairs("([b{x]y})")); + } + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/StackWithTwoQueues.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/StackWithTwoQueues.java new file mode 100644 index 0000000000..7a58fbff56 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/StackWithTwoQueues.java @@ -0,0 +1,53 @@ +package com.coding.basic.stack; + +import java.util.ArrayDeque; +import java.util.Queue; + +public class StackWithTwoQueues { + Queue queue1 = new ArrayDeque<>(); + Queue queue2 = new ArrayDeque<>(); + + public void push(int data) { + //两个栈都为空时,优先考虑queue1 + if (queue1.isEmpty()&&queue2.isEmpty()) { + queue1.add(data); + return; + } + + if (queue1.isEmpty()) { + queue2.add(data); + return; + } + + if (queue2.isEmpty()) { + queue1.add(data); + return; + } + + } + + public int pop() { + + if (queue1.isEmpty()&&queue2.isEmpty()) { + throw new RuntimeException("stack is empty"); + } + + if (queue1.isEmpty()) { + while (queue2.size()>1) { + queue1.add(queue2.poll()); + } + return queue2.poll(); + } + + if (queue2.isEmpty()) { + while (queue1.size()>1) { + queue2.add(queue1.poll()); + } + return queue1.poll(); + } + + throw new RuntimeException("no queue is empty, this is not allowed"); + + + } +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/StackWithTwoQueuesTest.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/StackWithTwoQueuesTest.java new file mode 100644 index 0000000000..4541b1f040 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/StackWithTwoQueuesTest.java @@ -0,0 +1,36 @@ +package com.coding.basic.stack; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class StackWithTwoQueuesTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void test() { + StackWithTwoQueues stack = new StackWithTwoQueues(); + stack.push(1); + stack.push(2); + stack.push(3); + stack.push(4); + Assert.assertEquals(4, stack.pop()); + Assert.assertEquals(3, stack.pop()); + + stack.push(5); + Assert.assertEquals(5, stack.pop()); + Assert.assertEquals(2, stack.pop()); + Assert.assertEquals(1, stack.pop()); + } + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/Tail.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/Tail.java new file mode 100644 index 0000000000..7f30ce55c8 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/Tail.java @@ -0,0 +1,5 @@ +package com.coding.basic.stack; + +public class Tail { + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/TwoStackInOneArray.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/TwoStackInOneArray.java new file mode 100644 index 0000000000..a532fd6e6c --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/TwoStackInOneArray.java @@ -0,0 +1,117 @@ +package com.coding.basic.stack; + +import java.util.Arrays; + +/** + * 用一个数组实现两个栈 + * 将数组的起始位置看作是第一个栈的栈底,将数组的尾部看作第二个栈的栈底,压栈时,栈顶指针分别向中间移动,直到两栈顶指针相遇,则扩容。 + * @author liuxin + * + */ +public class TwoStackInOneArray { + private Object[] data = new Object[10]; + private int size; + private int top1, top2; + + public TwoStackInOneArray(int n){ + data = new Object[n]; + size = n; + top1 = -1; + top2 = data.length; + } + /** + * 向第一个栈中压入元素 + * @param o + */ + public void push1(Object o){ + ensureCapacity(); + data[++top1] = o; + } + /* + * 向第二个栈压入元素 + */ + public void push2(Object o){ + ensureCapacity(); + data[--top2] = o; + } + public void ensureCapacity(){ + if(top2-top1>1){ + return; + } else{ + + Object[] newArray = new Object[data.length*2]; + System.arraycopy(data, 0, newArray, 0, top1+1); + + int stack2Size = data.length-top2; + int newTop2 = newArray.length-stack2Size; + System.arraycopy(data, top2, newArray, newTop2, stack2Size); + + top2 = newTop2; + data = newArray; + } + } + /** + * 从第一个栈中弹出元素 + * @return + */ + public Object pop1(){ + if(top1 == -1){ + throw new RuntimeException("Stack1 is empty"); + } + Object o = data[top1]; + data[top1] = null; + top1--; + return o; + + } + /** + * 从第二个栈弹出元素 + * @return + */ + public Object pop2(){ + if(top2 == data.length){ + throw new RuntimeException("Stack2 is empty"); + } + Object o = data[top2]; + data[top2] = null; + top2++; + return o; + } + /** + * 获取第一个栈的栈顶元素 + * @return + */ + + public Object peek1(){ + if(top1 == -1){ + throw new RuntimeException("Stack1 is empty"); + } + return data[top1]; + } + + + /** + * 获取第二个栈的栈顶元素 + * @return + */ + + public Object peek2(){ + if(top2 == data.length){ + throw new RuntimeException("Stack2 is empty"); + } + return data[top2]; + } + + public Object[] stack1ToArray(){ + return Arrays.copyOf(data, top1+1); + } + public Object[] stack2ToArray(){ + int size = data.length-top2; + Object [] stack2Data = new Object[size]; + int j=0; + for(int i=data.length-1; i>=top2 ;i--){ + stack2Data[j++] = data[i]; + } + return stack2Data; + } +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/TwoStackInOneArrayTest.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/TwoStackInOneArrayTest.java new file mode 100644 index 0000000000..b743d422c6 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/TwoStackInOneArrayTest.java @@ -0,0 +1,65 @@ +package com.coding.basic.stack; + +import java.util.Arrays; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class TwoStackInOneArrayTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void test1() { + TwoStackInOneArray stack = new TwoStackInOneArray(10); + stack.push1(1); + stack.push1(2); + stack.push1(3); + stack.push1(4); + stack.push1(5); + + stack.push2(1); + stack.push2(2); + stack.push2(3); + stack.push2(4); + stack.push2(5); + + for(int i=1;i<=5;i++){ + Assert.assertEquals(stack.peek1(), stack.peek2()); + Assert.assertEquals(stack.pop1(), stack.pop2()); + } + + + } + @Test + public void test2() { + TwoStackInOneArray stack = new TwoStackInOneArray(5); + stack.push1(1); + stack.push1(2); + stack.push1(3); + stack.push1(4); + stack.push1(5); + stack.push1(6); + stack.push1(7); + + stack.push2(1); + stack.push2(2); + stack.push2(3); + stack.push2(4); + + + Assert.assertEquals("[1, 2, 3, 4, 5, 6, 7]",Arrays.toString(stack.stack1ToArray())); + Assert.assertEquals("[1, 2, 3, 4]",Arrays.toString(stack.stack2ToArray())); + } + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixExpr.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixExpr.java new file mode 100644 index 0000000000..cebef21fa3 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixExpr.java @@ -0,0 +1,72 @@ +package com.coding.basic.stack.expr; + +import java.util.List; +import java.util.Stack; + + +public class InfixExpr { + String expr = null; + + public InfixExpr(String expr) { + this.expr = expr; + } + + public float evaluate() { + + + TokenParser parser = new TokenParser(); + List tokens = parser.parse(this.expr); + + + Stack opStack = new Stack<>(); + Stack numStack = new Stack<>(); + + for(Token token : tokens){ + + if (token.isOperator()){ + + while(!opStack.isEmpty() + && !token.hasHigherPriority(opStack.peek())){ + Token prevOperator = opStack.pop(); + Float f2 = numStack.pop(); + Float f1 = numStack.pop(); + Float result = calculate(prevOperator.toString(), f1,f2); + numStack.push(result); + + } + opStack.push(token); + } + if(token.isNumber()){ + numStack.push(new Float(token.getIntValue())); + } + } + + while(!opStack.isEmpty()){ + Token token = opStack.pop(); + Float f2 = numStack.pop(); + Float f1 = numStack.pop(); + numStack.push(calculate(token.toString(), f1,f2)); + } + + + return numStack.pop().floatValue(); + } + private Float calculate(String op, Float f1, Float f2){ + if(op.equals("+")){ + return f1+f2; + } + if(op.equals("-")){ + return f1-f2; + } + if(op.equals("*")){ + return f1*f2; + } + if(op.equals("/")){ + return f1/f2; + } + throw new RuntimeException(op + " is not supported"); + } + + + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixExprTest.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixExprTest.java new file mode 100644 index 0000000000..20e34e8852 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixExprTest.java @@ -0,0 +1,52 @@ +package com.coding.basic.stack.expr; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + +public class InfixExprTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testEvaluate() { + //InfixExpr expr = new InfixExpr("300*20+12*5-20/4"); + { + InfixExpr expr = new InfixExpr("2+3*4+5"); + Assert.assertEquals(19.0, expr.evaluate(), 0.001f); + } + { + InfixExpr expr = new InfixExpr("3*20+12*5-40/2"); + Assert.assertEquals(100.0, expr.evaluate(), 0.001f); + } + + { + InfixExpr expr = new InfixExpr("3*20/2"); + Assert.assertEquals(30, expr.evaluate(), 0.001f); + } + + { + InfixExpr expr = new InfixExpr("20/2*3"); + Assert.assertEquals(30, expr.evaluate(), 0.001f); + } + + { + InfixExpr expr = new InfixExpr("10-30+50"); + Assert.assertEquals(30, expr.evaluate(), 0.001f); + } + { + InfixExpr expr = new InfixExpr("10-2*3+50"); + Assert.assertEquals(54, expr.evaluate(), 0.001f); + } + + } + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixToPostfix.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixToPostfix.java new file mode 100644 index 0000000000..9e501eda20 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixToPostfix.java @@ -0,0 +1,43 @@ +package com.coding.basic.stack.expr; + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +public class InfixToPostfix { + + public static List convert(String expr) { + List inFixTokens = new TokenParser().parse(expr); + + List postFixTokens = new ArrayList<>(); + + Stack opStack = new Stack(); + for(Token token : inFixTokens){ + + if(token.isOperator()){ + + while(!opStack.isEmpty() + && !token.hasHigherPriority(opStack.peek())){ + postFixTokens.add(opStack.pop()); + + } + opStack.push(token); + + } + if(token.isNumber()){ + + postFixTokens.add(token); + + } + } + + while(!opStack.isEmpty()){ + postFixTokens.add(opStack.pop()); + } + + return postFixTokens; + } + + + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixToPostfixTest.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixToPostfixTest.java new file mode 100644 index 0000000000..f879f55f14 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixToPostfixTest.java @@ -0,0 +1,41 @@ +package com.coding.basic.stack.expr; + +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class InfixToPostfixTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testConvert() { + { + List tokens = InfixToPostfix.convert("2+3"); + Assert.assertEquals("[2, 3, +]", tokens.toString()); + } + { + + List tokens = InfixToPostfix.convert("2+3*4"); + Assert.assertEquals("[2, 3, 4, *, +]", tokens.toString()); + } + + { + + List tokens = InfixToPostfix.convert("2-3*4+5"); + Assert.assertEquals("[2, 3, 4, *, -, 5, +]", tokens.toString()); + } + } + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PostfixExpr.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PostfixExpr.java new file mode 100644 index 0000000000..c54eb69e2a --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PostfixExpr.java @@ -0,0 +1,46 @@ +package com.coding.basic.stack.expr; + +import java.util.List; +import java.util.Stack; + +public class PostfixExpr { +String expr = null; + + public PostfixExpr(String expr) { + this.expr = expr; + } + + public float evaluate() { + TokenParser parser = new TokenParser(); + List tokens = parser.parse(this.expr); + + + Stack numStack = new Stack<>(); + for(Token token : tokens){ + if(token.isNumber()){ + numStack.push(new Float(token.getIntValue())); + } else{ + Float f2 = numStack.pop(); + Float f1 = numStack.pop(); + numStack.push(calculate(token.toString(),f1,f2)); + } + } + return numStack.pop().floatValue(); + } + + private Float calculate(String op, Float f1, Float f2){ + if(op.equals("+")){ + return f1+f2; + } + if(op.equals("-")){ + return f1-f2; + } + if(op.equals("*")){ + return f1*f2; + } + if(op.equals("/")){ + return f1/f2; + } + throw new RuntimeException(op + " is not supported"); + } +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PostfixExprTest.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PostfixExprTest.java new file mode 100644 index 0000000000..c0435a2db5 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PostfixExprTest.java @@ -0,0 +1,41 @@ +package com.coding.basic.stack.expr; + + + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class PostfixExprTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testEvaluate() { + { + PostfixExpr expr = new PostfixExpr("6 5 2 3 + 8 * + 3 + *"); + Assert.assertEquals(288, expr.evaluate(),0.0f); + } + { + //9+(3-1)*3+10/2 + PostfixExpr expr = new PostfixExpr("9 3 1-3*+ 10 2/+"); + Assert.assertEquals(20, expr.evaluate(),0.0f); + } + + { + //10-2*3+50 + PostfixExpr expr = new PostfixExpr("10 2 3 * - 50 +"); + Assert.assertEquals(54, expr.evaluate(),0.0f); + } + } + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PrefixExpr.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PrefixExpr.java new file mode 100644 index 0000000000..f811fd6d9a --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PrefixExpr.java @@ -0,0 +1,52 @@ +package com.coding.basic.stack.expr; + +import java.util.List; +import java.util.Stack; + +public class PrefixExpr { + String expr = null; + + public PrefixExpr(String expr) { + this.expr = expr; + } + + public float evaluate() { + TokenParser parser = new TokenParser(); + List tokens = parser.parse(this.expr); + + Stack exprStack = new Stack<>(); + Stack numStack = new Stack<>(); + for(Token token : tokens){ + exprStack.push(token); + } + + while(!exprStack.isEmpty()){ + Token t = exprStack.pop(); + if(t.isNumber()){ + numStack.push(new Float(t.getIntValue())); + }else{ + Float f1 = numStack.pop(); + Float f2 = numStack.pop(); + numStack.push(calculate(t.toString(),f1,f2)); + + } + } + return numStack.pop().floatValue(); + } + + private Float calculate(String op, Float f1, Float f2){ + if(op.equals("+")){ + return f1+f2; + } + if(op.equals("-")){ + return f1-f2; + } + if(op.equals("*")){ + return f1*f2; + } + if(op.equals("/")){ + return f1/f2; + } + throw new RuntimeException(op + " is not supported"); + } +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PrefixExprTest.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PrefixExprTest.java new file mode 100644 index 0000000000..5cec210e75 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PrefixExprTest.java @@ -0,0 +1,45 @@ +package com.coding.basic.stack.expr; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + +public class PrefixExprTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testEvaluate() { + { + // 2*3+4*5 + PrefixExpr expr = new PrefixExpr("+ * 2 3* 4 5"); + Assert.assertEquals(26, expr.evaluate(),0.001f); + } + { + // 4*2 + 6+9*2/3 -8 + PrefixExpr expr = new PrefixExpr("-++6/*2 9 3 * 4 2 8"); + Assert.assertEquals(12, expr.evaluate(),0.001f); + } + { + //(3+4)*5-6 + PrefixExpr expr = new PrefixExpr("- * + 3 4 5 6"); + Assert.assertEquals(29, expr.evaluate(),0.001f); + } + { + //1+((2+3)*4)-5 + PrefixExpr expr = new PrefixExpr("- + 1 * + 2 3 4 5"); + Assert.assertEquals(16, expr.evaluate(),0.001f); + } + + + } + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/Token.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/Token.java new file mode 100644 index 0000000000..8579743fe9 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/Token.java @@ -0,0 +1,50 @@ +package com.coding.basic.stack.expr; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +class Token { + public static final List OPERATORS = Arrays.asList("+", "-", "*", "/"); + private static final Map priorities = new HashMap<>(); + static { + priorities.put("+", 1); + priorities.put("-", 1); + priorities.put("*", 2); + priorities.put("/", 2); + } + static final int OPERATOR = 1; + static final int NUMBER = 2; + String value; + int type; + public Token(int type, String value){ + this.type = type; + this.value = value; + } + + public boolean isNumber() { + return type == NUMBER; + } + + public boolean isOperator() { + return type == OPERATOR; + } + + public int getIntValue() { + return Integer.valueOf(value).intValue(); + } + public String toString(){ + return value; + } + + public boolean hasHigherPriority(Token t){ + if(!this.isOperator() && !t.isOperator()){ + throw new RuntimeException("numbers can't compare priority"); + } + return priorities.get(this.value) - priorities.get(t.value) > 0; + } + + + +} \ No newline at end of file diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/TokenParser.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/TokenParser.java new file mode 100644 index 0000000000..d3b0f167e1 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/TokenParser.java @@ -0,0 +1,57 @@ +package com.coding.basic.stack.expr; + +import java.util.ArrayList; +import java.util.List; + +public class TokenParser { + + + public List parse(String expr) { + List tokens = new ArrayList<>(); + + int i = 0; + + while (i < expr.length()) { + + char c = expr.charAt(i); + + if (isOperator(c)) { + + Token t = new Token(Token.OPERATOR, String.valueOf(c)); + tokens.add(t); + i++; + + } else if (Character.isDigit(c)) { + + int nextOperatorIndex = indexOfNextOperator(i, expr); + String value = expr.substring(i, nextOperatorIndex); + Token t = new Token(Token.NUMBER, value); + tokens.add(t); + i = nextOperatorIndex; + + } else{ + System.out.println("char :["+c+"] is not number or operator,ignore"); + i++; + } + + } + return tokens; + } + + private int indexOfNextOperator(int i, String expr) { + + while (Character.isDigit(expr.charAt(i))) { + i++; + if (i == expr.length()) { + break; + } + } + return i; + + } + + private boolean isOperator(char c) { + String sc = String.valueOf(c); + return Token.OPERATORS.contains(sc); + } +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/TokenParserTest.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/TokenParserTest.java new file mode 100644 index 0000000000..399d3e857e --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/stack/expr/TokenParserTest.java @@ -0,0 +1,41 @@ +package com.coding.basic.stack.expr; + +import static org.junit.Assert.*; + +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class TokenParserTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void test() { + + TokenParser parser = new TokenParser(); + List tokens = parser.parse("300*20+12*5-20/4"); + + Assert.assertEquals(300, tokens.get(0).getIntValue()); + Assert.assertEquals("*", tokens.get(1).toString()); + Assert.assertEquals(20, tokens.get(2).getIntValue()); + Assert.assertEquals("+", tokens.get(3).toString()); + Assert.assertEquals(12, tokens.get(4).getIntValue()); + Assert.assertEquals("*", tokens.get(5).toString()); + Assert.assertEquals(5, tokens.get(6).getIntValue()); + Assert.assertEquals("-", tokens.get(7).toString()); + Assert.assertEquals(20, tokens.get(8).getIntValue()); + Assert.assertEquals("/", tokens.get(9).toString()); + Assert.assertEquals(4, tokens.get(10).getIntValue()); + } + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/tree/BinarySearchTree.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/tree/BinarySearchTree.java new file mode 100644 index 0000000000..284e5b0011 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/tree/BinarySearchTree.java @@ -0,0 +1,189 @@ +package com.coding.basic.tree; + +import java.util.ArrayList; +import java.util.List; + +import com.coding.basic.queue.Queue; + + +public class BinarySearchTree { + + BinaryTreeNode root; + public BinarySearchTree(BinaryTreeNode root){ + this.root = root; + } + public BinaryTreeNode getRoot(){ + return root; + } + public T findMin(){ + if(root == null){ + return null; + } + return findMin(root).data; + } + public T findMax(){ + if(root == null){ + return null; + } + return findMax(root).data; + } + public int height() { + return height(root); + } + public int size() { + return size(root); + } + public void remove(T e){ + remove(e, root); + } + + private BinaryTreeNode remove(T x, BinaryTreeNode t){ + if(t == null){ + return t; + } + int compareResult = x.compareTo(t.data); + + if(compareResult< 0 ){ + t.left = remove(x,t.left); + + } else if(compareResult > 0){ + t.right = remove(x, t.right); + + } else { + if(t.left != null && t.right != null){ + + t.data = findMin(t.right).data; + t.right = remove(t.data,t.right); + + } else{ + t = (t.left != null) ? t.left : t.right; + } + } + return t; + } + + private BinaryTreeNode findMin(BinaryTreeNode p){ + if (p==null){ + return null; + } else if (p.left == null){ + return p; + } else{ + return findMin(p.left); + } + } + private BinaryTreeNode findMax(BinaryTreeNode p){ + if (p==null){ + return null; + }else if (p.right==null){ + return p; + } else{ + return findMax(p.right); + } + } + private int height(BinaryTreeNode t){ + if (t==null){ + return 0; + }else { + int leftChildHeight=height(t.left); + int rightChildHeight=height(t.right); + if(leftChildHeight > rightChildHeight){ + return leftChildHeight+1; + } else{ + return rightChildHeight+1; + } + } + } + private int size(BinaryTreeNode t){ + if (t == null){ + return 0; + } + return size(t.left) + 1 + size(t.right); + + } + + public List levelVisit(){ + List result = new ArrayList(); + if(root == null){ + return result; + } + Queue> queue = new Queue>(); + BinaryTreeNode node = root; + queue.enQueue(node); + while (!queue.isEmpty()) { + node = queue.deQueue(); + result.add(node.data); + if (node.left != null){ + queue.enQueue(node.left); + } + if (node.right != null){ + queue.enQueue(node.right); + } + } + return result; + } + public boolean isValid(){ + return isValid(root); + } + public T getLowestCommonAncestor(T n1, T n2){ + if (root == null){ + return null; + } + return lowestCommonAncestor(root,n1,n2); + + } + public List getNodesBetween(T n1, T n2){ + List elements = new ArrayList<>(); + getNodesBetween(elements,root,n1,n2); + return elements; + } + + public void getNodesBetween(List elements ,BinaryTreeNode node, T n1, T n2){ + + if (node == null) { + return; + } + + if (n1.compareTo(node.data) < 0) { + getNodesBetween(elements,node.left, n1, n2); + } + + if ((n1.compareTo(node.data) <= 0 ) + && (n2.compareTo(node.data) >= 0 )) { + elements.add(node.data); + } + if (n2.compareTo(node.data)>0) { + getNodesBetween(elements,node.right, n1, n2); + } + } + private T lowestCommonAncestor(BinaryTreeNode node,T n1, T n2){ + if(node == null){ + return null; + } + // 如果n1和n2都比 node的值小, LCA在左孩子 + if (node.data.compareTo(n1) > 0 && node.data.compareTo(n2) >0){ + return lowestCommonAncestor(node.left, n1, n2); + } + + // 如果n1和n2都比 node的值小, LCA在右孩子 + if (node.data.compareTo(n1) < 0 && node.data.compareTo(n2) <0) + return lowestCommonAncestor(node.right, n1, n2); + + return node.data; + } + private boolean isValid(BinaryTreeNode t){ + if(t == null){ + return true; + } + if(t.left != null && findMax(t.left).data.compareTo(t.data) >0){ + return false; + } + if(t.right !=null && findMin(t.right).data.compareTo(t.data) <0){ + return false; + } + if(!isValid(t.left) || !isValid(t.right)){ + return false; + } + return true; + } +} + diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/tree/BinarySearchTreeTest.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/tree/BinarySearchTreeTest.java new file mode 100644 index 0000000000..590e60306c --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/tree/BinarySearchTreeTest.java @@ -0,0 +1,108 @@ +package com.coding.basic.tree; + +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class BinarySearchTreeTest { + + BinarySearchTree tree = null; + + @Before + public void setUp() throws Exception { + BinaryTreeNode root = new BinaryTreeNode(6); + root.left = new BinaryTreeNode(2); + root.right = new BinaryTreeNode(8); + root.left.left = new BinaryTreeNode(1); + root.left.right = new BinaryTreeNode(4); + root.left.right.left = new BinaryTreeNode(3); + root.left.right.right = new BinaryTreeNode(5); + tree = new BinarySearchTree(root); + } + + @After + public void tearDown() throws Exception { + tree = null; + } + + @Test + public void testFindMin() { + Assert.assertEquals(1, tree.findMin().intValue()); + + } + + @Test + public void testFindMax() { + Assert.assertEquals(8, tree.findMax().intValue()); + } + + @Test + public void testHeight() { + Assert.assertEquals(4, tree.height()); + } + + @Test + public void testSize() { + Assert.assertEquals(7, tree.size()); + } + + @Test + public void testRemoveLeaf() { + tree.remove(3); + BinaryTreeNode root= tree.getRoot(); + Assert.assertEquals(4, root.left.right.data.intValue()); + + } + @Test + public void testRemoveMiddleNode1() { + tree.remove(4); + BinaryTreeNode root= tree.getRoot(); + Assert.assertEquals(5, root.left.right.data.intValue()); + Assert.assertEquals(3, root.left.right.left.data.intValue()); + } + @Test + public void testRemoveMiddleNode2() { + tree.remove(2); + BinaryTreeNode root= tree.getRoot(); + Assert.assertEquals(3, root.left.data.intValue()); + Assert.assertEquals(4, root.left.right.data.intValue()); + } + + @Test + public void testLevelVisit() { + List values = tree.levelVisit(); + Assert.assertEquals("[6, 2, 8, 1, 4, 3, 5]", values.toString()); + + } + @Test + public void testLCA(){ + Assert.assertEquals(2,tree.getLowestCommonAncestor(1, 5).intValue()); + Assert.assertEquals(2,tree.getLowestCommonAncestor(1, 4).intValue()); + Assert.assertEquals(6,tree.getLowestCommonAncestor(3, 8).intValue()); + } + @Test + public void testIsValid() { + + Assert.assertTrue(tree.isValid()); + + BinaryTreeNode root = new BinaryTreeNode(6); + root.left = new BinaryTreeNode(2); + root.right = new BinaryTreeNode(8); + root.left.left = new BinaryTreeNode(4); + root.left.right = new BinaryTreeNode(1); + root.left.right.left = new BinaryTreeNode(3); + tree = new BinarySearchTree(root); + + Assert.assertFalse(tree.isValid()); + } + @Test + public void testGetNodesBetween(){ + List numbers = this.tree.getNodesBetween(3, 8); + Assert.assertEquals("[3, 4, 5, 6, 8]",numbers.toString()); + } +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/tree/BinaryTreeNode.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/tree/BinaryTreeNode.java new file mode 100644 index 0000000000..3f6f4d2b44 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/tree/BinaryTreeNode.java @@ -0,0 +1,36 @@ +package com.coding.basic.tree; + +public class BinaryTreeNode { + + public T data; + public BinaryTreeNode left; + public BinaryTreeNode right; + + public BinaryTreeNode(T data){ + this.data=data; + } + public T getData() { + return data; + } + public void setData(T data) { + this.data = data; + } + public BinaryTreeNode getLeft() { + return left; + } + public void setLeft(BinaryTreeNode left) { + this.left = left; + } + public BinaryTreeNode getRight() { + return right; + } + public void setRight(BinaryTreeNode right) { + this.right = right; + } + + public BinaryTreeNode insert(Object o){ + return null; + } + + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/tree/BinaryTreeUtil.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/tree/BinaryTreeUtil.java new file mode 100644 index 0000000000..f2a6515fa6 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/tree/BinaryTreeUtil.java @@ -0,0 +1,116 @@ +package com.coding.basic.tree; + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +public class BinaryTreeUtil { + /** + * 用递归的方式实现对二叉树的前序遍历, 需要通过BinaryTreeUtilTest测试 + * + * @param root + * @return + */ + public static List preOrderVisit(BinaryTreeNode root) { + List result = new ArrayList(); + preOrderVisit(root, result); + return result; + } + + /** + * 用递归的方式实现对二叉树的中遍历 + * + * @param root + * @return + */ + public static List inOrderVisit(BinaryTreeNode root) { + List result = new ArrayList(); + inOrderVisit(root, result); + return result; + } + + /** + * 用递归的方式实现对二叉树的后遍历 + * + * @param root + * @return + */ + public static List postOrderVisit(BinaryTreeNode root) { + List result = new ArrayList(); + postOrderVisit(root, result); + return result; + } + + public static List preOrderWithoutRecursion(BinaryTreeNode root) { + + List result = new ArrayList(); + Stack> stack = new Stack>(); + + BinaryTreeNode node = root; + + if(node != null){ + stack.push(node); + } + + while(!stack.isEmpty()){ + node = stack.pop(); + result.add(node.data); + + if(node.right != null){ + stack.push(node.right); + } + + if(node.left != null){ + stack.push(node.right); + } + } + return result; + } + + public static List inOrderWithoutRecursion(BinaryTreeNode root) { + + List result = new ArrayList(); + BinaryTreeNode node = root; + Stack> stack = new Stack>(); + + while (node != null || !stack.isEmpty()) { + + while (node != null) { + stack.push(node); + node = node.left; + } + BinaryTreeNode currentNode = stack.pop(); + result.add(currentNode.data); + node = currentNode.right; + } + return result; + } + + private static void preOrderVisit(BinaryTreeNode node, List result) { + if (node == null) { + return; + } + result.add(node.getData()); + preOrderVisit(node.getLeft(), result); + preOrderVisit(node.getRight(), result); + } + + private static void inOrderVisit(BinaryTreeNode node, List result) { + if (node == null) { + return; + } + inOrderVisit(node.getLeft(), result); + result.add(node.getData()); + inOrderVisit(node.getRight(), result); + } + + private static void postOrderVisit(BinaryTreeNode node, List result) { + if (node == null) { + return; + } + postOrderVisit(node.getLeft(), result); + postOrderVisit(node.getRight(), result); + result.add(node.getData()); + } + +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/tree/BinaryTreeUtilTest.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/tree/BinaryTreeUtilTest.java new file mode 100644 index 0000000000..41857e137d --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/tree/BinaryTreeUtilTest.java @@ -0,0 +1,75 @@ +package com.coding.basic.tree; + +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class BinaryTreeUtilTest { + + BinaryTreeNode root = null; + @Before + public void setUp() throws Exception { + root = new BinaryTreeNode(1); + root.setLeft(new BinaryTreeNode(2)); + root.setRight(new BinaryTreeNode(5)); + root.getLeft().setLeft(new BinaryTreeNode(3)); + root.getLeft().setRight(new BinaryTreeNode(4)); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testPreOrderVisit() { + + List result = BinaryTreeUtil.preOrderVisit(root); + Assert.assertEquals("[1, 2, 3, 4, 5]", result.toString()); + + + } + @Test + public void testInOrderVisit() { + + + List result = BinaryTreeUtil.inOrderVisit(root); + Assert.assertEquals("[3, 2, 4, 1, 5]", result.toString()); + + } + + @Test + public void testPostOrderVisit() { + + + List result = BinaryTreeUtil.postOrderVisit(root); + Assert.assertEquals("[3, 4, 2, 5, 1]", result.toString()); + + } + + + @Test + public void testInOrderVisitWithoutRecursion() { + BinaryTreeNode node = root.getLeft().getRight(); + node.setLeft(new BinaryTreeNode(6)); + node.setRight(new BinaryTreeNode(7)); + + List result = BinaryTreeUtil.inOrderWithoutRecursion(root); + Assert.assertEquals("[3, 2, 6, 4, 7, 1, 5]", result.toString()); + + } + @Test + public void testPreOrderVisitWithoutRecursion() { + BinaryTreeNode node = root.getLeft().getRight(); + node.setLeft(new BinaryTreeNode(6)); + node.setRight(new BinaryTreeNode(7)); + + List result = BinaryTreeUtil.preOrderWithoutRecursion(root); + Assert.assertEquals("[1, 2, 3, 4, 6, 7, 5]", result.toString()); + + } +} diff --git a/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/tree/FileList.java b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/tree/FileList.java new file mode 100644 index 0000000000..85fb8ab2a4 --- /dev/null +++ b/students/1377699408/data-structure/answer/src/main/java/com/coding/basic/tree/FileList.java @@ -0,0 +1,34 @@ +package com.coding.basic.tree; + +import java.io.File; + +public class FileList { + public void list(File f) { + list(f, 0); + } + + public void list(File f, int depth) { + printName(f, depth); + if (f.isDirectory()) { + File[] files = f.listFiles(); + for (File i : files) + list(i, depth + 1); + } + } + + void printName(File f, int depth) { + String name = f.getName(); + for (int i = 0; i < depth; i++) + System.out.print("+"); + if (f.isDirectory()) + System.out.println("Dir: " + name); + else + System.out.println(f.getName() + " " + f.length()); + } + + public static void main(String args[]) { + FileList L = new FileList(); + File f = new File("C:\\coderising\\tmp"); + L.list(f); + } +} diff --git a/students/1377699408/data-structure/assignment/pom.xml b/students/1377699408/data-structure/assignment/pom.xml new file mode 100644 index 0000000000..5024466d17 --- /dev/null +++ b/students/1377699408/data-structure/assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ds-assignment + 0.0.1-SNAPSHOT + jar + + ds-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/DownloadThread.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/DownloadThread.java new file mode 100644 index 0000000000..900a3ad358 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/DownloadThread.java @@ -0,0 +1,20 @@ +package com.coderising.download; + +import com.coderising.download.api.Connection; + +public class DownloadThread extends Thread{ + + Connection conn; + int startPos; + int endPos; + + public DownloadThread( Connection conn, int startPos, int endPos){ + + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + } + public void run(){ + + } +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/FileDownloader.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/FileDownloader.java new file mode 100644 index 0000000000..c3c8a3f27d --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/FileDownloader.java @@ -0,0 +1,73 @@ +package com.coderising.download; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionException; +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; + + +public class FileDownloader { + + String url; + + DownloadListener listener; + + ConnectionManager cm; + + + public FileDownloader(String _url) { + this.url = _url; + + } + + public void execute(){ + // 在这里实现你的代码, 注意: 需要用多线程实现下载 + // 这个类依赖于其他几个接口, 你需要写这几个接口的实现代码 + // (1) ConnectionManager , 可以打开一个连接,通过Connection可以读取其中的一段(用startPos, endPos来指定) + // (2) DownloadListener, 由于是多线程下载, 调用这个类的客户端不知道什么时候结束,所以你需要实现当所有 + // 线程都执行完以后, 调用listener的notifiedFinished方法, 这样客户端就能收到通知。 + // 具体的实现思路: + // 1. 需要调用ConnectionManager的open方法打开连接, 然后通过Connection.getContentLength方法获得文件的长度 + // 2. 至少启动3个线程下载, 注意每个线程需要先调用ConnectionManager的open方法 + // 然后调用read方法, read方法中有读取文件的开始位置和结束位置的参数, 返回值是byte[]数组 + // 3. 把byte数组写入到文件中 + // 4. 所有的线程都下载完成以后, 需要调用listener的notifiedFinished方法 + + // 下面的代码是示例代码, 也就是说只有一个线程, 你需要改造成多线程的。 + Connection conn = null; + try { + + conn = cm.open(this.url); + + int length = conn.getContentLength(); + + new DownloadThread(conn,0,length-1).start(); + + } catch (ConnectionException e) { + e.printStackTrace(); + }finally{ + if(conn != null){ + conn.close(); + } + } + + + + + } + + public void setListener(DownloadListener listener) { + this.listener = listener; + } + + + + public void setConnectionManager(ConnectionManager ucm){ + this.cm = ucm; + } + + public DownloadListener getListener(){ + return this.listener; + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/FileDownloaderTest.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/FileDownloaderTest.java new file mode 100644 index 0000000000..4ff7f46ae0 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/FileDownloaderTest.java @@ -0,0 +1,59 @@ +package com.coderising.download; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; +import com.coderising.download.impl.ConnectionManagerImpl; + +public class FileDownloaderTest { + boolean downloadFinished = false; + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testDownload() { + + String url = "http://localhost:8080/test.jpg"; + + FileDownloader downloader = new FileDownloader(url); + + + ConnectionManager cm = new ConnectionManagerImpl(); + downloader.setConnectionManager(cm); + + downloader.setListener(new DownloadListener() { + @Override + public void notifyFinished() { + downloadFinished = true; + } + + }); + + + downloader.execute(); + + // 等待多线程下载程序执行完毕 + while (!downloadFinished) { + try { + System.out.println("还没有下载完成,休眠五秒"); + //休眠5秒 + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + System.out.println("下载完成!"); + + + + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/api/Connection.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/api/Connection.java new file mode 100644 index 0000000000..0957eaf7f4 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/api/Connection.java @@ -0,0 +1,23 @@ +package com.coderising.download.api; + +import java.io.IOException; + +public interface Connection { + /** + * 给定开始和结束位置, 读取数据, 返回值是字节数组 + * @param startPos 开始位置, 从0开始 + * @param endPos 结束位置 + * @return + */ + public byte[] read(int startPos,int endPos) throws IOException; + /** + * 得到数据内容的长度 + * @return + */ + public int getContentLength(); + + /** + * 关闭连接 + */ + public void close(); +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/api/ConnectionException.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/api/ConnectionException.java new file mode 100644 index 0000000000..1551a80b3d --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/api/ConnectionException.java @@ -0,0 +1,5 @@ +package com.coderising.download.api; + +public class ConnectionException extends Exception { + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/api/ConnectionManager.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/api/ConnectionManager.java new file mode 100644 index 0000000000..ce045393b1 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/api/ConnectionManager.java @@ -0,0 +1,10 @@ +package com.coderising.download.api; + +public interface ConnectionManager { + /** + * 给定一个url , 打开一个连接 + * @param url + * @return + */ + public Connection open(String url) throws ConnectionException; +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/api/DownloadListener.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/api/DownloadListener.java new file mode 100644 index 0000000000..bf9807b307 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/api/DownloadListener.java @@ -0,0 +1,5 @@ +package com.coderising.download.api; + +public interface DownloadListener { + public void notifyFinished(); +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/impl/ConnectionImpl.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..36a9d2ce15 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/impl/ConnectionImpl.java @@ -0,0 +1,27 @@ +package com.coderising.download.impl; + +import java.io.IOException; + +import com.coderising.download.api.Connection; + +public class ConnectionImpl implements Connection{ + + @Override + public byte[] read(int startPos, int endPos) throws IOException { + + return null; + } + + @Override + public int getContentLength() { + + return 0; + } + + @Override + public void close() { + + + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/impl/ConnectionManagerImpl.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..172371dd55 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,15 @@ +package com.coderising.download.impl; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionException; +import com.coderising.download.api.ConnectionManager; + +public class ConnectionManagerImpl implements ConnectionManager { + + @Override + public Connection open(String url) throws ConnectionException { + + return null; + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/litestruts/LoginAction.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/litestruts/LoginAction.java new file mode 100644 index 0000000000..dcdbe226ed --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/litestruts/LoginAction.java @@ -0,0 +1,39 @@ +package com.coderising.litestruts; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * @author liuxin + * + */ +public class LoginAction{ + private String name ; + private String password; + private String message; + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String execute(){ + if("test".equals(name) && "1234".equals(password)){ + this.message = "login successful"; + return "success"; + } + this.message = "login failed,please check your user/pwd"; + return "fail"; + } + + public void setName(String name){ + this.name = name; + } + public void setPassword(String password){ + this.password = password; + } + public String getMessage(){ + return this.message; + } +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/litestruts/Struts.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/litestruts/Struts.java new file mode 100644 index 0000000000..85e2e22de3 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/litestruts/Struts.java @@ -0,0 +1,34 @@ +package com.coderising.litestruts; + +import java.util.Map; + + + +public class Struts { + + public static View runAction(String actionName, Map parameters) { + + /* + + 0. 读取配置文件struts.xml + + 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + ("name"="test" , "password"="1234") , + 那就应该调用 setName和setPassword方法 + + 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + + 3. 通过反射找到对象的所有getter方法(例如 getMessage), + 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + 放到View对象的parameters + + 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + 放到View对象的jsp字段中。 + + */ + + return null; + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/litestruts/StrutsTest.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/litestruts/StrutsTest.java new file mode 100644 index 0000000000..b8c81faf3c --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/litestruts/StrutsTest.java @@ -0,0 +1,43 @@ +package com.coderising.litestruts; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + + + + + +public class StrutsTest { + + @Test + public void testLoginActionSuccess() { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/litestruts/View.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/litestruts/View.java new file mode 100644 index 0000000000..07df2a5dab --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/litestruts/View.java @@ -0,0 +1,23 @@ +package com.coderising.litestruts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/litestruts/struts.xml b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/litestruts/struts.xml new file mode 100644 index 0000000000..e5d9aebba8 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/Course.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/Course.java new file mode 100644 index 0000000000..436d092f58 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/Course.java @@ -0,0 +1,24 @@ +package com.coderising.ood.course.bad; + +import java.util.List; + +public class Course { + private String id; + private String desc; + private int duration ; + + List prerequisites; + + public List getPrerequisites() { + return prerequisites; + } + + + public boolean equals(Object o){ + if(o == null || !(o instanceof Course)){ + return false; + } + Course c = (Course)o; + return (c != null) && c.id.equals(id); + } +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/CourseOffering.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/CourseOffering.java new file mode 100644 index 0000000000..ab8c764584 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/CourseOffering.java @@ -0,0 +1,26 @@ +package com.coderising.ood.course.bad; + +import java.util.ArrayList; +import java.util.List; + + +public class CourseOffering { + private Course course; + private String location; + private String teacher; + private int maxStudents; + + List students = new ArrayList(); + + public int getMaxStudents() { + return maxStudents; + } + + public List getStudents() { + return students; + } + + public Course getCourse() { + return course; + } +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/CourseService.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/CourseService.java new file mode 100644 index 0000000000..8c34bad0c3 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/CourseService.java @@ -0,0 +1,16 @@ +package com.coderising.ood.course.bad; + + + +public class CourseService { + + public void chooseCourse(Student student, CourseOffering sc){ + //如果学生上过该科目的先修科目,并且该课程还未满, 则学生可以加入该课程 + if(student.getCoursesAlreadyTaken().containsAll( + sc.getCourse().getPrerequisites()) + && sc.getMaxStudents() > sc.getStudents().size()){ + sc.getStudents().add(student); + } + + } +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/Student.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/Student.java new file mode 100644 index 0000000000..a651923ef5 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/Student.java @@ -0,0 +1,14 @@ +package com.coderising.ood.course.bad; + +import java.util.ArrayList; +import java.util.List; + +public class Student { + private String id; + private String name; + private List coursesAlreadyTaken = new ArrayList(); + + public List getCoursesAlreadyTaken() { + return coursesAlreadyTaken; + } +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/good/Course.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/good/Course.java new file mode 100644 index 0000000000..aefc9692bb --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/good/Course.java @@ -0,0 +1,18 @@ +package com.coderising.ood.course.good; + +import java.util.List; + +public class Course { + private String id; + private String desc; + private int duration ; + + List prerequisites; + + public List getPrerequisites() { + return prerequisites; + } + +} + + diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/good/CourseOffering.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/good/CourseOffering.java new file mode 100644 index 0000000000..8660ec8109 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/good/CourseOffering.java @@ -0,0 +1,34 @@ +package com.coderising.ood.course.good; + +import java.util.ArrayList; +import java.util.List; + +public class CourseOffering { + private Course course; + private String location; + private String teacher; + private int maxStudents; + + List students = new ArrayList(); + + public List getStudents() { + return students; + } + public int getMaxStudents() { + return maxStudents; + } + public Course getCourse() { + return course; + } + + + // 第二步: 把主要逻辑移动到CourseOffering 中 + public void addStudent(Student student){ + + if(student.canAttend(course) + && this.maxStudents > students.size()){ + students.add(student); + } + } + // 第三步: 重构CourseService +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/good/CourseService.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/good/CourseService.java new file mode 100644 index 0000000000..22ba4a5450 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/good/CourseService.java @@ -0,0 +1,14 @@ +package com.coderising.ood.course.good; + + + +public class CourseService { + + public void chooseCourse(Student student, CourseOffering sc){ + //第一步:重构: canAttend , 但是还有问题 + if(student.canAttend(sc.getCourse()) + && sc.getMaxStudents() > sc.getStudents().size()){ + sc.getStudents().add(student); + } + } +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/good/Student.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/good/Student.java new file mode 100644 index 0000000000..2c7e128b2a --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/course/good/Student.java @@ -0,0 +1,21 @@ +package com.coderising.ood.course.good; + +import java.util.ArrayList; +import java.util.List; + +public class Student { + private String id; + private String name; + private List coursesAlreadyTaken = new ArrayList(); + + public List getCoursesAlreadyTaken() { + return coursesAlreadyTaken; + } + + public boolean canAttend(Course course){ + return this.coursesAlreadyTaken.containsAll( + course.getPrerequisites()); + } +} + + diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java new file mode 100644 index 0000000000..b6cf28c096 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return null; + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/ocp/Logger.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/ocp/Logger.java new file mode 100644 index 0000000000..0357c4d912 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/ocp/Logger.java @@ -0,0 +1,38 @@ +package com.coderising.ood.ocp; + +public class Logger { + + public final int RAW_LOG = 1; + public final int RAW_LOG_WITH_DATE = 2; + public final int EMAIL_LOG = 1; + public final int SMS_LOG = 2; + public final int PRINT_LOG = 3; + + int type = 0; + int method = 0; + + public Logger(int logType, int logMethod){ + this.type = logType; + this.method = logMethod; + } + public void log(String msg){ + + String logMsg = msg; + + if(this.type == RAW_LOG){ + logMsg = msg; + } else if(this.type == RAW_LOG_WITH_DATE){ + String txtDate = DateUtil.getCurrentDateAsString(); + logMsg = txtDate + ": " + msg; + } + + if(this.method == EMAIL_LOG){ + MailUtil.send(logMsg); + } else if(this.method == SMS_LOG){ + SMSUtil.send(logMsg); + } else if(this.method == PRINT_LOG){ + System.out.println(logMsg); + } + } +} + diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java new file mode 100644 index 0000000000..ec54b839c5 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class MailUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java new file mode 100644 index 0000000000..13cf802418 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class SMSUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..9f9e749af7 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..781587a846 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,199 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery = null; + + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected String productID = null; + protected String productDesc = null; + + private static Configuration config; + + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + + + config = new Configuration(); + + setSMTPHost(); + setAltSMTPHost(); + + + setFromAddress(); + + + setLoadQuery(); + + sendEMails(mailDebug, loadMailingList()); + + + } + + + + + protected void setProductID(String productID) + { + this.productID = productID; + + } + + protected String getproductID() + { + return productID; + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected void setSMTPHost() + { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() + { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + protected void setFromAddress() + { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setMessage(HashMap userInfo) throws IOException + { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + + + + } + + + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + private void setProductDesc(String desc) { + this.productDesc = desc; + } + + + protected void configureEMail(HashMap userInfo) throws IOException + { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try + { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } + + else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..a98917f829 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo R15 +P4955 Vivo X20 \ No newline at end of file diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/Iterator.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/Iterator.java new file mode 100644 index 0000000000..06ef6311b2 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/Iterator.java @@ -0,0 +1,7 @@ +package com.coding.basic; + +public interface Iterator { + public boolean hasNext(); + public Object next(); + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/List.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/List.java new file mode 100644 index 0000000000..10d13b5832 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/List.java @@ -0,0 +1,9 @@ +package com.coding.basic; + +public interface List { + public void add(Object o); + public void add(int index, Object o); + public Object get(int index); + public Object remove(int index); + public int size(); +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/array/ArrayList.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/array/ArrayList.java new file mode 100644 index 0000000000..4576c016af --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/array/ArrayList.java @@ -0,0 +1,35 @@ +package com.coding.basic.array; + +import com.coding.basic.Iterator; +import com.coding.basic.List; + +public class ArrayList implements List { + + private int size = 0; + + private Object[] elementData = new Object[100]; + + public void add(Object o){ + + } + public void add(int index, Object o){ + + } + + public Object get(int index){ + return null; + } + + public Object remove(int index){ + return null; + } + + public int size(){ + return -1; + } + + public Iterator iterator(){ + return null; + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/array/ArrayUtil.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/array/ArrayUtil.java new file mode 100644 index 0000000000..45740e6d57 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/array/ArrayUtil.java @@ -0,0 +1,96 @@ +package com.coding.basic.array; + +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 + 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * @param origin + * @return + */ + public void reverseArray(int[] origin){ + + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: + * {1,3,4,5,6,6,5,4,7,6,7,5} + * @param oldArray + * @return + */ + + public int[] removeZero(int[] oldArray){ + return null; + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 + * 例如 a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * @param array1 + * @param array2 + * @return + */ + + public int[] merge(int[] array1, int[] array2){ + return null; + } + /** + * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size + * 注意,老数组的元素在新数组中需要保持 + * 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 + * [2,3,6,0,0,0] + * @param oldArray + * @param size + * @return + */ + public int[] grow(int [] oldArray, int size){ + return null; + } + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 + * 例如, max = 15 , 则返回的数组应该为 [1,1,2,3,5,8,13] + * max = 1, 则返回空数组 [] + * @param max + * @return + */ + public int[] fibonacci(int max){ + return null; + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public int[] getPrimes(int max){ + return null; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public int[] getPerfectNumbers(int max){ + return null; + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * @param array + * @param s + * @return + */ + public String join(int[] array, String seperator){ + return null; + } + + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/linklist/LRUPageFrame.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/linklist/LRUPageFrame.java new file mode 100644 index 0000000000..994a241a3d --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/linklist/LRUPageFrame.java @@ -0,0 +1,57 @@ +package com.coding.basic.linklist; + + +public class LRUPageFrame { + + private static class Node { + + Node prev; + Node next; + int pageNum; + + Node() { + } + } + + private int capacity; + + private int currentSize; + private Node first;// 链表头 + private Node last;// 链表尾 + + + public LRUPageFrame(int capacity) { + this.currentSize = 0; + this.capacity = capacity; + + } + + /** + * 获取缓存中对象 + * + * @param key + * @return + */ + public void access(int pageNum) { + + + } + + + public String toString(){ + StringBuilder buffer = new StringBuilder(); + Node node = first; + while(node != null){ + buffer.append(node.pageNum); + + node = node.next; + if(node != null){ + buffer.append(","); + } + } + return buffer.toString(); + } + + + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/linklist/LRUPageFrameTest.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/linklist/LRUPageFrameTest.java new file mode 100644 index 0000000000..7fd72fc2b4 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/linklist/LRUPageFrameTest.java @@ -0,0 +1,34 @@ +package com.coding.basic.linklist; + +import org.junit.Assert; + +import org.junit.Test; + + +public class LRUPageFrameTest { + + @Test + public void testAccess() { + LRUPageFrame frame = new LRUPageFrame(3); + frame.access(7); + frame.access(0); + frame.access(1); + Assert.assertEquals("1,0,7", frame.toString()); + frame.access(2); + Assert.assertEquals("2,1,0", frame.toString()); + frame.access(0); + Assert.assertEquals("0,2,1", frame.toString()); + frame.access(0); + Assert.assertEquals("0,2,1", frame.toString()); + frame.access(3); + Assert.assertEquals("3,0,2", frame.toString()); + frame.access(0); + Assert.assertEquals("0,3,2", frame.toString()); + frame.access(4); + Assert.assertEquals("4,0,3", frame.toString()); + frame.access(5); + Assert.assertEquals("5,4,0", frame.toString()); + + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/linklist/LinkedList.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/linklist/LinkedList.java new file mode 100644 index 0000000000..f4c7556a2e --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/linklist/LinkedList.java @@ -0,0 +1,125 @@ +package com.coding.basic.linklist; + +import com.coding.basic.Iterator; +import com.coding.basic.List; + +public class LinkedList implements List { + + private Node head; + + public void add(Object o){ + + } + public void add(int index , Object o){ + + } + public Object get(int index){ + return null; + } + public Object remove(int index){ + return null; + } + + public int size(){ + return -1; + } + + public void addFirst(Object o){ + + } + public void addLast(Object o){ + + } + public Object removeFirst(){ + return null; + } + public Object removeLast(){ + return null; + } + public Iterator iterator(){ + return null; + } + + + private static class Node{ + Object data; + Node next; + + } + + /** + * 把该链表逆置 + * 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + + */ + public void removeFirstHalf(){ + + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * @param i + * @param length + */ + public void remove(int i, int length){ + + } + /** + * 假定当前链表和listB均包含已升序排列的整数 + * 从当前链表中取出那些listB所指定的元素 + * 例如当前链表 = 11->101->201->301->401->501->601->701 + * listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + * @param list + */ + public int[] getElements(LinkedList list){ + return null; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 从当前链表中中删除在listB中出现的元素 + + * @param list + */ + + public void subtract(LinkedList list){ + + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues(){ + + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * @param min + * @param max + */ + public void removeRange(int min, int max){ + + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * @param list + */ + public LinkedList intersection( LinkedList list){ + return null; + } +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/queue/CircleQueue.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/queue/CircleQueue.java new file mode 100644 index 0000000000..2e0550c67e --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/queue/CircleQueue.java @@ -0,0 +1,39 @@ +package com.coding.basic.queue; + +/** + * 用数组实现循环队列 + * @author liuxin + * + * @param + */ +public class CircleQueue { + + private final static int DEFAULT_SIZE = 10; + + //用数组来保存循环队列的元素 + private Object[] elementData = new Object[DEFAULT_SIZE] ; + + //队头 + private int front = 0; + //队尾 + private int rear = 0; + + public boolean isEmpty() { + return false; + + } + + public int size() { + return -1; + } + + + + public void enQueue(E data) { + + } + + public E deQueue() { + return null; + } +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/queue/Josephus.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/queue/Josephus.java new file mode 100644 index 0000000000..6a3ea639b9 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/queue/Josephus.java @@ -0,0 +1,18 @@ +package com.coding.basic.queue; + +import java.util.List; + +/** + * 用Queue来实现Josephus问题 + * 在这个古老的问题当中, N个深陷绝境的人一致同意用这种方式减少生存人数: N个人围成一圈(位置记为0到N-1), 并且从第一个人报数, 报到M的人会被杀死, 直到最后一个人留下来 + * 该方法返回一个List, 包含了被杀死人的次序 + * @author liuxin + * + */ +public class Josephus { + + public static List execute(int n, int m){ + return null; + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/queue/JosephusTest.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/queue/JosephusTest.java new file mode 100644 index 0000000000..7d90318b51 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/queue/JosephusTest.java @@ -0,0 +1,27 @@ +package com.coding.basic.queue; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class JosephusTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testExecute() { + + Assert.assertEquals("[1, 3, 5, 0, 4, 2, 6]", Josephus.execute(7, 2).toString()); + + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/queue/Queue.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/queue/Queue.java new file mode 100644 index 0000000000..c4c4b7325e --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/queue/Queue.java @@ -0,0 +1,61 @@ +package com.coding.basic.queue; + +import java.util.NoSuchElementException; + +public class Queue { + private Node first; + private Node last; + private int size; + + + private static class Node { + private E item; + private Node next; + } + + + public Queue() { + first = null; + last = null; + size = 0; + } + + + public boolean isEmpty() { + return first == null; + } + + public int size() { + return size; + } + + + + public void enQueue(E data) { + Node oldlast = last; + last = new Node(); + last.item = data; + last.next = null; + if (isEmpty()) { + first = last; + } + else{ + oldlast.next = last; + } + size++; + } + + public E deQueue() { + if (isEmpty()) { + throw new NoSuchElementException("Queue underflow"); + } + E item = first.item; + first = first.next; + size--; + if (isEmpty()) { + last = null; + } + return item; + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/queue/QueueWithTwoStacks.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/queue/QueueWithTwoStacks.java new file mode 100644 index 0000000000..cef19a8b59 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/queue/QueueWithTwoStacks.java @@ -0,0 +1,47 @@ +package com.coding.basic.queue; + +import java.util.Stack; + +/** + * 用两个栈来实现一个队列 + * @author liuxin + * + * @param + */ +public class QueueWithTwoStacks { + private Stack stack1; + private Stack stack2; + + + public QueueWithTwoStacks() { + stack1 = new Stack(); + stack2 = new Stack(); + } + + + + + public boolean isEmpty() { + return false; + } + + + + public int size() { + return -1; + } + + + + public void enQueue(E item) { + + } + + public E deQueue() { + return null; + } + + + + } + diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/QuickMinStack.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/QuickMinStack.java new file mode 100644 index 0000000000..f391d92b8f --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/QuickMinStack.java @@ -0,0 +1,19 @@ +package com.coding.basic.stack; + +/** + * 设计一个栈,支持栈的push和pop操作,以及第三种操作findMin, 它返回改数据结构中的最小元素 + * finMin操作最坏的情形下时间复杂度应该是O(1) , 简单来讲,操作一次就可以得到最小值 + * @author liuxin + * + */ +public class QuickMinStack { + public void push(int data){ + + } + public int pop(){ + return -1; + } + public int findMin(){ + return -1; + } +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/Stack.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/Stack.java new file mode 100644 index 0000000000..fedb243604 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/Stack.java @@ -0,0 +1,24 @@ +package com.coding.basic.stack; + +import com.coding.basic.array.ArrayList; + +public class Stack { + private ArrayList elementData = new ArrayList(); + + public void push(Object o){ + } + + public Object pop(){ + return null; + } + + public Object peek(){ + return null; + } + public boolean isEmpty(){ + return false; + } + public int size(){ + return -1; + } +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/StackUtil.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/StackUtil.java new file mode 100644 index 0000000000..b0ec38161d --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/StackUtil.java @@ -0,0 +1,48 @@ +package com.coding.basic.stack; +import java.util.Stack; +public class StackUtil { + + + + /** + * 假设栈中的元素是Integer, 从栈顶到栈底是 : 5,4,3,2,1 调用该方法后, 元素次序变为: 1,2,3,4,5 + * 注意:只能使用Stack的基本操作,即push,pop,peek,isEmpty, 可以使用另外一个栈来辅助 + */ + public static void reverse(Stack s) { + + + + } + + /** + * 删除栈中的某个元素 注意:只能使用Stack的基本操作,即push,pop,peek,isEmpty, 可以使用另外一个栈来辅助 + * + * @param o + */ + public static void remove(Stack s,Object o) { + + } + + /** + * 从栈顶取得len个元素, 原来的栈中元素保持不变 + * 注意:只能使用Stack的基本操作,即push,pop,peek,isEmpty, 可以使用另外一个栈来辅助 + * @param len + * @return + */ + public static Object[] getTop(Stack s,int len) { + return null; + } + /** + * 字符串s 可能包含这些字符: ( ) [ ] { }, a,b,c... x,yz + * 使用堆栈检查字符串s中的括号是不是成对出现的。 + * 例如s = "([e{d}f])" , 则该字符串中的括号是成对出现, 该方法返回true + * 如果 s = "([b{x]y})", 则该字符串中的括号不是成对出现的, 该方法返回false; + * @param s + * @return + */ + public static boolean isValidPairs(String s){ + return false; + } + + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/StackUtilTest.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/StackUtilTest.java new file mode 100644 index 0000000000..76f2cb7668 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/StackUtilTest.java @@ -0,0 +1,65 @@ +package com.coding.basic.stack; + +import java.util.Stack; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +public class StackUtilTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void testReverse() { + Stack s = new Stack(); + s.push(1); + s.push(2); + s.push(3); + s.push(4); + s.push(5); + Assert.assertEquals("[1, 2, 3, 4, 5]", s.toString()); + StackUtil.reverse(s); + Assert.assertEquals("[5, 4, 3, 2, 1]", s.toString()); + } + + @Test + public void testRemove() { + Stack s = new Stack(); + s.push(1); + s.push(2); + s.push(3); + StackUtil.remove(s, 2); + Assert.assertEquals("[1, 3]", s.toString()); + } + + @Test + public void testGetTop() { + Stack s = new Stack(); + s.push(1); + s.push(2); + s.push(3); + s.push(4); + s.push(5); + { + Object[] values = StackUtil.getTop(s, 3); + Assert.assertEquals(5, values[0]); + Assert.assertEquals(4, values[1]); + Assert.assertEquals(3, values[2]); + } + } + + @Test + public void testIsValidPairs() { + Assert.assertTrue(StackUtil.isValidPairs("([e{d}f])")); + Assert.assertFalse(StackUtil.isValidPairs("([b{x]y})")); + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/StackWithTwoQueues.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/StackWithTwoQueues.java new file mode 100644 index 0000000000..d0ab4387d2 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/StackWithTwoQueues.java @@ -0,0 +1,16 @@ +package com.coding.basic.stack; + + +public class StackWithTwoQueues { + + + public void push(int data) { + + } + + public int pop() { + return -1; + } + + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/TwoStackInOneArray.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/TwoStackInOneArray.java new file mode 100644 index 0000000000..e86d056a24 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/TwoStackInOneArray.java @@ -0,0 +1,57 @@ +package com.coding.basic.stack; + +/** + * 用一个数组实现两个栈 + * 将数组的起始位置看作是第一个栈的栈底,将数组的尾部看作第二个栈的栈底,压栈时,栈顶指针分别向中间移动,直到两栈顶指针相遇,则扩容。 + * @author liuxin + * + */ +public class TwoStackInOneArray { + Object[] data = new Object[10]; + + /** + * 向第一个栈中压入元素 + * @param o + */ + public void push1(Object o){ + + } + /** + * 从第一个栈中弹出元素 + * @return + */ + public Object pop1(){ + return null; + } + + /** + * 获取第一个栈的栈顶元素 + * @return + */ + + public Object peek1(){ + return null; + } + /* + * 向第二个栈压入元素 + */ + public void push2(Object o){ + + } + /** + * 从第二个栈弹出元素 + * @return + */ + public Object pop2(){ + return null; + } + /** + * 获取第二个栈的栈顶元素 + * @return + */ + + public Object peek2(){ + return null; + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/InfixExpr.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/InfixExpr.java new file mode 100644 index 0000000000..ef85ff007f --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/InfixExpr.java @@ -0,0 +1,15 @@ +package com.coding.basic.stack.expr; + +public class InfixExpr { + String expr = null; + + public InfixExpr(String expr) { + this.expr = expr; + } + + public float evaluate() { + return 0.0f; + } + + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/InfixExprTest.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/InfixExprTest.java new file mode 100644 index 0000000000..20e34e8852 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/InfixExprTest.java @@ -0,0 +1,52 @@ +package com.coding.basic.stack.expr; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + +public class InfixExprTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testEvaluate() { + //InfixExpr expr = new InfixExpr("300*20+12*5-20/4"); + { + InfixExpr expr = new InfixExpr("2+3*4+5"); + Assert.assertEquals(19.0, expr.evaluate(), 0.001f); + } + { + InfixExpr expr = new InfixExpr("3*20+12*5-40/2"); + Assert.assertEquals(100.0, expr.evaluate(), 0.001f); + } + + { + InfixExpr expr = new InfixExpr("3*20/2"); + Assert.assertEquals(30, expr.evaluate(), 0.001f); + } + + { + InfixExpr expr = new InfixExpr("20/2*3"); + Assert.assertEquals(30, expr.evaluate(), 0.001f); + } + + { + InfixExpr expr = new InfixExpr("10-30+50"); + Assert.assertEquals(30, expr.evaluate(), 0.001f); + } + { + InfixExpr expr = new InfixExpr("10-2*3+50"); + Assert.assertEquals(54, expr.evaluate(), 0.001f); + } + + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/InfixToPostfix.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/InfixToPostfix.java new file mode 100644 index 0000000000..96a2194a67 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/InfixToPostfix.java @@ -0,0 +1,14 @@ +package com.coding.basic.stack.expr; + +import java.util.List; + +public class InfixToPostfix { + + public static List convert(String expr) { + + return null; + } + + + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PostfixExpr.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PostfixExpr.java new file mode 100644 index 0000000000..dcbb18be4b --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PostfixExpr.java @@ -0,0 +1,18 @@ +package com.coding.basic.stack.expr; + +import java.util.List; +import java.util.Stack; + +public class PostfixExpr { +String expr = null; + + public PostfixExpr(String expr) { + this.expr = expr; + } + + public float evaluate() { + return 0.0f; + } + + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PostfixExprTest.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PostfixExprTest.java new file mode 100644 index 0000000000..c0435a2db5 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PostfixExprTest.java @@ -0,0 +1,41 @@ +package com.coding.basic.stack.expr; + + + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class PostfixExprTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testEvaluate() { + { + PostfixExpr expr = new PostfixExpr("6 5 2 3 + 8 * + 3 + *"); + Assert.assertEquals(288, expr.evaluate(),0.0f); + } + { + //9+(3-1)*3+10/2 + PostfixExpr expr = new PostfixExpr("9 3 1-3*+ 10 2/+"); + Assert.assertEquals(20, expr.evaluate(),0.0f); + } + + { + //10-2*3+50 + PostfixExpr expr = new PostfixExpr("10 2 3 * - 50 +"); + Assert.assertEquals(54, expr.evaluate(),0.0f); + } + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PrefixExpr.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PrefixExpr.java new file mode 100644 index 0000000000..956927e2df --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PrefixExpr.java @@ -0,0 +1,18 @@ +package com.coding.basic.stack.expr; + +import java.util.List; +import java.util.Stack; + +public class PrefixExpr { + String expr = null; + + public PrefixExpr(String expr) { + this.expr = expr; + } + + public float evaluate() { + return 0.0f; + } + + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PrefixExprTest.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PrefixExprTest.java new file mode 100644 index 0000000000..5cec210e75 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PrefixExprTest.java @@ -0,0 +1,45 @@ +package com.coding.basic.stack.expr; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + +public class PrefixExprTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testEvaluate() { + { + // 2*3+4*5 + PrefixExpr expr = new PrefixExpr("+ * 2 3* 4 5"); + Assert.assertEquals(26, expr.evaluate(),0.001f); + } + { + // 4*2 + 6+9*2/3 -8 + PrefixExpr expr = new PrefixExpr("-++6/*2 9 3 * 4 2 8"); + Assert.assertEquals(12, expr.evaluate(),0.001f); + } + { + //(3+4)*5-6 + PrefixExpr expr = new PrefixExpr("- * + 3 4 5 6"); + Assert.assertEquals(29, expr.evaluate(),0.001f); + } + { + //1+((2+3)*4)-5 + PrefixExpr expr = new PrefixExpr("- + 1 * + 2 3 4 5"); + Assert.assertEquals(16, expr.evaluate(),0.001f); + } + + + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/Token.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/Token.java new file mode 100644 index 0000000000..8579743fe9 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/Token.java @@ -0,0 +1,50 @@ +package com.coding.basic.stack.expr; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +class Token { + public static final List OPERATORS = Arrays.asList("+", "-", "*", "/"); + private static final Map priorities = new HashMap<>(); + static { + priorities.put("+", 1); + priorities.put("-", 1); + priorities.put("*", 2); + priorities.put("/", 2); + } + static final int OPERATOR = 1; + static final int NUMBER = 2; + String value; + int type; + public Token(int type, String value){ + this.type = type; + this.value = value; + } + + public boolean isNumber() { + return type == NUMBER; + } + + public boolean isOperator() { + return type == OPERATOR; + } + + public int getIntValue() { + return Integer.valueOf(value).intValue(); + } + public String toString(){ + return value; + } + + public boolean hasHigherPriority(Token t){ + if(!this.isOperator() && !t.isOperator()){ + throw new RuntimeException("numbers can't compare priority"); + } + return priorities.get(this.value) - priorities.get(t.value) > 0; + } + + + +} \ No newline at end of file diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/TokenParser.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/TokenParser.java new file mode 100644 index 0000000000..d3b0f167e1 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/TokenParser.java @@ -0,0 +1,57 @@ +package com.coding.basic.stack.expr; + +import java.util.ArrayList; +import java.util.List; + +public class TokenParser { + + + public List parse(String expr) { + List tokens = new ArrayList<>(); + + int i = 0; + + while (i < expr.length()) { + + char c = expr.charAt(i); + + if (isOperator(c)) { + + Token t = new Token(Token.OPERATOR, String.valueOf(c)); + tokens.add(t); + i++; + + } else if (Character.isDigit(c)) { + + int nextOperatorIndex = indexOfNextOperator(i, expr); + String value = expr.substring(i, nextOperatorIndex); + Token t = new Token(Token.NUMBER, value); + tokens.add(t); + i = nextOperatorIndex; + + } else{ + System.out.println("char :["+c+"] is not number or operator,ignore"); + i++; + } + + } + return tokens; + } + + private int indexOfNextOperator(int i, String expr) { + + while (Character.isDigit(expr.charAt(i))) { + i++; + if (i == expr.length()) { + break; + } + } + return i; + + } + + private boolean isOperator(char c) { + String sc = String.valueOf(c); + return Token.OPERATORS.contains(sc); + } +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/TokenParserTest.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/TokenParserTest.java new file mode 100644 index 0000000000..399d3e857e --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/TokenParserTest.java @@ -0,0 +1,41 @@ +package com.coding.basic.stack.expr; + +import static org.junit.Assert.*; + +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class TokenParserTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void test() { + + TokenParser parser = new TokenParser(); + List tokens = parser.parse("300*20+12*5-20/4"); + + Assert.assertEquals(300, tokens.get(0).getIntValue()); + Assert.assertEquals("*", tokens.get(1).toString()); + Assert.assertEquals(20, tokens.get(2).getIntValue()); + Assert.assertEquals("+", tokens.get(3).toString()); + Assert.assertEquals(12, tokens.get(4).getIntValue()); + Assert.assertEquals("*", tokens.get(5).toString()); + Assert.assertEquals(5, tokens.get(6).getIntValue()); + Assert.assertEquals("-", tokens.get(7).toString()); + Assert.assertEquals(20, tokens.get(8).getIntValue()); + Assert.assertEquals("/", tokens.get(9).toString()); + Assert.assertEquals(4, tokens.get(10).getIntValue()); + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/tree/BinarySearchTree.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/tree/BinarySearchTree.java new file mode 100644 index 0000000000..4536ee7a2b --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/tree/BinarySearchTree.java @@ -0,0 +1,55 @@ +package com.coding.basic.tree; + +import java.util.ArrayList; +import java.util.List; + +import com.coding.basic.queue.Queue; + +public class BinarySearchTree { + + BinaryTreeNode root; + public BinarySearchTree(BinaryTreeNode root){ + this.root = root; + } + public BinaryTreeNode getRoot(){ + return root; + } + public T findMin(){ + return null; + } + public T findMax(){ + return null; + } + public int height() { + return -1; + } + public int size() { + return -1; + } + public void remove(T e){ + + } + public List levelVisit(){ + + return null; + } + public boolean isValid(){ + return false; + } + public T getLowestCommonAncestor(T n1, T n2){ + return null; + + } + /** + * 返回所有满足下列条件的节点的值: n1 <= n <= n2 , n 为 + * 该二叉查找树中的某一节点 + * @param n1 + * @param n2 + * @return + */ + public List getNodesBetween(T n1, T n2){ + return null; + } + +} + diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/tree/BinarySearchTreeTest.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/tree/BinarySearchTreeTest.java new file mode 100644 index 0000000000..4a53dbe2f1 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/tree/BinarySearchTreeTest.java @@ -0,0 +1,109 @@ +package com.coding.basic.tree; + +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class BinarySearchTreeTest { + + BinarySearchTree tree = null; + + @Before + public void setUp() throws Exception { + BinaryTreeNode root = new BinaryTreeNode(6); + root.left = new BinaryTreeNode(2); + root.right = new BinaryTreeNode(8); + root.left.left = new BinaryTreeNode(1); + root.left.right = new BinaryTreeNode(4); + root.left.right.left = new BinaryTreeNode(3); + root.left.right.right = new BinaryTreeNode(5); + tree = new BinarySearchTree(root); + } + + @After + public void tearDown() throws Exception { + tree = null; + } + + @Test + public void testFindMin() { + Assert.assertEquals(1, tree.findMin().intValue()); + + } + + @Test + public void testFindMax() { + Assert.assertEquals(8, tree.findMax().intValue()); + } + + @Test + public void testHeight() { + Assert.assertEquals(4, tree.height()); + } + + @Test + public void testSize() { + Assert.assertEquals(7, tree.size()); + } + + @Test + public void testRemoveLeaf() { + tree.remove(3); + BinaryTreeNode root= tree.getRoot(); + Assert.assertEquals(4, root.left.right.data.intValue()); + + } + @Test + public void testRemoveMiddleNode1() { + tree.remove(4); + BinaryTreeNode root= tree.getRoot(); + Assert.assertEquals(5, root.left.right.data.intValue()); + Assert.assertEquals(3, root.left.right.left.data.intValue()); + } + @Test + public void testRemoveMiddleNode2() { + tree.remove(2); + BinaryTreeNode root= tree.getRoot(); + Assert.assertEquals(3, root.left.data.intValue()); + Assert.assertEquals(4, root.left.right.data.intValue()); + } + + @Test + public void testLevelVisit() { + List values = tree.levelVisit(); + Assert.assertEquals("[6, 2, 8, 1, 4, 3, 5]", values.toString()); + + } + @Test + public void testLCA(){ + Assert.assertEquals(2,tree.getLowestCommonAncestor(1, 5).intValue()); + Assert.assertEquals(2,tree.getLowestCommonAncestor(1, 4).intValue()); + Assert.assertEquals(6,tree.getLowestCommonAncestor(3, 8).intValue()); + } + @Test + public void testIsValid() { + + Assert.assertTrue(tree.isValid()); + + BinaryTreeNode root = new BinaryTreeNode(6); + root.left = new BinaryTreeNode(2); + root.right = new BinaryTreeNode(8); + root.left.left = new BinaryTreeNode(4); + root.left.right = new BinaryTreeNode(1); + root.left.right.left = new BinaryTreeNode(3); + tree = new BinarySearchTree(root); + + Assert.assertFalse(tree.isValid()); + } + @Test + public void testGetNodesBetween(){ + List numbers = this.tree.getNodesBetween(3, 8); + System.out.println(numbers.toString()); + + } +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/tree/BinaryTreeNode.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/tree/BinaryTreeNode.java new file mode 100644 index 0000000000..c1421cd398 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/tree/BinaryTreeNode.java @@ -0,0 +1,35 @@ +package com.coding.basic.tree; + +public class BinaryTreeNode { + + public T data; + public BinaryTreeNode left; + public BinaryTreeNode right; + + public BinaryTreeNode(T data){ + this.data=data; + } + public T getData() { + return data; + } + public void setData(T data) { + this.data = data; + } + public BinaryTreeNode getLeft() { + return left; + } + public void setLeft(BinaryTreeNode left) { + this.left = left; + } + public BinaryTreeNode getRight() { + return right; + } + public void setRight(BinaryTreeNode right) { + this.right = right; + } + + public BinaryTreeNode insert(Object o){ + return null; + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/tree/BinaryTreeUtil.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/tree/BinaryTreeUtil.java new file mode 100644 index 0000000000..b033cbe1d5 --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/tree/BinaryTreeUtil.java @@ -0,0 +1,66 @@ +package com.coding.basic.tree; + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +public class BinaryTreeUtil { + /** + * 用递归的方式实现对二叉树的前序遍历, 需要通过BinaryTreeUtilTest测试 + * + * @param root + * @return + */ + public static List preOrderVisit(BinaryTreeNode root) { + List result = new ArrayList(); + + return result; + } + + /** + * 用递归的方式实现对二叉树的中遍历 + * + * @param root + * @return + */ + public static List inOrderVisit(BinaryTreeNode root) { + List result = new ArrayList(); + + return result; + } + + /** + * 用递归的方式实现对二叉树的后遍历 + * + * @param root + * @return + */ + public static List postOrderVisit(BinaryTreeNode root) { + List result = new ArrayList(); + + return result; + } + /** + * 用非递归的方式实现对二叉树的前序遍历 + * @param root + * @return + */ + public static List preOrderWithoutRecursion(BinaryTreeNode root) { + + List result = new ArrayList(); + + return result; + } + /** + * 用非递归的方式实现对二叉树的中序遍历 + * @param root + * @return + */ + public static List inOrderWithoutRecursion(BinaryTreeNode root) { + + List result = new ArrayList(); + + return result; + } + +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/tree/BinaryTreeUtilTest.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/tree/BinaryTreeUtilTest.java new file mode 100644 index 0000000000..41857e137d --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/tree/BinaryTreeUtilTest.java @@ -0,0 +1,75 @@ +package com.coding.basic.tree; + +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class BinaryTreeUtilTest { + + BinaryTreeNode root = null; + @Before + public void setUp() throws Exception { + root = new BinaryTreeNode(1); + root.setLeft(new BinaryTreeNode(2)); + root.setRight(new BinaryTreeNode(5)); + root.getLeft().setLeft(new BinaryTreeNode(3)); + root.getLeft().setRight(new BinaryTreeNode(4)); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testPreOrderVisit() { + + List result = BinaryTreeUtil.preOrderVisit(root); + Assert.assertEquals("[1, 2, 3, 4, 5]", result.toString()); + + + } + @Test + public void testInOrderVisit() { + + + List result = BinaryTreeUtil.inOrderVisit(root); + Assert.assertEquals("[3, 2, 4, 1, 5]", result.toString()); + + } + + @Test + public void testPostOrderVisit() { + + + List result = BinaryTreeUtil.postOrderVisit(root); + Assert.assertEquals("[3, 4, 2, 5, 1]", result.toString()); + + } + + + @Test + public void testInOrderVisitWithoutRecursion() { + BinaryTreeNode node = root.getLeft().getRight(); + node.setLeft(new BinaryTreeNode(6)); + node.setRight(new BinaryTreeNode(7)); + + List result = BinaryTreeUtil.inOrderWithoutRecursion(root); + Assert.assertEquals("[3, 2, 6, 4, 7, 1, 5]", result.toString()); + + } + @Test + public void testPreOrderVisitWithoutRecursion() { + BinaryTreeNode node = root.getLeft().getRight(); + node.setLeft(new BinaryTreeNode(6)); + node.setRight(new BinaryTreeNode(7)); + + List result = BinaryTreeUtil.preOrderWithoutRecursion(root); + Assert.assertEquals("[1, 2, 3, 4, 6, 7, 5]", result.toString()); + + } +} diff --git a/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/tree/FileList.java b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/tree/FileList.java new file mode 100644 index 0000000000..6e65192e4a --- /dev/null +++ b/students/1377699408/data-structure/assignment/src/main/java/com/coding/basic/tree/FileList.java @@ -0,0 +1,10 @@ +package com.coding.basic.tree; + +import java.io.File; + +public class FileList { + public void list(File f) { + } + + +} diff --git a/students/1377699408/ood/ood-assignment/pom.xml b/students/1377699408/ood/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/1377699408/ood/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..ccffce577d --- /dev/null +++ b/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public static String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/EmailException.java b/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/EmailException.java new file mode 100644 index 0000000000..1be735e5f5 --- /dev/null +++ b/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/EmailException.java @@ -0,0 +1,7 @@ +package com.coderising.ood.srp; + +public class EmailException extends Exception { + public EmailException(String message) { + super(message); + } +} diff --git a/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..4397366a16 --- /dev/null +++ b/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,57 @@ +package com.coderising.ood.srp; + +import com.coderising.ood.srp.bean.Email; +import com.coderising.ood.srp.bean.Product; +import com.coderising.ood.srp.dao.EmailDAO; + +import java.io.IOException; +import java.util.*; + +public class PromotionMail { + private static EmailDAO emailDAO = new EmailDAO(); + + public static void main(String[] args) throws Exception { + List emailList = getEmails("product_promotion.txt"); + for (Email email : emailList) { + sendEmail(email); + } + + } + + public static List getEmails(String file) throws IOException { + List emailList = new ArrayList(); + List list = Product.getProductByFile(file); + + for (Product p : list) { + String productId = p.getProductID(); + List> l = emailDAO.listSubscriptionsByProdoctId(productId); + for (Map userInfo : l) { + String username = userInfo.get("NAME"); + String productDesc = p.getProductDesc(); + String fromAddr = Configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN); + List toAddr = new ArrayList(); + toAddr.add(userInfo.get("EMAIL")); + String smtpServer = Configuration.getProperty(ConfigurationKeys.SMTP_SERVER); + Email email = new Email(fromAddr, toAddr, "\"您关注的产品降价了\"", "尊敬的 " + username + ", 您关注的产品 " + productDesc + " 降价了,欢迎购买!", smtpServer, fromAddr); + emailList.add(email); + } + } + return emailList; + } + + public static void sendEmail(Email email) { + if (email == null) { + System.out.println("没有邮件发送"); + } + try { + email.send(); + } catch (EmailException e) { + email.setSmtpServer(Configuration.getProperty(ConfigurationKeys.ALT_SMTP_SERVER)); + try { + email.send(); + } catch (EmailException e1) { + System.out.println("使用备用服务器发送失败"); + } + } + } +} diff --git a/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/bean/Email.java b/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/bean/Email.java new file mode 100644 index 0000000000..de6cfe1636 --- /dev/null +++ b/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/bean/Email.java @@ -0,0 +1,102 @@ +package com.coderising.ood.srp.bean; + + +import com.coderising.ood.srp.utils.CollectionUtils; +import com.coderising.ood.srp.EmailException; +import com.coderising.ood.srp.utils.StringUtils; + +import java.util.Arrays; +import java.util.List; + +public class Email { + private String fromAddress; + private List toAddresses; + private String subject; + private String content; + private String smtpServer; + private String email_admin; + + public Email(String fromAddress, List toAddresses, String subject, String content, String smtpServer, String email_admin) { + this.fromAddress = fromAddress; + this.toAddresses = toAddresses; + this.subject = subject; + this.content = content; + this.smtpServer = smtpServer; + this.email_admin = email_admin; + } + + public void send() throws EmailException { + //假装发了一封邮件 + check_send(); + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(this.getFromAddress()).append("\n"); + buffer.append("To:").append(Arrays.toString(this.getToAddresses().toArray())).append("\n"); + buffer.append("Subject:").append(this.getSubject()).append("\n"); + buffer.append("Content:").append(this.getContent()).append("\n"); + System.out.println(buffer.toString()); + } + + private void check_send() throws EmailException { + if (StringUtils.isBlank(this.fromAddress)) { + throw new EmailException("fromAddress is empty"); + } + if (CollectionUtils.isEmpty(this.toAddresses)) { + throw new EmailException("toAddresses is empty"); + } + if (StringUtils.isBlank(this.subject)) { + throw new EmailException("subject is empty"); + } + } + + public Email() { + } + + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public List getToAddresses() { + return toAddresses; + } + + public void setToAddresses(List toAddresses) { + this.toAddresses = toAddresses; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public String getSmtpServer() { + return smtpServer; + } + + public void setSmtpServer(String smtpServer) { + this.smtpServer = smtpServer; + } + + public String getEmail_admin() { + return email_admin; + } + + public void setEmail_admin(String email_admin) { + this.email_admin = email_admin; + } +} diff --git a/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/bean/Product.java b/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/bean/Product.java new file mode 100644 index 0000000000..c3872c33bb --- /dev/null +++ b/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/bean/Product.java @@ -0,0 +1,66 @@ +package com.coderising.ood.srp.bean; + +import com.coderising.ood.srp.utils.StringUtils; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class Product { + private String productID; + private String productDesc; + + public static List getProductByFile(String f) throws IOException { + List list = new ArrayList(); + File file = new File(f); + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String s = ""; + while (!StringUtils.isBlank((s=br.readLine()))) { + String[] data = s.split(" "); + Product p = new Product(data[0], data[1]); + System.out.println("产品ID = " + data[0] + "\n"); + System.out.println("产品描述 = " + data[1] + "\n"); + list.add(p); + } + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + if (br != null) { + br.close(); + } + } + return list; + } + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + + public Product() { + + } + + public Product(String productID, String productDesc) { + + this.productID = productID; + this.productDesc = productDesc; + } +} diff --git a/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dao/EmailDAO.java b/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dao/EmailDAO.java new file mode 100644 index 0000000000..39975b9276 --- /dev/null +++ b/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dao/EmailDAO.java @@ -0,0 +1,22 @@ +package com.coderising.ood.srp.dao; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class EmailDAO { + public List> listSubscriptionsByProdoctId(String productId) { + String sql = "Select name from subscriptions " + + "where product_id= '" + productId + "' " + + "and send_mail=1 "; + List> userList = new ArrayList>(); + for (int i = 1; i <= 3; i++) { + Map userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + return userList; + } +} diff --git a/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/utils/CollectionUtils.java b/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/utils/CollectionUtils.java new file mode 100644 index 0000000000..ff60683472 --- /dev/null +++ b/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/utils/CollectionUtils.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp.utils; + +import java.util.List; + +public class CollectionUtils { + public static boolean isEmpty(List list) { + return list == null || list.size() == 0; + } +} diff --git a/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/utils/StringUtils.java b/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/utils/StringUtils.java new file mode 100644 index 0000000000..4d86f4ba08 --- /dev/null +++ b/students/1377699408/ood/ood-assignment/src/main/java/com/coderising/ood/srp/utils/StringUtils.java @@ -0,0 +1,7 @@ +package com.coderising.ood.srp.utils; + +public class StringUtils { + public static boolean isBlank(String s) { + return s == null || "".equals(s.trim()); + } +} diff --git a/students/1395844061/.gitignore b/students/1395844061/.gitignore new file mode 100644 index 0000000000..d41523dfd3 --- /dev/null +++ b/students/1395844061/.gitignore @@ -0,0 +1,26 @@ +# Created by .ignore support plugin (hsz.mobi) +### Java template +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +1395844061.iml diff --git a/students/1395844061/README.md b/students/1395844061/README.md new file mode 100644 index 0000000000..32243de0c9 --- /dev/null +++ b/students/1395844061/README.md @@ -0,0 +1,2 @@ +### 1395844061 ood +1. ood代码优化 diff --git a/students/1395844061/build.gradle b/students/1395844061/build.gradle new file mode 100644 index 0000000000..db1cbf8def --- /dev/null +++ b/students/1395844061/build.gradle @@ -0,0 +1,18 @@ +group 'peng-test' +version '1.0-SNAPSHOT' + +apply plugin: 'java' + +sourceCompatibility = 1.5 + +repositories { + maven{ + url "http://maven.oschina.net/content/groups/public/" + } +} + +dependencies { + + compile 'org.htmlparser:htmlparser:2.1' + testCompile group: 'junit', name: 'junit', version: '4.11' +} diff --git a/students/1395844061/course-pro-1/build.gradle b/students/1395844061/course-pro-1/build.gradle new file mode 100644 index 0000000000..939cf6ccbe --- /dev/null +++ b/students/1395844061/course-pro-1/build.gradle @@ -0,0 +1,14 @@ +group 'peng-test' +version '1.0-SNAPSHOT' + +apply plugin: 'java' + +sourceCompatibility = 1.8 + +repositories { + mavenCentral() +} + +dependencies { + testCompile group: 'junit', name: 'junit', version: '4.12' +} diff --git a/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/ProductInfo.java b/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/ProductInfo.java new file mode 100644 index 0000000000..1ba8cf2db7 --- /dev/null +++ b/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/ProductInfo.java @@ -0,0 +1,30 @@ +package com.coderising.ood.srp; + +/** + * ProductInfo + * + * @author Chenpz + * @package com.coderising.ood.srp + * @date 2017/6/14/22:41 + */ +public class ProductInfo { + + private String productID = null; + private String productDesc = null; + + public ProductInfo(){} + + public ProductInfo(String productID, String productDesc){ + this.productID = productID; + this.productDesc = productDesc; + } + + public String getProductDesc() { + return productDesc; + } + + public String getProductID() { + return productID; + } + +} diff --git a/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..0be9b165c9 --- /dev/null +++ b/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,99 @@ +package com.coderising.ood.srp; + +import com.coderising.ood.srp.utils.DBUtil; +import com.coderising.ood.srp.utils.MailUtil; +import com.coderising.ood.srp.utils.ArgsUtil; + +import java.io.IOException; +import java.util.*; + +/** + * PromotionMail + * + * @author Chenpz + * @package com.coderising.ood.srp + * @date 2017/6/12/23:33 + */ +public class PromotionMail { + + private ProductInfo productInfo; + private List mailInfoList = new ArrayList<>(); + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + public PromotionMail(){} + + public PromotionMail(ProductInfo productInfo) throws Exception { + this.productInfo = productInfo; + initMailInfoList(loadMailingList()); + } + + /** + * 获取每个型号的手机关注的人员信息列表 + * @return + * @throws Exception + */ + private List> loadMailingList() throws Exception { + String sql = "select name from subscriptions " + + "where product_id= '" + productInfo.getProductID() +"' " + + "and send_mail=1 "; + return DBUtil.query(sql); + } + + /** + * 组装促销邮件的内容信息 + * @param mailingList + */ + private void initMailInfoList(List> mailingList) { + if (ArgsUtil.isNotEmpty(mailingList)){ + for (Map map : mailingList){ + // 初始化 mailInfoList + mailInfoList.add(buildMailInfo(map)); + } + } + } + + /** + * 组装邮件内容信息 + * @param userInfo + * @return + */ + private MailInfo buildMailInfo(Map userInfo){ + String name = userInfo.get(NAME_KEY); + String subject = "您关注的产品降价了"; + String message = "尊敬的 "+name+", 您关注的产品 " + productInfo.getProductDesc() + " 降价了,欢迎购买!" ; + String toAddress = userInfo.get(EMAIL_KEY); + return new MailInfo(toAddress, subject, message); + } + + /** + * 发送促销邮件 + * @param debug + * @throws IOException + */ + public void sendEMails(boolean debug) throws IOException { + System.out.println("开始发送邮件... ..."); + if (ArgsUtil.isNotEmpty(mailInfoList)) { + for (MailInfo mailInfo : mailInfoList){ + MailUtil.sendEmail(mailInfo.toAddress, mailInfo.subject, mailInfo.message, debug); + } + }else { + System.out.println("没有邮件发送... ..."); + } + } + + class MailInfo{ + + private String toAddress = null; + private String subject = null; + private String message = null; + + MailInfo(String toAddress, String subject, String message){ + this.toAddress = toAddress; + this.subject = subject; + this.message = message; + } + } + +} diff --git a/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/config/Configuration.java b/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/config/Configuration.java new file mode 100644 index 0000000000..931e93ab3b --- /dev/null +++ b/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/config/Configuration.java @@ -0,0 +1,31 @@ +package com.coderising.ood.srp.config; + +import java.util.HashMap; +import java.util.Map; + +/** + * Configuration + * + * @author Chenpz + * @package com.coderising.ood.srp + * @date 2017/6/12/23:30 + */ +public class Configuration { + + static Map configurations = new HashMap<>(); + + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER , "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN , "admin@company.com"); + } + + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + return configurations.get(key); + } +} diff --git a/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/config/ConfigurationKeys.java b/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/config/ConfigurationKeys.java new file mode 100644 index 0000000000..702c8cce32 --- /dev/null +++ b/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/config/ConfigurationKeys.java @@ -0,0 +1,16 @@ +package com.coderising.ood.srp.config; + +/** + * ConfigurationKeys + * + * @author Chenpz + * @package com.coderising.ood.srp + * @date 2017/6/12/23:31 + */ +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/utils/ArgsUtil.java b/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/utils/ArgsUtil.java new file mode 100644 index 0000000000..b329a9ade4 --- /dev/null +++ b/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/utils/ArgsUtil.java @@ -0,0 +1,28 @@ +package com.coderising.ood.srp.utils; + +import java.util.List; + +/** + * ArgsUtil + * + * @author Chenpz + * @package com.coderising.ood.srp.utils + * @date 2017/6/17/11:56 + */ +public final class ArgsUtil { + + private ArgsUtil(){ + throw new RuntimeException("illegal called!"); + } + + public static boolean isNotNull(Object object){ + + return object != null; + } + + public static boolean isNotEmpty(List list){ + + return isNotNull(list) && !list.isEmpty(); + } + +} diff --git a/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/utils/DBUtil.java b/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/utils/DBUtil.java new file mode 100644 index 0000000000..2b4e0410ac --- /dev/null +++ b/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/utils/DBUtil.java @@ -0,0 +1,37 @@ +package com.coderising.ood.srp.utils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * DBUtil + * + * @author Chenpz + * @package com.coderising.ood.srp + * @date 2017/6/12/23:32 + */ +public final class DBUtil { + + private DBUtil(){ + throw new RuntimeException("illegal called!"); + } + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List> query(String sql){ + System.out.println("sql: "+sql); + List> userList = new ArrayList<>(); + for (int i = 1; i <= 3; i++) { + Map userInfo = new HashMap<>(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + return userList; + } +} diff --git a/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/utils/FileUtil.java b/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/utils/FileUtil.java new file mode 100644 index 0000000000..43af9df5e4 --- /dev/null +++ b/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/utils/FileUtil.java @@ -0,0 +1,46 @@ +package com.coderising.ood.srp.utils; + +import com.coderising.ood.srp.ProductInfo; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; + +/** + * FileUtils + * + * @author Chenpz + * @package com.coderising.ood.srp + * @date 2017/6/14/22:43 + */ +public final class FileUtil { + + private FileUtil(){ + throw new RuntimeException("illegal called!"); + } + + public static List readProductInfoFromFile(String filePath) throws IOException{ + + if (!ArgsUtil.isNotNull(filePath)) + throw new IllegalArgumentException("illegal arguments"); + + File file = new File(filePath); + BufferedReader br = null; + List productInfoList = new ArrayList<>(); + try { + br = new BufferedReader(new FileReader(file)); + String temp; + while((temp = br.readLine()) != null){ + String[] data = temp.split(" "); + productInfoList.add(new ProductInfo(data[0], data[1])); + } + return productInfoList; + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + if (br != null) + br.close(); + } + } + +} diff --git a/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/utils/MailUtil.java b/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/utils/MailUtil.java new file mode 100644 index 0000000000..cff76d7bf0 --- /dev/null +++ b/students/1395844061/course-pro-1/src/main/java/com/coderising/ood/srp/utils/MailUtil.java @@ -0,0 +1,67 @@ +package com.coderising.ood.srp.utils; + +import com.coderising.ood.srp.config.Configuration; +import com.coderising.ood.srp.config.ConfigurationKeys; + +/** + * MailUtil + * + * @author Chenpz + * @package com.coderising.ood.srp + * @date 2017/6/12/23:28 + */ +public final class MailUtil { + + private static String smtpHost = null; + private static String altSmtpHost = null; + private static String fromAddress = null; + + static{ + Configuration config = new Configuration(); + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + private MailUtil(){ + throw new RuntimeException("illegal called!"); + } + + public static void sendEmail(String toAddress, String subject, String message, boolean debug) { + + //假装发了一封邮件 + System.out.println("debug: " + debug); + try { + System.out.println("使用默认host发送邮件"); + sendDefaultMail(toAddress, subject, message); + }catch (Exception e){ + System.out.println("使用备用host发送邮件"); + sendAltMail(toAddress,subject, message); + } + } + + private static void sendDefaultMail(String toAddress, String subject, String message){ + System.out.println("smtpHost: " + smtpHost); + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + } + + private static void sendAltMail(String toAddress, String subject, String message){ + System.out.println("altSmtpHost: " + altSmtpHost); + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + } + + + + + +} diff --git a/students/1395844061/course-pro-1/src/test/java/com/coderising/ood/srp/MainTest.java b/students/1395844061/course-pro-1/src/test/java/com/coderising/ood/srp/MainTest.java new file mode 100644 index 0000000000..2bf0df1070 --- /dev/null +++ b/students/1395844061/course-pro-1/src/test/java/com/coderising/ood/srp/MainTest.java @@ -0,0 +1,27 @@ +package com.coderising.ood.srp; + +import com.coderising.ood.srp.utils.ArgsUtil; +import com.coderising.ood.srp.utils.FileUtil; + +import java.util.List; + +/** + * MainTest + * + * @author Chenpz + * @package com.coderising.ood.srp + * @date 2017/6/14/22:45 + */ +public class MainTest { + + public static void main(String[] args) throws Exception{ + String filePath = MainTest.class.getClassLoader().getResource("product_promotion.txt").getFile(); + List productInfoList = FileUtil.readProductInfoFromFile(filePath); + if (ArgsUtil.isNotEmpty(productInfoList)){ + for (ProductInfo productInfo: productInfoList){ + new PromotionMail(productInfo) + .sendEMails(false); + } + } + } +} diff --git a/students/1395844061/course-pro-1/src/test/resources/product_promotion.txt b/students/1395844061/course-pro-1/src/test/resources/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/1395844061/course-pro-1/src/test/resources/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/1395844061/settings.gradle b/students/1395844061/settings.gradle new file mode 100644 index 0000000000..f66e41c2f9 --- /dev/null +++ b/students/1395844061/settings.gradle @@ -0,0 +1,2 @@ +include 'course-pro-1' + diff --git a/students/1398524980/README.md b/students/1398524980/README.md new file mode 100644 index 0000000000..a652ad5ecf --- /dev/null +++ b/students/1398524980/README.md @@ -0,0 +1 @@ +作业 \ No newline at end of file diff --git a/students/1398524980/second phase/once/README.md b/students/1398524980/second phase/once/README.md new file mode 100644 index 0000000000..4a2bb84fe9 --- /dev/null +++ b/students/1398524980/second phase/once/README.md @@ -0,0 +1 @@ +面向对象设计 \ No newline at end of file diff --git a/students/1398524980/second phase/once/ood_assignment/pom.xml b/students/1398524980/second phase/once/ood_assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/1398524980/second phase/once/ood_assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..0fb3dcfa77 --- /dev/null +++ b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,34 @@ +package main.java.com.coderising.ood.srp; + +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + private static Configuration config; + + static Map configurations = new HashMap<>(); + static { + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + + private Configuration() { + } + + protected static Configuration getConfig() { + return config; + } + + /** + * + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..e63eb922a4 --- /dev/null +++ b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package main.java.com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..1a88f401f1 --- /dev/null +++ b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,24 @@ +package main.java.com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * @param sql + * @return + */ + public static List> query(String sql){ + + List> userList = new ArrayList>(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/FromAddress.java b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/FromAddress.java new file mode 100644 index 0000000000..1a71da260d --- /dev/null +++ b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/FromAddress.java @@ -0,0 +1,15 @@ +package main.java.com.coderising.ood.srp; + +public class FromAddress { + + private String fromAddress = null; + + protected void setFromAddress() { + fromAddress = Configuration.getConfig().getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + public String getFromAddress() { + return fromAddress; + } + +} diff --git a/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/LoadInformation.java b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/LoadInformation.java new file mode 100644 index 0000000000..1eac48983f --- /dev/null +++ b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/LoadInformation.java @@ -0,0 +1,22 @@ +package main.java.com.coderising.ood.srp; + +import java.util.List; + +public class LoadInformation { + + private String productID = new ProductInfo().getproductID(); + + private String sendMailQuery = null; + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + "where product_id= '" + productID + "' " + "and send_mail=1 "; + + System.out.println("loadQuery set"); + } + +} diff --git a/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..84dbffa75d --- /dev/null +++ b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,16 @@ +package main.java.com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + +} diff --git a/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/ProductInfo.java b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/ProductInfo.java new file mode 100644 index 0000000000..a678d2987e --- /dev/null +++ b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/ProductInfo.java @@ -0,0 +1,52 @@ +package main.java.com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +public class ProductInfo { + + private String productID = null; + private String productDesc = null; + + /** + * + * @throws IOException + */ + public void readProductInfo(String pomotionInfoAddress) throws IOException { + + File f = new File(pomotionInfoAddress); + + readFile(f); + } + + private void readFile(File file) throws IOException { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + productID = data[0]; + productDesc = data[1]; + + System.out.println("ƷID = " + productID + "\n"); + System.out.println("Ʒ = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + protected String getproductID() { + return productID; + } + + protected String getProductDesc() { + return productDesc; + } + +} diff --git a/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..c94ac5a088 --- /dev/null +++ b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,36 @@ +package main.java.com.coderising.ood.srp; + +public class PromotionMail { + + private static ProductInfo productInfo = new ProductInfo(); + private static SetProtocol setprotocol = new SetProtocol(); + private static LoadInformation loadInformation = new LoadInformation(); + private static FromAddress fromAddress = new FromAddress(); + private static SendEMails sendEmails = new SendEMails(); + + public static void main(String[] args) throws Exception { + + boolean emailDebug = false; + new PromotionMail(emailDebug, + "C:\\Users\\123\\Documents\\workspace\\ood_assignment\\src\\com\\coderising\\ood\\srp\\product_promotion.txt"); + } + + PromotionMail(boolean emailDebug, String pomotionInfoAddress) throws Exception { + + // ȡƷϢ + productInfo.readProductInfo(pomotionInfoAddress); + + // ÷ͷЭ + setprotocol.setProtocol(); + + // öȡϢ + loadInformation.setLoadQuery(); + + // ÷͵ַ + fromAddress.setFromAddress(); + + // ʼ ʼ + sendEmails.sendEMails(emailDebug); + } + +} \ No newline at end of file diff --git a/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/SendEMails.java b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/SendEMails.java new file mode 100644 index 0000000000..29bb0f1363 --- /dev/null +++ b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/SendEMails.java @@ -0,0 +1,51 @@ +package main.java.com.coderising.ood.srp; + +import java.util.HashMap; +import java.util.Iterator; + +public class SendEMails { + + private ToAddressAndMessage message = new ToAddressAndMessage(); + + private String smtpHost = new SetProtocol().getSMTPHost(); + private String altSmtpHost = new SetProtocol().getAltSMTPHost(); + + private LoadInformation load = new LoadInformation(); + + /** + * + * @param debug + * @param mailingList + * @throws Exception + */ + protected void sendEMails(boolean debug) throws Exception { + + System.out.println("开始发送邮件"); + + if (load.loadMailingList() != null) { + Iterator iter = load.loadMailingList().iterator(); + while (iter.hasNext()) { + message.configureEMail((HashMap) iter.next()); + try { + if (message.toAddress.length() > 0) { + message.sendSMTPHostWay(smtpHost, debug); + } + } catch (Exception e) { + try { + message.sendAltSMTPHostWay(altSmtpHost, debug); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + } + + else { + System.out.println("没有邮件发送"); + + } + + } + +} diff --git a/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/SetProtocol.java b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/SetProtocol.java new file mode 100644 index 0000000000..98e0151fb6 --- /dev/null +++ b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/SetProtocol.java @@ -0,0 +1,32 @@ +package main.java.com.coderising.ood.srp; + +public class SetProtocol { + + private String smtpHost = null; + private String altSmtpHost = null; + + private Configuration config; + + protected void setProtocol() { + config = Configuration.getConfig(); + setSMTPHost(); + setAltSMTPHost(); + } + + private void setSMTPHost() { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + private void setAltSMTPHost() { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + } + + protected String getSMTPHost() { + return smtpHost; + } + + protected String getAltSMTPHost() { + return altSmtpHost; + } + +} diff --git a/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/ToAddressAndMessage.java b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/ToAddressAndMessage.java new file mode 100644 index 0000000000..c99bbc683b --- /dev/null +++ b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/ToAddressAndMessage.java @@ -0,0 +1,52 @@ +package main.java.com.coderising.ood.srp; + +import java.io.IOException; +import java.util.HashMap; + +public class ToAddressAndMessage { + + private String productDesc = new ProductInfo().getProductDesc(); + + protected String toAddress = null; + private String fromAddress = new FromAddress().getFromAddress(); + + private String subject = null; + private String message = null; + + private static final String EMAIL_KEY = "EMAIL"; + private static final String NAME_KEY = "NAME"; + + /** + * + * @param userInfo + * @throws IOException + */ + protected void addressAndMessage(HashMap userInfo) throws IOException { + configureEMail(userInfo); + setMessage(userInfo); + } + + protected void configureEMail(HashMap userInfo) throws IOException { + + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected void setMessage(HashMap userInfo) throws IOException { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 " + name + ", 您关注的产品 " + productDesc + " 降价了,欢迎购买!"; + } + + protected void sendSMTPHostWay(String smtpHost, boolean debug) { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } + + protected void sendAltSMTPHostWay(String altSmtpHost, boolean debug) { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + } + +} diff --git a/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/1398524980/second phase/once/ood_assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/1417442485/out/production/1417442485/main/java/com/coderising/ood/srp/product_promotion.txt b/students/1417442485/out/production/1417442485/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/1417442485/out/production/1417442485/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/1417442485/pom.xml b/students/1417442485/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/1417442485/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/1417442485/src/main/java/com/coderising/ood/srp/Configuration.java b/students/1417442485/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..70b861717d --- /dev/null +++ b/students/1417442485/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package main.java.com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + private static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public static String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/1417442485/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/1417442485/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..e63eb922a4 --- /dev/null +++ b/students/1417442485/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package main.java.com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/1417442485/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/1417442485/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..c34751d344 --- /dev/null +++ b/students/1417442485/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,20 @@ +package main.java.com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(final String sql){ + final List userList = new ArrayList<>(); + for (int i = 1; i <= 3; i++) { + userList.add(new UserInfo("User" + i, "aa@bb.com")); + } + return userList; + } +} diff --git a/students/1417442485/src/main/java/com/coderising/ood/srp/FileUtil.java b/students/1417442485/src/main/java/com/coderising/ood/srp/FileUtil.java new file mode 100644 index 0000000000..aa288e2795 --- /dev/null +++ b/students/1417442485/src/main/java/com/coderising/ood/srp/FileUtil.java @@ -0,0 +1,25 @@ +package main.java.com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +public class FileUtil { + + public static String[] readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + String[] data; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + data = temp.split(" "); + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + return data; + } +} diff --git a/students/1417442485/src/main/java/com/coderising/ood/srp/MailMessage.java b/students/1417442485/src/main/java/com/coderising/ood/srp/MailMessage.java new file mode 100644 index 0000000000..7e499b7d64 --- /dev/null +++ b/students/1417442485/src/main/java/com/coderising/ood/srp/MailMessage.java @@ -0,0 +1,9 @@ +package main.java.com.coderising.ood.srp; + +public interface MailMessage { + + String getFromAddress(); + String getToAddress(); + String getSubject(); + String getMessageBody(); +} diff --git a/students/1417442485/src/main/java/com/coderising/ood/srp/MailService.java b/students/1417442485/src/main/java/com/coderising/ood/srp/MailService.java new file mode 100644 index 0000000000..2b8bdf73ef --- /dev/null +++ b/students/1417442485/src/main/java/com/coderising/ood/srp/MailService.java @@ -0,0 +1,19 @@ +package main.java.com.coderising.ood.srp; + +public class MailService { + + public static void send(final MailMessage message, final MailSetting mailSetting) { + if(message.getToAddress().length() == 0) return; + try { + MailUtil.sendEmail(message.getToAddress(), message.getFromAddress(), message.getSubject(), + message.getMessageBody(), MailSetting.smtpHost, mailSetting.emailDebug); + } catch (Exception e) { + try { + MailUtil.sendEmail(message.getToAddress(), message.getFromAddress(), message.getSubject(), + message.getMessageBody(), MailSetting.altSmtpHost, mailSetting.emailDebug); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } +} diff --git a/students/1417442485/src/main/java/com/coderising/ood/srp/MailSetting.java b/students/1417442485/src/main/java/com/coderising/ood/srp/MailSetting.java new file mode 100644 index 0000000000..0991bbae02 --- /dev/null +++ b/students/1417442485/src/main/java/com/coderising/ood/srp/MailSetting.java @@ -0,0 +1,11 @@ +package main.java.com.coderising.ood.srp; + +public class MailSetting { + static String smtpHost = Configuration.getProperty(ConfigurationKeys.SMTP_SERVER); + static String altSmtpHost = Configuration.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + final boolean emailDebug; + + public MailSetting(boolean emailDebug) { + this.emailDebug = emailDebug; + } +} diff --git a/students/1417442485/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/1417442485/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..59cc73476e --- /dev/null +++ b/students/1417442485/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package main.java.com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/1417442485/src/main/java/com/coderising/ood/srp/Product.java b/students/1417442485/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..2e807c9d50 --- /dev/null +++ b/students/1417442485/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,11 @@ +package main.java.com.coderising.ood.srp; + +public class Product { + final String productId; + final String productDesc; + + public Product(String productId, String productDesc) { + this.productId = productId; + this.productDesc = productDesc; + } +} diff --git a/students/1417442485/src/main/java/com/coderising/ood/srp/ProductDataStore.java b/students/1417442485/src/main/java/com/coderising/ood/srp/ProductDataStore.java new file mode 100644 index 0000000000..770baa7aff --- /dev/null +++ b/students/1417442485/src/main/java/com/coderising/ood/srp/ProductDataStore.java @@ -0,0 +1,30 @@ +package main.java.com.coderising.ood.srp; + +import java.io.File; +import java.io.IOException; + +public class ProductDataStore { + + private final File mFileDataSource; + + public ProductDataStore(final File file) { + mFileDataSource = file; + } + + public Product getProduct() { + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + String[] data = null; + try { + data = FileUtil.readFile(mFileDataSource); + } catch (IOException e) { + e.printStackTrace(); + } + Product product = null; + if(data != null && data.length >= 2) { + product = new Product(data[0], data[1]); + System.out.println("产品ID = " + product.productId + "\n"); + System.out.println("产品描述 = " + product.productDesc + "\n"); + } + return product; + } +} diff --git a/students/1417442485/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/1417442485/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..881bdb0f7c --- /dev/null +++ b/students/1417442485/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,32 @@ +package main.java.com.coderising.ood.srp; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +public class PromotionMail { + + private static final String PRODUCT_FILE = "src/main/java/com/coderising/ood/srp/product_promotion.txt"; + + public static void main(String[] args) throws Exception { + + final Product product = new ProductDataStore(new File(PRODUCT_FILE)).getProduct(); + final List userList = UserDataStore.getMailingList(product.productId); + final MailSetting mailSetting = new MailSetting(false); + + PromotionMail.sendEmails(product, userList, mailSetting); + } + + protected static void sendEmails(final Product product, final List userList, final MailSetting mailSetting) throws IOException + { + if(userList == null || userList.isEmpty()) { + System.out.println("没有邮件发送"); + return; + } + System.out.println("开始发送邮件"); + for (UserInfo userInfo : userList) { + final PromotionMailMessage message = new PromotionMailMessage(userInfo.email, userInfo.name, product.productDesc); + MailService.send(message, mailSetting); + } + } +} diff --git a/students/1417442485/src/main/java/com/coderising/ood/srp/PromotionMailMessage.java b/students/1417442485/src/main/java/com/coderising/ood/srp/PromotionMailMessage.java new file mode 100644 index 0000000000..e6f1548559 --- /dev/null +++ b/students/1417442485/src/main/java/com/coderising/ood/srp/PromotionMailMessage.java @@ -0,0 +1,37 @@ +package main.java.com.coderising.ood.srp; + +public class PromotionMailMessage implements MailMessage { + private final static String FROM_ADDRESS = Configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN); + private final static String SUBJECT = "您关注的产品降价了"; + private final String toAddress; + private final String message; + + public PromotionMailMessage(final String toAddress, final String userName, final String productDesc){ + this.toAddress = toAddress; + if (toAddress.length() > 0) { + message = "尊敬的 "+userName+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + } else { + message = null; + } + } + + @Override + public String getFromAddress() { + return FROM_ADDRESS; + } + + @Override + public String getToAddress() { + return toAddress; + } + + @Override + public String getSubject() { + return SUBJECT; + } + + @Override + public String getMessageBody() { + return message; + } +} diff --git a/students/1417442485/src/main/java/com/coderising/ood/srp/UserDataStore.java b/students/1417442485/src/main/java/com/coderising/ood/srp/UserDataStore.java new file mode 100644 index 0000000000..b62d9b0072 --- /dev/null +++ b/students/1417442485/src/main/java/com/coderising/ood/srp/UserDataStore.java @@ -0,0 +1,15 @@ +package main.java.com.coderising.ood.srp; + +import java.util.List; + +public class UserDataStore { + + public static List getMailingList(String productId) throws Exception { + final String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productId +"' " + + "and send_mail=1 "; + + return DBUtil.query(sendMailQuery); + } + +} diff --git a/students/1417442485/src/main/java/com/coderising/ood/srp/UserInfo.java b/students/1417442485/src/main/java/com/coderising/ood/srp/UserInfo.java new file mode 100644 index 0000000000..26272ef017 --- /dev/null +++ b/students/1417442485/src/main/java/com/coderising/ood/srp/UserInfo.java @@ -0,0 +1,11 @@ +package main.java.com.coderising.ood.srp; + +public class UserInfo { + final String name; + final String email; + + public UserInfo(final String name, final String email) { + this.name = name; + this.email = email; + } +} diff --git a/students/1417442485/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/1417442485/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/1417442485/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/1418243288/readme.md b/students/1418243288/readme.md new file mode 100644 index 0000000000..fcb796bdef --- /dev/null +++ b/students/1418243288/readme.md @@ -0,0 +1,5 @@ +测试下新上传的值 +#test + +#试试对不对# +public void main diff --git a/students/1425809544/ood-assignment/pom.xml b/students/1425809544/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/1425809544/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/config/Configuration.java b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/config/Configuration.java new file mode 100644 index 0000000000..a3f51236bc --- /dev/null +++ b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/config/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.config; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/config/ConfigurationKeys.java b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/config/ConfigurationKeys.java new file mode 100644 index 0000000000..e7c449f10c --- /dev/null +++ b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/config/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.config; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/file/product_promotion.txt b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/file/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/file/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/pojo/Email.java b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/pojo/Email.java new file mode 100644 index 0000000000..ed92dfec0b --- /dev/null +++ b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/pojo/Email.java @@ -0,0 +1,49 @@ +package com.coderising.ood.pojo; + +/** + * @author xyy + * @create 2017-06-19 9:44 + **/ +public class Email { + + + private String toAddress; + private String subject; + private String message; + + public Email() { + } + + public Email(String toAddress, String subject, String message) { + this.toAddress = toAddress; + this.subject = subject; + this.message = message; + } + + public String getToAddress() { + return toAddress; + } + + public Email setToAddress(String toAddress) { + this.toAddress = toAddress; + return this; + } + + public String getSubject() { + return subject; + } + + public Email setSubject(String subject) { + this.subject = subject; + return this; + } + + public String getMessage() { + return message; + } + + public Email setMessage(String message) { + this.message = message; + return this; + } +} diff --git a/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/pojo/EmailServiceConfig.java b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/pojo/EmailServiceConfig.java new file mode 100644 index 0000000000..091583b3ed --- /dev/null +++ b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/pojo/EmailServiceConfig.java @@ -0,0 +1,45 @@ +package com.coderising.ood.pojo; + +/** + * @author xyy + * @create 2017-06-19 10:00 + **/ +public class EmailServiceConfig { + + private String smtpHost; + private String altSmtpHost; + private String fromAddress; + + public EmailServiceConfig(String smtpHost, String altSmtpHost, String fromAddress) { + this.smtpHost = smtpHost; + this.altSmtpHost = altSmtpHost; + this.fromAddress = fromAddress; + } + + public String getSmtpHost() { + return smtpHost; + } + + public EmailServiceConfig setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + return this; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public EmailServiceConfig setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + return this; + } + + public String getFromAddress() { + return fromAddress; + } + + public EmailServiceConfig setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + return this; + } +} diff --git a/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/pojo/Product.java b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/pojo/Product.java new file mode 100644 index 0000000000..f869bf1f12 --- /dev/null +++ b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/pojo/Product.java @@ -0,0 +1,37 @@ +package com.coderising.ood.pojo; + +/** + * 产品类 + * + * @author xyy + * @create 2017-06-19 9:30 + **/ +public class Product { + + + private String productID; + private String productDesc; + + + + + + + public String getProductID() { + return productID; + } + + public Product setProductID(String productID) { + this.productID = productID; + return this; + } + + public String getProductDesc() { + return productDesc; + } + + public Product setProductDesc(String productDesc) { + this.productDesc = productDesc; + return this; + } +} diff --git a/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/pojo/User.java b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/pojo/User.java new file mode 100644 index 0000000000..69975f6cbd --- /dev/null +++ b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/pojo/User.java @@ -0,0 +1,29 @@ +package com.coderising.ood.pojo; + +/** + * @author xyy + * @create 2017-06-19 9:48 + **/ +public class User { + + private String name; + private String email; + + public String getName() { + return name; + } + + public User setName(String name) { + this.name = name; + return this; + } + + public String getEmail() { + return email; + } + + public User setEmail(String email) { + this.email = email; + return this; + } +} diff --git a/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/service/EmailService.java b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/service/EmailService.java new file mode 100644 index 0000000000..2fece21ec2 --- /dev/null +++ b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/service/EmailService.java @@ -0,0 +1,55 @@ +package com.coderising.ood.service; + +import com.coderising.ood.pojo.Email; +import com.coderising.ood.pojo.EmailServiceConfig; +import com.coderising.ood.pojo.Product; +import com.coderising.ood.pojo.User; + +import java.io.IOException; + +/** + * @author xyy + * @create 2017-06-19 9:44 + **/ +public class EmailService { + + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + + public static Email configureEMail(User user, Product product) throws IOException { + String toAddress = user.getEmail(); + String name = ""; + if (toAddress.length() > 0) { + name = user.getName(); + } + String subject = "您关注的产品降价了"; + String message = "尊敬的 " + name + ", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!"; + Email email = new Email(toAddress, subject, message); + return email; + } + + public static void sendEmail(EmailServiceConfig emailServiceConfig, Email email, boolean debug) { + try { + if (email.getToAddress().length() > 0) { + sendEmail(email.getToAddress(), emailServiceConfig.getFromAddress(), email.getSubject(), email.getMessage(), emailServiceConfig.getSmtpHost(), debug); + } + } catch (Exception e) { + try { + sendEmail(email.getToAddress(), emailServiceConfig.getFromAddress(), email.getSubject(), email.getMessage(), emailServiceConfig.getAltSmtpHost(), debug); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } +} diff --git a/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/service/ProductService.java b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/service/ProductService.java new file mode 100644 index 0000000000..ccacef7bce --- /dev/null +++ b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/service/ProductService.java @@ -0,0 +1,52 @@ +package com.coderising.ood.service; + +import com.coderising.ood.pojo.Product; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * @author xyy + * @create 2017-06-19 9:34 + **/ +public class ProductService { + + + public static List getAllProductFromFile(File file) throws IOException { + List productList = new ArrayList(); + BufferedReader br = null; + + try { + + br = new BufferedReader(new FileReader(file)); + String temp = null; + while ((temp = br.readLine()) != null) { + String[] data = temp.split(" "); + Product product = new Product(); + product.setProductID(data[0]); + product.setProductDesc(data[1]); + System.out.println("产品ID = " + product.getProductID() + "\n"); + System.out.println("产品描述 = " + product.getProductDesc() + "\n"); + productList.add(product); + } + + return productList; + + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + return null; + } + +} diff --git a/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/service/PromotionMail.java b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/service/PromotionMail.java new file mode 100644 index 0000000000..f89aff500a --- /dev/null +++ b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/service/PromotionMail.java @@ -0,0 +1,63 @@ +package com.coderising.ood.service; + +import com.coderising.ood.config.Configuration; +import com.coderising.ood.config.ConfigurationKeys; +import com.coderising.ood.pojo.Email; +import com.coderising.ood.pojo.EmailServiceConfig; +import com.coderising.ood.pojo.Product; +import com.coderising.ood.pojo.User; + +import java.io.File; +import java.util.List; + +public class PromotionMail { + + public static void main(String[] args) throws Exception { + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + File file = new File("D:\\product_promotion.txt"); + //1.获得产品信息 + ProductService productService = new ProductService(); + List productList = productService.getAllProductFromFile(file); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(productList, emailDebug); + } + + + + public PromotionMail(List productList, boolean mailDebug) throws Exception { + //2.邮件服务器配置 + Configuration config = new Configuration(); + EmailServiceConfig emailServiceConfig = new EmailServiceConfig(config.getProperty(ConfigurationKeys.SMTP_SERVER), config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER), config.getProperty(ConfigurationKeys.EMAIL_ADMIN)); + //3.发送邮件 + sendEMails(mailDebug, productList, emailServiceConfig); + + } + + + public void sendEMails(boolean debug, List productList, EmailServiceConfig emailServiceConfig) throws Exception { + System.out.println("开始发送邮件"); + if (productList != null) { + for (Product product : productList) { + List userList = UserService.getSendEmailUser(product); + if (null != userList && userList.size() > 0) { + for (User user : userList) { + Email email = EmailService.configureEMail((user), product); + if (email.getToAddress().length() > 0) { + EmailService.sendEmail(emailServiceConfig,email,debug); + } + } + } + } + + } else { + System.out.println("没有邮件发送"); + + } + + } + + +} + + diff --git a/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/service/UserService.java b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/service/UserService.java new file mode 100644 index 0000000000..a7c6d8fe38 --- /dev/null +++ b/students/1425809544/ood-assignment/src/main/java/com/coderising/ood/service/UserService.java @@ -0,0 +1,44 @@ +package com.coderising.ood.service; + +import com.coderising.ood.pojo.Product; +import com.coderising.ood.pojo.User; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author xyy + * @create 2017-06-19 9:48 + **/ +public class UserService { + + + public static List getSendEmailUser(Product product) throws Exception { + + + setLoadQuery(product); + + List userList = new ArrayList(); + + for (int i = 0; i < 3; i++) { + User user = new User(); + user.setName("user" + i); + user.setEmail(user.getName() + "@qq.com"); + userList.add(user); + } + return userList; + } + + + //通过产品id获取关注了产品的用户 + public static void setLoadQuery(Product product) throws Exception { + + String sql = "Select name from subscriptions " + + "where product_id= '" + product.getProductID() + "' " + + "and send_mail=1 "; + + System.out.println("loadQuery set"); + } + + +} diff --git a/students/1753179526/readme.md b/students/1753179526/readme.md new file mode 100644 index 0000000000..0eb59149a8 --- /dev/null +++ b/students/1753179526/readme.md @@ -0,0 +1,5 @@ +Test git commit. push-wary + +第二次提交内容,更改编码问题。 + +增加new line 测试命令行 \ No newline at end of file diff --git a/students/247565311/week00/Configuration.java b/students/247565311/week00/Configuration.java new file mode 100644 index 0000000000..66f989efd0 --- /dev/null +++ b/students/247565311/week00/Configuration.java @@ -0,0 +1,19 @@ +package week00; +import java.util.HashMap; +import java.util.Map; +public class Configuration { + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * Ӧôļ ΪֱӴһmap ȥ + * @param key + * @return + */ + public String getProperty(String key) { + return configurations.get(key); + } +} diff --git a/students/247565311/week00/ConfigurationKeys.java b/students/247565311/week00/ConfigurationKeys.java new file mode 100644 index 0000000000..10da9ce88c --- /dev/null +++ b/students/247565311/week00/ConfigurationKeys.java @@ -0,0 +1,6 @@ +package week00; +public class ConfigurationKeys { + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; +} diff --git a/students/247565311/week00/DBUtil.java b/students/247565311/week00/DBUtil.java new file mode 100644 index 0000000000..903bdef223 --- /dev/null +++ b/students/247565311/week00/DBUtil.java @@ -0,0 +1,21 @@ +package week00; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +public class DBUtil { + /** + * Ӧôݿ ǼΪֱɡ + * @param sql + * @return + */ + public static List> query(String sql){ + List> userList = new ArrayList>(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + return userList; + } +} diff --git a/students/247565311/week00/MailUtil.java b/students/247565311/week00/MailUtil.java new file mode 100644 index 0000000000..01e6e32fc8 --- /dev/null +++ b/students/247565311/week00/MailUtil.java @@ -0,0 +1,14 @@ +package week00; + +public class MailUtil { + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //װһʼ + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + } +} diff --git a/students/247565311/week00/PromotionMail.java b/students/247565311/week00/PromotionMail.java new file mode 100644 index 0000000000..a1e079f571 --- /dev/null +++ b/students/247565311/week00/PromotionMail.java @@ -0,0 +1,136 @@ +package week00; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +class ProductMessage{ + public String productID; + public String productDesc; + public ProductMessage(String id,String desc){ + productID = id; + productDesc = desc; + } +} +class ProductMessageIter{ + BufferedReader reader = null; + boolean loadFileSuccess = false,readFinished = false; + public ProductMessageIter(File socFile){ + try { + reader = new BufferedReader(new FileReader(socFile)); + } catch (FileNotFoundException e) { + e.printStackTrace(); + return; + } + loadFileSuccess = true; + } + public boolean hasNext(){ + if(!loadFileSuccess || readFinished) return false; + try { + reader.mark(10); + String lineMsg = reader.readLine(); + reader.reset(); + if(lineMsg.equals("")) { + readFinished = true; + reader.close(); + return false; + } + } catch (IOException e) { + e.printStackTrace(); + } + return true; + } + public ProductMessage next(){ + String lineMsg=null; + try { + lineMsg = reader.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + if(lineMsg == null) return null; + String [] msgs = lineMsg.split(" "); + ProductMessage msg = new ProductMessage(msgs[0],msgs[1]); + System.out.println("ƷID = " + msgs[0]); + System.out.println("Ʒ = " + msgs[1]); + return msg; + } +} +class EMailSender{ + String fromAddress = null; + String smtpHost = null; + String altSmtpHost = null; + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + public EMailSender(){ + Configuration config = new Configuration(); + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + // ʼݣɹɻᷢʼ + public void configureAndSendEMail(HashMap userInfo,ProductMessage prdMsg,boolean debug) throws IOException + { + String toAddress = "",subject = "",message = ""; + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) { + String name = (String) userInfo.get(NAME_KEY); + subject = "עIJƷ"; + message = "𾴵 "+name+", עIJƷ " + prdMsg.productDesc + " ˣӭ!" ; + System.out.println("ʼʼ"); + sendEMail(toAddress,subject,message,debug); + }else { + System.out.println("ûʼ"); + } + } + // ֪ͨʼ + void sendEMail(String toAddress,String subject,String message,boolean debug) throws IOException + { + boolean sendSucceed = false; + try + { + if (toAddress.length() > 0){ + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + sendSucceed = true; + } + } + catch (Exception e) {} + if(!sendSucceed){ + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + } catch (Exception e2) + { + System.out.println("ͨ SMTPʼʧ: " + e2.getMessage()); + } + } + } +} +public class PromotionMail { + public static void main(String[] args) throws Exception { + File f = new File("J:\\gitstore\\coding2017\\students\\247565311\\week00\\product_promotion.txt"); + boolean emailDebug = false; + PromotionMail pe = new PromotionMail(f, emailDebug); + } + // ̿ + public PromotionMail(File file, boolean mailDebug) throws Exception { + ProductMessageIter iter = new ProductMessageIter(file);//ȡļ ļֻһÿո P8756 iPhone8 + while(iter.hasNext()){ + ProductMessage prdMsg = iter.next(); + List> userInfos = loadMailingList(prdMsg); + for(HashMap user : userInfos){ + new EMailSender().configureAndSendEMail(user,prdMsg,mailDebug); + } + } + } + // ȡûб + protected List> loadMailingList(ProductMessage prdMsg) throws Exception { + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + prdMsg.productID +"' " + + "and send_mail=1 "; + System.out.println("ûб..."); + return DBUtil.query(sendMailQuery); + } +} diff --git a/students/247565311/week00/product_promotion.txt b/students/247565311/week00/product_promotion.txt new file mode 100644 index 0000000000..e98aea9f01 --- /dev/null +++ b/students/247565311/week00/product_promotion.txt @@ -0,0 +1,5 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 + diff --git a/students/250103158/data-structure/answer/pom.xml b/students/250103158/data-structure/answer/pom.xml new file mode 100644 index 0000000000..ac6ba882df --- /dev/null +++ b/students/250103158/data-structure/answer/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ds-answer + 0.0.1-SNAPSHOT + jar + + ds-answer + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/250103158/data-structure/answer/src/main/java/com/coderising/download/DownloadThread.java b/students/250103158/data-structure/answer/src/main/java/com/coderising/download/DownloadThread.java new file mode 100644 index 0000000000..900a3ad358 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coderising/download/DownloadThread.java @@ -0,0 +1,20 @@ +package com.coderising.download; + +import com.coderising.download.api.Connection; + +public class DownloadThread extends Thread{ + + Connection conn; + int startPos; + int endPos; + + public DownloadThread( Connection conn, int startPos, int endPos){ + + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + } + public void run(){ + + } +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coderising/download/FileDownloader.java b/students/250103158/data-structure/answer/src/main/java/com/coderising/download/FileDownloader.java new file mode 100644 index 0000000000..c3c8a3f27d --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coderising/download/FileDownloader.java @@ -0,0 +1,73 @@ +package com.coderising.download; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionException; +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; + + +public class FileDownloader { + + String url; + + DownloadListener listener; + + ConnectionManager cm; + + + public FileDownloader(String _url) { + this.url = _url; + + } + + public void execute(){ + // 在这里实现你的代码, 注意: 需要用多线程实现下载 + // 这个类依赖于其他几个接口, 你需要写这几个接口的实现代码 + // (1) ConnectionManager , 可以打开一个连接,通过Connection可以读取其中的一段(用startPos, endPos来指定) + // (2) DownloadListener, 由于是多线程下载, 调用这个类的客户端不知道什么时候结束,所以你需要实现当所有 + // 线程都执行完以后, 调用listener的notifiedFinished方法, 这样客户端就能收到通知。 + // 具体的实现思路: + // 1. 需要调用ConnectionManager的open方法打开连接, 然后通过Connection.getContentLength方法获得文件的长度 + // 2. 至少启动3个线程下载, 注意每个线程需要先调用ConnectionManager的open方法 + // 然后调用read方法, read方法中有读取文件的开始位置和结束位置的参数, 返回值是byte[]数组 + // 3. 把byte数组写入到文件中 + // 4. 所有的线程都下载完成以后, 需要调用listener的notifiedFinished方法 + + // 下面的代码是示例代码, 也就是说只有一个线程, 你需要改造成多线程的。 + Connection conn = null; + try { + + conn = cm.open(this.url); + + int length = conn.getContentLength(); + + new DownloadThread(conn,0,length-1).start(); + + } catch (ConnectionException e) { + e.printStackTrace(); + }finally{ + if(conn != null){ + conn.close(); + } + } + + + + + } + + public void setListener(DownloadListener listener) { + this.listener = listener; + } + + + + public void setConnectionManager(ConnectionManager ucm){ + this.cm = ucm; + } + + public DownloadListener getListener(){ + return this.listener; + } + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coderising/download/FileDownloaderTest.java b/students/250103158/data-structure/answer/src/main/java/com/coderising/download/FileDownloaderTest.java new file mode 100644 index 0000000000..4ff7f46ae0 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coderising/download/FileDownloaderTest.java @@ -0,0 +1,59 @@ +package com.coderising.download; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; +import com.coderising.download.impl.ConnectionManagerImpl; + +public class FileDownloaderTest { + boolean downloadFinished = false; + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testDownload() { + + String url = "http://localhost:8080/test.jpg"; + + FileDownloader downloader = new FileDownloader(url); + + + ConnectionManager cm = new ConnectionManagerImpl(); + downloader.setConnectionManager(cm); + + downloader.setListener(new DownloadListener() { + @Override + public void notifyFinished() { + downloadFinished = true; + } + + }); + + + downloader.execute(); + + // 等待多线程下载程序执行完毕 + while (!downloadFinished) { + try { + System.out.println("还没有下载完成,休眠五秒"); + //休眠5秒 + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + System.out.println("下载完成!"); + + + + } + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coderising/download/api/Connection.java b/students/250103158/data-structure/answer/src/main/java/com/coderising/download/api/Connection.java new file mode 100644 index 0000000000..0957eaf7f4 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coderising/download/api/Connection.java @@ -0,0 +1,23 @@ +package com.coderising.download.api; + +import java.io.IOException; + +public interface Connection { + /** + * 给定开始和结束位置, 读取数据, 返回值是字节数组 + * @param startPos 开始位置, 从0开始 + * @param endPos 结束位置 + * @return + */ + public byte[] read(int startPos,int endPos) throws IOException; + /** + * 得到数据内容的长度 + * @return + */ + public int getContentLength(); + + /** + * 关闭连接 + */ + public void close(); +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coderising/download/api/ConnectionException.java b/students/250103158/data-structure/answer/src/main/java/com/coderising/download/api/ConnectionException.java new file mode 100644 index 0000000000..1551a80b3d --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coderising/download/api/ConnectionException.java @@ -0,0 +1,5 @@ +package com.coderising.download.api; + +public class ConnectionException extends Exception { + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coderising/download/api/ConnectionManager.java b/students/250103158/data-structure/answer/src/main/java/com/coderising/download/api/ConnectionManager.java new file mode 100644 index 0000000000..ce045393b1 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coderising/download/api/ConnectionManager.java @@ -0,0 +1,10 @@ +package com.coderising.download.api; + +public interface ConnectionManager { + /** + * 给定一个url , 打开一个连接 + * @param url + * @return + */ + public Connection open(String url) throws ConnectionException; +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coderising/download/api/DownloadListener.java b/students/250103158/data-structure/answer/src/main/java/com/coderising/download/api/DownloadListener.java new file mode 100644 index 0000000000..bf9807b307 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coderising/download/api/DownloadListener.java @@ -0,0 +1,5 @@ +package com.coderising.download.api; + +public interface DownloadListener { + public void notifyFinished(); +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coderising/download/impl/ConnectionImpl.java b/students/250103158/data-structure/answer/src/main/java/com/coderising/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..36a9d2ce15 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coderising/download/impl/ConnectionImpl.java @@ -0,0 +1,27 @@ +package com.coderising.download.impl; + +import java.io.IOException; + +import com.coderising.download.api.Connection; + +public class ConnectionImpl implements Connection{ + + @Override + public byte[] read(int startPos, int endPos) throws IOException { + + return null; + } + + @Override + public int getContentLength() { + + return 0; + } + + @Override + public void close() { + + + } + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coderising/download/impl/ConnectionManagerImpl.java b/students/250103158/data-structure/answer/src/main/java/com/coderising/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..172371dd55 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coderising/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,15 @@ +package com.coderising.download.impl; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionException; +import com.coderising.download.api.ConnectionManager; + +public class ConnectionManagerImpl implements ConnectionManager { + + @Override + public Connection open(String url) throws ConnectionException { + + return null; + } + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coderising/litestruts/LoginAction.java b/students/250103158/data-structure/answer/src/main/java/com/coderising/litestruts/LoginAction.java new file mode 100644 index 0000000000..dcdbe226ed --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coderising/litestruts/LoginAction.java @@ -0,0 +1,39 @@ +package com.coderising.litestruts; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * @author liuxin + * + */ +public class LoginAction{ + private String name ; + private String password; + private String message; + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String execute(){ + if("test".equals(name) && "1234".equals(password)){ + this.message = "login successful"; + return "success"; + } + this.message = "login failed,please check your user/pwd"; + return "fail"; + } + + public void setName(String name){ + this.name = name; + } + public void setPassword(String password){ + this.password = password; + } + public String getMessage(){ + return this.message; + } +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coderising/litestruts/Struts.java b/students/250103158/data-structure/answer/src/main/java/com/coderising/litestruts/Struts.java new file mode 100644 index 0000000000..85e2e22de3 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coderising/litestruts/Struts.java @@ -0,0 +1,34 @@ +package com.coderising.litestruts; + +import java.util.Map; + + + +public class Struts { + + public static View runAction(String actionName, Map parameters) { + + /* + + 0. 读取配置文件struts.xml + + 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + ("name"="test" , "password"="1234") , + 那就应该调用 setName和setPassword方法 + + 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + + 3. 通过反射找到对象的所有getter方法(例如 getMessage), + 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + 放到View对象的parameters + + 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + 放到View对象的jsp字段中。 + + */ + + return null; + } + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coderising/litestruts/StrutsTest.java b/students/250103158/data-structure/answer/src/main/java/com/coderising/litestruts/StrutsTest.java new file mode 100644 index 0000000000..b8c81faf3c --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coderising/litestruts/StrutsTest.java @@ -0,0 +1,43 @@ +package com.coderising.litestruts; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + + + + + +public class StrutsTest { + + @Test + public void testLoginActionSuccess() { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coderising/litestruts/View.java b/students/250103158/data-structure/answer/src/main/java/com/coderising/litestruts/View.java new file mode 100644 index 0000000000..07df2a5dab --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coderising/litestruts/View.java @@ -0,0 +1,23 @@ +package com.coderising.litestruts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coderising/litestruts/struts.xml b/students/250103158/data-structure/answer/src/main/java/com/coderising/litestruts/struts.xml new file mode 100644 index 0000000000..e5d9aebba8 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coderising/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/Iterator.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/Iterator.java new file mode 100644 index 0000000000..06ef6311b2 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/Iterator.java @@ -0,0 +1,7 @@ +package com.coding.basic; + +public interface Iterator { + public boolean hasNext(); + public Object next(); + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/List.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/List.java new file mode 100644 index 0000000000..10d13b5832 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/List.java @@ -0,0 +1,9 @@ +package com.coding.basic; + +public interface List { + public void add(Object o); + public void add(int index, Object o); + public Object get(int index); + public Object remove(int index); + public int size(); +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/array/ArrayList.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/array/ArrayList.java new file mode 100644 index 0000000000..4576c016af --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/array/ArrayList.java @@ -0,0 +1,35 @@ +package com.coding.basic.array; + +import com.coding.basic.Iterator; +import com.coding.basic.List; + +public class ArrayList implements List { + + private int size = 0; + + private Object[] elementData = new Object[100]; + + public void add(Object o){ + + } + public void add(int index, Object o){ + + } + + public Object get(int index){ + return null; + } + + public Object remove(int index){ + return null; + } + + public int size(){ + return -1; + } + + public Iterator iterator(){ + return null; + } + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/array/ArrayUtil.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/array/ArrayUtil.java new file mode 100644 index 0000000000..45740e6d57 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/array/ArrayUtil.java @@ -0,0 +1,96 @@ +package com.coding.basic.array; + +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 + 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * @param origin + * @return + */ + public void reverseArray(int[] origin){ + + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: + * {1,3,4,5,6,6,5,4,7,6,7,5} + * @param oldArray + * @return + */ + + public int[] removeZero(int[] oldArray){ + return null; + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 + * 例如 a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * @param array1 + * @param array2 + * @return + */ + + public int[] merge(int[] array1, int[] array2){ + return null; + } + /** + * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size + * 注意,老数组的元素在新数组中需要保持 + * 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 + * [2,3,6,0,0,0] + * @param oldArray + * @param size + * @return + */ + public int[] grow(int [] oldArray, int size){ + return null; + } + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 + * 例如, max = 15 , 则返回的数组应该为 [1,1,2,3,5,8,13] + * max = 1, 则返回空数组 [] + * @param max + * @return + */ + public int[] fibonacci(int max){ + return null; + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public int[] getPrimes(int max){ + return null; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public int[] getPerfectNumbers(int max){ + return null; + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * @param array + * @param s + * @return + */ + public String join(int[] array, String seperator){ + return null; + } + + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/linklist/LRUPageFrame.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/linklist/LRUPageFrame.java new file mode 100644 index 0000000000..24b9d8b155 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/linklist/LRUPageFrame.java @@ -0,0 +1,164 @@ +package com.coding.basic.linklist; + + +public class LRUPageFrame { + + private static class Node { + + Node prev; + Node next; + int pageNum; + + Node() { + } + } + + private int capacity; + + private int currentSize; + private Node first;// 链表头 + private Node last;// 链表尾 + + + public LRUPageFrame(int capacity) { + this.currentSize = 0; + this.capacity = capacity; + + } + + /** + * 获取缓存中对象 + * + * @param key + * @return + */ + public void access(int pageNum) { + + Node node = find(pageNum); + //在该队列中存在, 则提到队列头 + if (node != null) { + + moveExistingNodeToHead(node); + + } else{ + + node = new Node(); + node.pageNum = pageNum; + + // 缓存容器是否已经超过大小. + if (currentSize >= capacity) { + removeLast(); + + } + + addNewNodetoHead(node); + + + + + } + } + + private void addNewNodetoHead(Node node) { + + if(isEmpty()){ + + node.prev = null; + node.next = null; + first = node; + last = node; + + } else{ + node.prev = null; + node.next = first; + first.prev = node; + first = node; + } + this.currentSize ++; + } + + private Node find(int data){ + + Node node = first; + while(node != null){ + if(node.pageNum == data){ + return node; + } + node = node.next; + } + return null; + + } + + + + + + + /** + * 删除链表尾部节点 表示 删除最少使用的缓存对象 + */ + private void removeLast() { + Node prev = last.prev; + prev.next = null; + last.prev = null; + last = prev; + this.currentSize --; + } + + /** + * 移动到链表头,表示这个节点是最新使用过的 + * + * @param node + */ + private void moveExistingNodeToHead(Node node) { + + if (node == first) { + + return; + } + else if(node == last){ + //当前节点是链表尾, 需要放到链表头 + Node prevNode = node.prev; + prevNode.next = null; + last.prev = null; + last = prevNode; + + } else{ + //node 在链表的中间, 把node 的前后节点连接起来 + Node prevNode = node.prev; + prevNode.next = node.next; + + Node nextNode = node.next; + nextNode.prev = prevNode; + + + } + + node.prev = null; + node.next = first; + first.prev = node; + first = node; + + } + private boolean isEmpty(){ + return (first == null) && (last == null); + } + + public String toString(){ + StringBuilder buffer = new StringBuilder(); + Node node = first; + while(node != null){ + buffer.append(node.pageNum); + + node = node.next; + if(node != null){ + buffer.append(","); + } + } + return buffer.toString(); + } + + + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/linklist/LRUPageFrameTest.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/linklist/LRUPageFrameTest.java new file mode 100644 index 0000000000..7fd72fc2b4 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/linklist/LRUPageFrameTest.java @@ -0,0 +1,34 @@ +package com.coding.basic.linklist; + +import org.junit.Assert; + +import org.junit.Test; + + +public class LRUPageFrameTest { + + @Test + public void testAccess() { + LRUPageFrame frame = new LRUPageFrame(3); + frame.access(7); + frame.access(0); + frame.access(1); + Assert.assertEquals("1,0,7", frame.toString()); + frame.access(2); + Assert.assertEquals("2,1,0", frame.toString()); + frame.access(0); + Assert.assertEquals("0,2,1", frame.toString()); + frame.access(0); + Assert.assertEquals("0,2,1", frame.toString()); + frame.access(3); + Assert.assertEquals("3,0,2", frame.toString()); + frame.access(0); + Assert.assertEquals("0,3,2", frame.toString()); + frame.access(4); + Assert.assertEquals("4,0,3", frame.toString()); + frame.access(5); + Assert.assertEquals("5,4,0", frame.toString()); + + } + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/linklist/LinkedList.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/linklist/LinkedList.java new file mode 100644 index 0000000000..f4c7556a2e --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/linklist/LinkedList.java @@ -0,0 +1,125 @@ +package com.coding.basic.linklist; + +import com.coding.basic.Iterator; +import com.coding.basic.List; + +public class LinkedList implements List { + + private Node head; + + public void add(Object o){ + + } + public void add(int index , Object o){ + + } + public Object get(int index){ + return null; + } + public Object remove(int index){ + return null; + } + + public int size(){ + return -1; + } + + public void addFirst(Object o){ + + } + public void addLast(Object o){ + + } + public Object removeFirst(){ + return null; + } + public Object removeLast(){ + return null; + } + public Iterator iterator(){ + return null; + } + + + private static class Node{ + Object data; + Node next; + + } + + /** + * 把该链表逆置 + * 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + + */ + public void removeFirstHalf(){ + + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * @param i + * @param length + */ + public void remove(int i, int length){ + + } + /** + * 假定当前链表和listB均包含已升序排列的整数 + * 从当前链表中取出那些listB所指定的元素 + * 例如当前链表 = 11->101->201->301->401->501->601->701 + * listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + * @param list + */ + public int[] getElements(LinkedList list){ + return null; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 从当前链表中中删除在listB中出现的元素 + + * @param list + */ + + public void subtract(LinkedList list){ + + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues(){ + + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * @param min + * @param max + */ + public void removeRange(int min, int max){ + + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * @param list + */ + public LinkedList intersection( LinkedList list){ + return null; + } +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/queue/CircleQueue.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/queue/CircleQueue.java new file mode 100644 index 0000000000..f169d5f8e4 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/queue/CircleQueue.java @@ -0,0 +1,47 @@ +package com.coding.basic.queue; + +public class CircleQueue { + + //用数组来保存循环队列的元素 + private Object[] elementData ; + int size = 0; + //队头 + private int front = 0; + //队尾 + private int rear = 0; + + public CircleQueue(int capacity){ + elementData = new Object[capacity]; + } + public boolean isEmpty() { + return (front == rear) && !isFull(); + + } + + public boolean isFull(){ + return size == elementData.length; + } + public int size() { + return size; + } + + public void enQueue(E data) { + if(isFull()){ + throw new RuntimeException("The queue is full"); + } + rear = (rear+1) % elementData.length; + elementData[rear++] = data; + size++; + } + + public E deQueue() { + if(isEmpty()){ + throw new RuntimeException("The queue is empty"); + } + E data = (E)elementData[front]; + elementData[front] = null; + front = (front+1) % elementData.length; + size --; + return data; + } +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/queue/CircleQueueTest.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/queue/CircleQueueTest.java new file mode 100644 index 0000000000..7307eb77d4 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/queue/CircleQueueTest.java @@ -0,0 +1,44 @@ +package com.coding.basic.queue; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class CircleQueueTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void test() { + CircleQueue queue = new CircleQueue(5); + Assert.assertTrue(queue.isEmpty()); + Assert.assertFalse(queue.isFull()); + + queue.enQueue("a"); + queue.enQueue("b"); + queue.enQueue("c"); + queue.enQueue("d"); + queue.enQueue("e"); + + Assert.assertTrue(queue.isFull()); + Assert.assertFalse(queue.isEmpty()); + Assert.assertEquals(5, queue.size()); + + Assert.assertEquals("a", queue.deQueue()); + Assert.assertEquals("b", queue.deQueue()); + Assert.assertEquals("c", queue.deQueue()); + Assert.assertEquals("d", queue.deQueue()); + Assert.assertEquals("e", queue.deQueue()); + + } + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/queue/Josephus.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/queue/Josephus.java new file mode 100644 index 0000000000..36ec615d36 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/queue/Josephus.java @@ -0,0 +1,39 @@ +package com.coding.basic.queue; + +import java.util.ArrayList; +import java.util.List; + +/** + * 用Queue来实现Josephus问题 + * 在这个古老的问题当中, N个深陷绝境的人一致同意用这种方式减少生存人数: N个人围成一圈(位置记为0到N-1), 并且从第一个人报数, 报到M的人会被杀死, 直到最后一个人留下来 + * @author liuxin + * + */ +public class Josephus { + + public static List execute(int n, int m){ + + Queue queue = new Queue(); + for (int i = 0; i < n; i++){ + queue.enQueue(i); + } + + List result = new ArrayList(); + int i = 0; + + while (!queue.isEmpty()) { + + int x = queue.deQueue(); + + if (++i % m == 0){ + result.add(x); + } else{ + queue.enQueue(x); + } + } + + + return result; + } + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/queue/JosephusTest.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/queue/JosephusTest.java new file mode 100644 index 0000000000..7d90318b51 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/queue/JosephusTest.java @@ -0,0 +1,27 @@ +package com.coding.basic.queue; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class JosephusTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testExecute() { + + Assert.assertEquals("[1, 3, 5, 0, 4, 2, 6]", Josephus.execute(7, 2).toString()); + + } + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/queue/Queue.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/queue/Queue.java new file mode 100644 index 0000000000..c4c4b7325e --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/queue/Queue.java @@ -0,0 +1,61 @@ +package com.coding.basic.queue; + +import java.util.NoSuchElementException; + +public class Queue { + private Node first; + private Node last; + private int size; + + + private static class Node { + private E item; + private Node next; + } + + + public Queue() { + first = null; + last = null; + size = 0; + } + + + public boolean isEmpty() { + return first == null; + } + + public int size() { + return size; + } + + + + public void enQueue(E data) { + Node oldlast = last; + last = new Node(); + last.item = data; + last.next = null; + if (isEmpty()) { + first = last; + } + else{ + oldlast.next = last; + } + size++; + } + + public E deQueue() { + if (isEmpty()) { + throw new NoSuchElementException("Queue underflow"); + } + E item = first.item; + first = first.next; + size--; + if (isEmpty()) { + last = null; + } + return item; + } + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/queue/QueueWithTwoStacks.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/queue/QueueWithTwoStacks.java new file mode 100644 index 0000000000..bc97df0800 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/queue/QueueWithTwoStacks.java @@ -0,0 +1,55 @@ +package com.coding.basic.queue; + +import java.util.NoSuchElementException; +import java.util.Stack; + +public class QueueWithTwoStacks { + private Stack stack1; + private Stack stack2; + + + public QueueWithTwoStacks() { + stack1 = new Stack(); + stack2 = new Stack(); + } + + + private void moveStack1ToStack2() { + while (!stack1.isEmpty()){ + stack2.push(stack1.pop()); + } + + } + + + public boolean isEmpty() { + return stack1.isEmpty() && stack2.isEmpty(); + } + + + + public int size() { + return stack1.size() + stack2.size(); + } + + + + public void enQueue(E item) { + stack1.push(item); + } + + public E deQueue() { + if (isEmpty()) { + throw new NoSuchElementException("Queue is empty"); + } + if (stack2.isEmpty()) { + moveStack1ToStack2(); + } + + return stack2.pop(); + } + + + + } + diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/QuickMinStack.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/QuickMinStack.java new file mode 100644 index 0000000000..faf2644ab1 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/QuickMinStack.java @@ -0,0 +1,44 @@ +package com.coding.basic.stack; + +import java.util.Stack; +/** + * 设计一个栈,支持栈的push和pop操作,以及第三种操作findMin, 它返回改数据结构中的最小元素 + * finMin操作最坏的情形下时间复杂度应该是O(1) , 简单来讲,操作一次就可以得到最小值 + * @author liuxin + * + */ +public class QuickMinStack { + + private Stack normalStack = new Stack(); + private Stack minNumStack = new Stack(); + + public void push(int data){ + + normalStack.push(data); + + if(minNumStack.isEmpty()){ + minNumStack.push(data); + } else{ + if(minNumStack.peek() >= data) { + minNumStack.push(data); + } + } + + } + public int pop(){ + if(normalStack.isEmpty()){ + throw new RuntimeException("the stack is empty"); + } + int value = normalStack.pop(); + if(value == minNumStack.peek()){ + minNumStack.pop(); + } + return value; + } + public int findMin(){ + if(minNumStack.isEmpty()){ + throw new RuntimeException("the stack is empty"); + } + return minNumStack.peek(); + } +} \ No newline at end of file diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/QuickMinStackTest.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/QuickMinStackTest.java new file mode 100644 index 0000000000..efe41a9f8f --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/QuickMinStackTest.java @@ -0,0 +1,39 @@ +package com.coding.basic.stack; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + +public class QuickMinStackTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void test() { + QuickMinStack stack = new QuickMinStack(); + stack.push(5); + Assert.assertEquals(5, stack.findMin()); + stack.push(6); + Assert.assertEquals(5, stack.findMin()); + stack.push(4); + Assert.assertEquals(4, stack.findMin()); + stack.push(4); + Assert.assertEquals(4, stack.findMin()); + + stack.pop(); + Assert.assertEquals(4, stack.findMin()); + stack.pop(); + Assert.assertEquals(5, stack.findMin()); + stack.pop(); + Assert.assertEquals(5, stack.findMin()); + } + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/Stack.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/Stack.java new file mode 100644 index 0000000000..fedb243604 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/Stack.java @@ -0,0 +1,24 @@ +package com.coding.basic.stack; + +import com.coding.basic.array.ArrayList; + +public class Stack { + private ArrayList elementData = new ArrayList(); + + public void push(Object o){ + } + + public Object pop(){ + return null; + } + + public Object peek(){ + return null; + } + public boolean isEmpty(){ + return false; + } + public int size(){ + return -1; + } +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/StackUtil.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/StackUtil.java new file mode 100644 index 0000000000..7c86d22fe7 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/StackUtil.java @@ -0,0 +1,168 @@ +package com.coding.basic.stack; +import java.util.Stack; +public class StackUtil { + + public static void bad_reverse(Stack s) { + if(s == null || s.isEmpty()){ + return; + } + Stack tmpStack = new Stack(); + while(!s.isEmpty()){ + tmpStack.push(s.pop()); + } + + s = tmpStack; + + } + + + + public static void reverse_247565311(Stack s){ + if(s == null || s.isEmpty()) { + return; + } + + int size = s.size(); + Stack tmpStack = new Stack(); + + for(int i=0;ii){ + tmpStack.push(s.pop()); + } + s.push(top); + while(tmpStack.size()>0){ + s.push(tmpStack.pop()); + } + } + } + + + + /** + * 假设栈中的元素是Integer, 从栈顶到栈底是 : 5,4,3,2,1 调用该方法后, 元素次序变为: 1,2,3,4,5 + * 注意:只能使用Stack的基本操作,即push,pop,peek,isEmpty, 可以使用另外一个栈来辅助 + */ + public static void reverse(Stack s) { + if(s == null || s.isEmpty()){ + return; + } + + Stack tmp = new Stack(); + while(!s.isEmpty()){ + tmp.push(s.pop()); + } + while(!tmp.isEmpty()){ + Integer top = tmp.pop(); + addToBottom(s,top); + } + + + } + public static void addToBottom(Stack s, Integer value){ + if(s.isEmpty()){ + s.push(value); + } else{ + Integer top = s.pop(); + addToBottom(s,value); + s.push(top); + } + + } + /** + * 删除栈中的某个元素 注意:只能使用Stack的基本操作,即push,pop,peek,isEmpty, 可以使用另外一个栈来辅助 + * + * @param o + */ + public static void remove(Stack s,Object o) { + if(s == null || s.isEmpty()){ + return; + } + Stack tmpStack = new Stack(); + + while(!s.isEmpty()){ + Object value = s.pop(); + if(!value.equals(o)){ + tmpStack.push(value); + } + } + + while(!tmpStack.isEmpty()){ + s.push(tmpStack.pop()); + } + } + + /** + * 从栈顶取得len个元素, 原来的栈中元素保持不变 + * 注意:只能使用Stack的基本操作,即push,pop,peek,isEmpty, 可以使用另外一个栈来辅助 + * @param len + * @return + */ + public static Object[] getTop(Stack s,int len) { + + if(s == null || s.isEmpty() || s.size() stack = new Stack(); + for(int i=0;i s = new Stack(); + s.push(1); + s.push(2); + s.push(3); + + StackUtil.addToBottom(s, 0); + + Assert.assertEquals("[0, 1, 2, 3]", s.toString()); + + } + @Test + public void testReverse() { + Stack s = new Stack(); + s.push(1); + s.push(2); + s.push(3); + s.push(4); + s.push(5); + Assert.assertEquals("[1, 2, 3, 4, 5]", s.toString()); + StackUtil.reverse(s); + Assert.assertEquals("[5, 4, 3, 2, 1]", s.toString()); + } + @Test + public void testReverse_247565311() { + Stack s = new Stack(); + s.push(1); + s.push(2); + s.push(3); + + Assert.assertEquals("[1, 2, 3]", s.toString()); + StackUtil.reverse_247565311(s); + Assert.assertEquals("[3, 2, 1]", s.toString()); + } + @Test + public void testRemove() { + Stack s = new Stack(); + s.push(1); + s.push(2); + s.push(3); + StackUtil.remove(s, 2); + Assert.assertEquals("[1, 3]", s.toString()); + } + + @Test + public void testGetTop() { + Stack s = new Stack(); + s.push(1); + s.push(2); + s.push(3); + s.push(4); + s.push(5); + { + Object[] values = StackUtil.getTop(s, 3); + Assert.assertEquals(5, values[0]); + Assert.assertEquals(4, values[1]); + Assert.assertEquals(3, values[2]); + } + } + + @Test + public void testIsValidPairs() { + Assert.assertTrue(StackUtil.isValidPairs("([e{d}f])")); + Assert.assertFalse(StackUtil.isValidPairs("([b{x]y})")); + } + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/StackWithTwoQueues.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/StackWithTwoQueues.java new file mode 100644 index 0000000000..7a58fbff56 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/StackWithTwoQueues.java @@ -0,0 +1,53 @@ +package com.coding.basic.stack; + +import java.util.ArrayDeque; +import java.util.Queue; + +public class StackWithTwoQueues { + Queue queue1 = new ArrayDeque<>(); + Queue queue2 = new ArrayDeque<>(); + + public void push(int data) { + //两个栈都为空时,优先考虑queue1 + if (queue1.isEmpty()&&queue2.isEmpty()) { + queue1.add(data); + return; + } + + if (queue1.isEmpty()) { + queue2.add(data); + return; + } + + if (queue2.isEmpty()) { + queue1.add(data); + return; + } + + } + + public int pop() { + + if (queue1.isEmpty()&&queue2.isEmpty()) { + throw new RuntimeException("stack is empty"); + } + + if (queue1.isEmpty()) { + while (queue2.size()>1) { + queue1.add(queue2.poll()); + } + return queue2.poll(); + } + + if (queue2.isEmpty()) { + while (queue1.size()>1) { + queue2.add(queue1.poll()); + } + return queue1.poll(); + } + + throw new RuntimeException("no queue is empty, this is not allowed"); + + + } +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/StackWithTwoQueuesTest.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/StackWithTwoQueuesTest.java new file mode 100644 index 0000000000..4541b1f040 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/StackWithTwoQueuesTest.java @@ -0,0 +1,36 @@ +package com.coding.basic.stack; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class StackWithTwoQueuesTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void test() { + StackWithTwoQueues stack = new StackWithTwoQueues(); + stack.push(1); + stack.push(2); + stack.push(3); + stack.push(4); + Assert.assertEquals(4, stack.pop()); + Assert.assertEquals(3, stack.pop()); + + stack.push(5); + Assert.assertEquals(5, stack.pop()); + Assert.assertEquals(2, stack.pop()); + Assert.assertEquals(1, stack.pop()); + } + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/Tail.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/Tail.java new file mode 100644 index 0000000000..7f30ce55c8 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/Tail.java @@ -0,0 +1,5 @@ +package com.coding.basic.stack; + +public class Tail { + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/TwoStackInOneArray.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/TwoStackInOneArray.java new file mode 100644 index 0000000000..a532fd6e6c --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/TwoStackInOneArray.java @@ -0,0 +1,117 @@ +package com.coding.basic.stack; + +import java.util.Arrays; + +/** + * 用一个数组实现两个栈 + * 将数组的起始位置看作是第一个栈的栈底,将数组的尾部看作第二个栈的栈底,压栈时,栈顶指针分别向中间移动,直到两栈顶指针相遇,则扩容。 + * @author liuxin + * + */ +public class TwoStackInOneArray { + private Object[] data = new Object[10]; + private int size; + private int top1, top2; + + public TwoStackInOneArray(int n){ + data = new Object[n]; + size = n; + top1 = -1; + top2 = data.length; + } + /** + * 向第一个栈中压入元素 + * @param o + */ + public void push1(Object o){ + ensureCapacity(); + data[++top1] = o; + } + /* + * 向第二个栈压入元素 + */ + public void push2(Object o){ + ensureCapacity(); + data[--top2] = o; + } + public void ensureCapacity(){ + if(top2-top1>1){ + return; + } else{ + + Object[] newArray = new Object[data.length*2]; + System.arraycopy(data, 0, newArray, 0, top1+1); + + int stack2Size = data.length-top2; + int newTop2 = newArray.length-stack2Size; + System.arraycopy(data, top2, newArray, newTop2, stack2Size); + + top2 = newTop2; + data = newArray; + } + } + /** + * 从第一个栈中弹出元素 + * @return + */ + public Object pop1(){ + if(top1 == -1){ + throw new RuntimeException("Stack1 is empty"); + } + Object o = data[top1]; + data[top1] = null; + top1--; + return o; + + } + /** + * 从第二个栈弹出元素 + * @return + */ + public Object pop2(){ + if(top2 == data.length){ + throw new RuntimeException("Stack2 is empty"); + } + Object o = data[top2]; + data[top2] = null; + top2++; + return o; + } + /** + * 获取第一个栈的栈顶元素 + * @return + */ + + public Object peek1(){ + if(top1 == -1){ + throw new RuntimeException("Stack1 is empty"); + } + return data[top1]; + } + + + /** + * 获取第二个栈的栈顶元素 + * @return + */ + + public Object peek2(){ + if(top2 == data.length){ + throw new RuntimeException("Stack2 is empty"); + } + return data[top2]; + } + + public Object[] stack1ToArray(){ + return Arrays.copyOf(data, top1+1); + } + public Object[] stack2ToArray(){ + int size = data.length-top2; + Object [] stack2Data = new Object[size]; + int j=0; + for(int i=data.length-1; i>=top2 ;i--){ + stack2Data[j++] = data[i]; + } + return stack2Data; + } +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/TwoStackInOneArrayTest.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/TwoStackInOneArrayTest.java new file mode 100644 index 0000000000..b743d422c6 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/TwoStackInOneArrayTest.java @@ -0,0 +1,65 @@ +package com.coding.basic.stack; + +import java.util.Arrays; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class TwoStackInOneArrayTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void test1() { + TwoStackInOneArray stack = new TwoStackInOneArray(10); + stack.push1(1); + stack.push1(2); + stack.push1(3); + stack.push1(4); + stack.push1(5); + + stack.push2(1); + stack.push2(2); + stack.push2(3); + stack.push2(4); + stack.push2(5); + + for(int i=1;i<=5;i++){ + Assert.assertEquals(stack.peek1(), stack.peek2()); + Assert.assertEquals(stack.pop1(), stack.pop2()); + } + + + } + @Test + public void test2() { + TwoStackInOneArray stack = new TwoStackInOneArray(5); + stack.push1(1); + stack.push1(2); + stack.push1(3); + stack.push1(4); + stack.push1(5); + stack.push1(6); + stack.push1(7); + + stack.push2(1); + stack.push2(2); + stack.push2(3); + stack.push2(4); + + + Assert.assertEquals("[1, 2, 3, 4, 5, 6, 7]",Arrays.toString(stack.stack1ToArray())); + Assert.assertEquals("[1, 2, 3, 4]",Arrays.toString(stack.stack2ToArray())); + } + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixExpr.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixExpr.java new file mode 100644 index 0000000000..cebef21fa3 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixExpr.java @@ -0,0 +1,72 @@ +package com.coding.basic.stack.expr; + +import java.util.List; +import java.util.Stack; + + +public class InfixExpr { + String expr = null; + + public InfixExpr(String expr) { + this.expr = expr; + } + + public float evaluate() { + + + TokenParser parser = new TokenParser(); + List tokens = parser.parse(this.expr); + + + Stack opStack = new Stack<>(); + Stack numStack = new Stack<>(); + + for(Token token : tokens){ + + if (token.isOperator()){ + + while(!opStack.isEmpty() + && !token.hasHigherPriority(opStack.peek())){ + Token prevOperator = opStack.pop(); + Float f2 = numStack.pop(); + Float f1 = numStack.pop(); + Float result = calculate(prevOperator.toString(), f1,f2); + numStack.push(result); + + } + opStack.push(token); + } + if(token.isNumber()){ + numStack.push(new Float(token.getIntValue())); + } + } + + while(!opStack.isEmpty()){ + Token token = opStack.pop(); + Float f2 = numStack.pop(); + Float f1 = numStack.pop(); + numStack.push(calculate(token.toString(), f1,f2)); + } + + + return numStack.pop().floatValue(); + } + private Float calculate(String op, Float f1, Float f2){ + if(op.equals("+")){ + return f1+f2; + } + if(op.equals("-")){ + return f1-f2; + } + if(op.equals("*")){ + return f1*f2; + } + if(op.equals("/")){ + return f1/f2; + } + throw new RuntimeException(op + " is not supported"); + } + + + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixExprTest.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixExprTest.java new file mode 100644 index 0000000000..20e34e8852 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixExprTest.java @@ -0,0 +1,52 @@ +package com.coding.basic.stack.expr; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + +public class InfixExprTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testEvaluate() { + //InfixExpr expr = new InfixExpr("300*20+12*5-20/4"); + { + InfixExpr expr = new InfixExpr("2+3*4+5"); + Assert.assertEquals(19.0, expr.evaluate(), 0.001f); + } + { + InfixExpr expr = new InfixExpr("3*20+12*5-40/2"); + Assert.assertEquals(100.0, expr.evaluate(), 0.001f); + } + + { + InfixExpr expr = new InfixExpr("3*20/2"); + Assert.assertEquals(30, expr.evaluate(), 0.001f); + } + + { + InfixExpr expr = new InfixExpr("20/2*3"); + Assert.assertEquals(30, expr.evaluate(), 0.001f); + } + + { + InfixExpr expr = new InfixExpr("10-30+50"); + Assert.assertEquals(30, expr.evaluate(), 0.001f); + } + { + InfixExpr expr = new InfixExpr("10-2*3+50"); + Assert.assertEquals(54, expr.evaluate(), 0.001f); + } + + } + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixToPostfix.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixToPostfix.java new file mode 100644 index 0000000000..9e501eda20 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixToPostfix.java @@ -0,0 +1,43 @@ +package com.coding.basic.stack.expr; + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +public class InfixToPostfix { + + public static List convert(String expr) { + List inFixTokens = new TokenParser().parse(expr); + + List postFixTokens = new ArrayList<>(); + + Stack opStack = new Stack(); + for(Token token : inFixTokens){ + + if(token.isOperator()){ + + while(!opStack.isEmpty() + && !token.hasHigherPriority(opStack.peek())){ + postFixTokens.add(opStack.pop()); + + } + opStack.push(token); + + } + if(token.isNumber()){ + + postFixTokens.add(token); + + } + } + + while(!opStack.isEmpty()){ + postFixTokens.add(opStack.pop()); + } + + return postFixTokens; + } + + + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixToPostfixTest.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixToPostfixTest.java new file mode 100644 index 0000000000..f879f55f14 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/InfixToPostfixTest.java @@ -0,0 +1,41 @@ +package com.coding.basic.stack.expr; + +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class InfixToPostfixTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testConvert() { + { + List tokens = InfixToPostfix.convert("2+3"); + Assert.assertEquals("[2, 3, +]", tokens.toString()); + } + { + + List tokens = InfixToPostfix.convert("2+3*4"); + Assert.assertEquals("[2, 3, 4, *, +]", tokens.toString()); + } + + { + + List tokens = InfixToPostfix.convert("2-3*4+5"); + Assert.assertEquals("[2, 3, 4, *, -, 5, +]", tokens.toString()); + } + } + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PostfixExpr.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PostfixExpr.java new file mode 100644 index 0000000000..c54eb69e2a --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PostfixExpr.java @@ -0,0 +1,46 @@ +package com.coding.basic.stack.expr; + +import java.util.List; +import java.util.Stack; + +public class PostfixExpr { +String expr = null; + + public PostfixExpr(String expr) { + this.expr = expr; + } + + public float evaluate() { + TokenParser parser = new TokenParser(); + List tokens = parser.parse(this.expr); + + + Stack numStack = new Stack<>(); + for(Token token : tokens){ + if(token.isNumber()){ + numStack.push(new Float(token.getIntValue())); + } else{ + Float f2 = numStack.pop(); + Float f1 = numStack.pop(); + numStack.push(calculate(token.toString(),f1,f2)); + } + } + return numStack.pop().floatValue(); + } + + private Float calculate(String op, Float f1, Float f2){ + if(op.equals("+")){ + return f1+f2; + } + if(op.equals("-")){ + return f1-f2; + } + if(op.equals("*")){ + return f1*f2; + } + if(op.equals("/")){ + return f1/f2; + } + throw new RuntimeException(op + " is not supported"); + } +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PostfixExprTest.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PostfixExprTest.java new file mode 100644 index 0000000000..c0435a2db5 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PostfixExprTest.java @@ -0,0 +1,41 @@ +package com.coding.basic.stack.expr; + + + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class PostfixExprTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testEvaluate() { + { + PostfixExpr expr = new PostfixExpr("6 5 2 3 + 8 * + 3 + *"); + Assert.assertEquals(288, expr.evaluate(),0.0f); + } + { + //9+(3-1)*3+10/2 + PostfixExpr expr = new PostfixExpr("9 3 1-3*+ 10 2/+"); + Assert.assertEquals(20, expr.evaluate(),0.0f); + } + + { + //10-2*3+50 + PostfixExpr expr = new PostfixExpr("10 2 3 * - 50 +"); + Assert.assertEquals(54, expr.evaluate(),0.0f); + } + } + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PrefixExpr.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PrefixExpr.java new file mode 100644 index 0000000000..f811fd6d9a --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PrefixExpr.java @@ -0,0 +1,52 @@ +package com.coding.basic.stack.expr; + +import java.util.List; +import java.util.Stack; + +public class PrefixExpr { + String expr = null; + + public PrefixExpr(String expr) { + this.expr = expr; + } + + public float evaluate() { + TokenParser parser = new TokenParser(); + List tokens = parser.parse(this.expr); + + Stack exprStack = new Stack<>(); + Stack numStack = new Stack<>(); + for(Token token : tokens){ + exprStack.push(token); + } + + while(!exprStack.isEmpty()){ + Token t = exprStack.pop(); + if(t.isNumber()){ + numStack.push(new Float(t.getIntValue())); + }else{ + Float f1 = numStack.pop(); + Float f2 = numStack.pop(); + numStack.push(calculate(t.toString(),f1,f2)); + + } + } + return numStack.pop().floatValue(); + } + + private Float calculate(String op, Float f1, Float f2){ + if(op.equals("+")){ + return f1+f2; + } + if(op.equals("-")){ + return f1-f2; + } + if(op.equals("*")){ + return f1*f2; + } + if(op.equals("/")){ + return f1/f2; + } + throw new RuntimeException(op + " is not supported"); + } +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PrefixExprTest.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PrefixExprTest.java new file mode 100644 index 0000000000..5cec210e75 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/PrefixExprTest.java @@ -0,0 +1,45 @@ +package com.coding.basic.stack.expr; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + +public class PrefixExprTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testEvaluate() { + { + // 2*3+4*5 + PrefixExpr expr = new PrefixExpr("+ * 2 3* 4 5"); + Assert.assertEquals(26, expr.evaluate(),0.001f); + } + { + // 4*2 + 6+9*2/3 -8 + PrefixExpr expr = new PrefixExpr("-++6/*2 9 3 * 4 2 8"); + Assert.assertEquals(12, expr.evaluate(),0.001f); + } + { + //(3+4)*5-6 + PrefixExpr expr = new PrefixExpr("- * + 3 4 5 6"); + Assert.assertEquals(29, expr.evaluate(),0.001f); + } + { + //1+((2+3)*4)-5 + PrefixExpr expr = new PrefixExpr("- + 1 * + 2 3 4 5"); + Assert.assertEquals(16, expr.evaluate(),0.001f); + } + + + } + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/Token.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/Token.java new file mode 100644 index 0000000000..8579743fe9 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/Token.java @@ -0,0 +1,50 @@ +package com.coding.basic.stack.expr; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +class Token { + public static final List OPERATORS = Arrays.asList("+", "-", "*", "/"); + private static final Map priorities = new HashMap<>(); + static { + priorities.put("+", 1); + priorities.put("-", 1); + priorities.put("*", 2); + priorities.put("/", 2); + } + static final int OPERATOR = 1; + static final int NUMBER = 2; + String value; + int type; + public Token(int type, String value){ + this.type = type; + this.value = value; + } + + public boolean isNumber() { + return type == NUMBER; + } + + public boolean isOperator() { + return type == OPERATOR; + } + + public int getIntValue() { + return Integer.valueOf(value).intValue(); + } + public String toString(){ + return value; + } + + public boolean hasHigherPriority(Token t){ + if(!this.isOperator() && !t.isOperator()){ + throw new RuntimeException("numbers can't compare priority"); + } + return priorities.get(this.value) - priorities.get(t.value) > 0; + } + + + +} \ No newline at end of file diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/TokenParser.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/TokenParser.java new file mode 100644 index 0000000000..d3b0f167e1 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/TokenParser.java @@ -0,0 +1,57 @@ +package com.coding.basic.stack.expr; + +import java.util.ArrayList; +import java.util.List; + +public class TokenParser { + + + public List parse(String expr) { + List tokens = new ArrayList<>(); + + int i = 0; + + while (i < expr.length()) { + + char c = expr.charAt(i); + + if (isOperator(c)) { + + Token t = new Token(Token.OPERATOR, String.valueOf(c)); + tokens.add(t); + i++; + + } else if (Character.isDigit(c)) { + + int nextOperatorIndex = indexOfNextOperator(i, expr); + String value = expr.substring(i, nextOperatorIndex); + Token t = new Token(Token.NUMBER, value); + tokens.add(t); + i = nextOperatorIndex; + + } else{ + System.out.println("char :["+c+"] is not number or operator,ignore"); + i++; + } + + } + return tokens; + } + + private int indexOfNextOperator(int i, String expr) { + + while (Character.isDigit(expr.charAt(i))) { + i++; + if (i == expr.length()) { + break; + } + } + return i; + + } + + private boolean isOperator(char c) { + String sc = String.valueOf(c); + return Token.OPERATORS.contains(sc); + } +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/TokenParserTest.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/TokenParserTest.java new file mode 100644 index 0000000000..399d3e857e --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/stack/expr/TokenParserTest.java @@ -0,0 +1,41 @@ +package com.coding.basic.stack.expr; + +import static org.junit.Assert.*; + +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class TokenParserTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void test() { + + TokenParser parser = new TokenParser(); + List tokens = parser.parse("300*20+12*5-20/4"); + + Assert.assertEquals(300, tokens.get(0).getIntValue()); + Assert.assertEquals("*", tokens.get(1).toString()); + Assert.assertEquals(20, tokens.get(2).getIntValue()); + Assert.assertEquals("+", tokens.get(3).toString()); + Assert.assertEquals(12, tokens.get(4).getIntValue()); + Assert.assertEquals("*", tokens.get(5).toString()); + Assert.assertEquals(5, tokens.get(6).getIntValue()); + Assert.assertEquals("-", tokens.get(7).toString()); + Assert.assertEquals(20, tokens.get(8).getIntValue()); + Assert.assertEquals("/", tokens.get(9).toString()); + Assert.assertEquals(4, tokens.get(10).getIntValue()); + } + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/tree/BinarySearchTree.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/tree/BinarySearchTree.java new file mode 100644 index 0000000000..284e5b0011 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/tree/BinarySearchTree.java @@ -0,0 +1,189 @@ +package com.coding.basic.tree; + +import java.util.ArrayList; +import java.util.List; + +import com.coding.basic.queue.Queue; + + +public class BinarySearchTree { + + BinaryTreeNode root; + public BinarySearchTree(BinaryTreeNode root){ + this.root = root; + } + public BinaryTreeNode getRoot(){ + return root; + } + public T findMin(){ + if(root == null){ + return null; + } + return findMin(root).data; + } + public T findMax(){ + if(root == null){ + return null; + } + return findMax(root).data; + } + public int height() { + return height(root); + } + public int size() { + return size(root); + } + public void remove(T e){ + remove(e, root); + } + + private BinaryTreeNode remove(T x, BinaryTreeNode t){ + if(t == null){ + return t; + } + int compareResult = x.compareTo(t.data); + + if(compareResult< 0 ){ + t.left = remove(x,t.left); + + } else if(compareResult > 0){ + t.right = remove(x, t.right); + + } else { + if(t.left != null && t.right != null){ + + t.data = findMin(t.right).data; + t.right = remove(t.data,t.right); + + } else{ + t = (t.left != null) ? t.left : t.right; + } + } + return t; + } + + private BinaryTreeNode findMin(BinaryTreeNode p){ + if (p==null){ + return null; + } else if (p.left == null){ + return p; + } else{ + return findMin(p.left); + } + } + private BinaryTreeNode findMax(BinaryTreeNode p){ + if (p==null){ + return null; + }else if (p.right==null){ + return p; + } else{ + return findMax(p.right); + } + } + private int height(BinaryTreeNode t){ + if (t==null){ + return 0; + }else { + int leftChildHeight=height(t.left); + int rightChildHeight=height(t.right); + if(leftChildHeight > rightChildHeight){ + return leftChildHeight+1; + } else{ + return rightChildHeight+1; + } + } + } + private int size(BinaryTreeNode t){ + if (t == null){ + return 0; + } + return size(t.left) + 1 + size(t.right); + + } + + public List levelVisit(){ + List result = new ArrayList(); + if(root == null){ + return result; + } + Queue> queue = new Queue>(); + BinaryTreeNode node = root; + queue.enQueue(node); + while (!queue.isEmpty()) { + node = queue.deQueue(); + result.add(node.data); + if (node.left != null){ + queue.enQueue(node.left); + } + if (node.right != null){ + queue.enQueue(node.right); + } + } + return result; + } + public boolean isValid(){ + return isValid(root); + } + public T getLowestCommonAncestor(T n1, T n2){ + if (root == null){ + return null; + } + return lowestCommonAncestor(root,n1,n2); + + } + public List getNodesBetween(T n1, T n2){ + List elements = new ArrayList<>(); + getNodesBetween(elements,root,n1,n2); + return elements; + } + + public void getNodesBetween(List elements ,BinaryTreeNode node, T n1, T n2){ + + if (node == null) { + return; + } + + if (n1.compareTo(node.data) < 0) { + getNodesBetween(elements,node.left, n1, n2); + } + + if ((n1.compareTo(node.data) <= 0 ) + && (n2.compareTo(node.data) >= 0 )) { + elements.add(node.data); + } + if (n2.compareTo(node.data)>0) { + getNodesBetween(elements,node.right, n1, n2); + } + } + private T lowestCommonAncestor(BinaryTreeNode node,T n1, T n2){ + if(node == null){ + return null; + } + // 如果n1和n2都比 node的值小, LCA在左孩子 + if (node.data.compareTo(n1) > 0 && node.data.compareTo(n2) >0){ + return lowestCommonAncestor(node.left, n1, n2); + } + + // 如果n1和n2都比 node的值小, LCA在右孩子 + if (node.data.compareTo(n1) < 0 && node.data.compareTo(n2) <0) + return lowestCommonAncestor(node.right, n1, n2); + + return node.data; + } + private boolean isValid(BinaryTreeNode t){ + if(t == null){ + return true; + } + if(t.left != null && findMax(t.left).data.compareTo(t.data) >0){ + return false; + } + if(t.right !=null && findMin(t.right).data.compareTo(t.data) <0){ + return false; + } + if(!isValid(t.left) || !isValid(t.right)){ + return false; + } + return true; + } +} + diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/tree/BinarySearchTreeTest.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/tree/BinarySearchTreeTest.java new file mode 100644 index 0000000000..590e60306c --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/tree/BinarySearchTreeTest.java @@ -0,0 +1,108 @@ +package com.coding.basic.tree; + +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class BinarySearchTreeTest { + + BinarySearchTree tree = null; + + @Before + public void setUp() throws Exception { + BinaryTreeNode root = new BinaryTreeNode(6); + root.left = new BinaryTreeNode(2); + root.right = new BinaryTreeNode(8); + root.left.left = new BinaryTreeNode(1); + root.left.right = new BinaryTreeNode(4); + root.left.right.left = new BinaryTreeNode(3); + root.left.right.right = new BinaryTreeNode(5); + tree = new BinarySearchTree(root); + } + + @After + public void tearDown() throws Exception { + tree = null; + } + + @Test + public void testFindMin() { + Assert.assertEquals(1, tree.findMin().intValue()); + + } + + @Test + public void testFindMax() { + Assert.assertEquals(8, tree.findMax().intValue()); + } + + @Test + public void testHeight() { + Assert.assertEquals(4, tree.height()); + } + + @Test + public void testSize() { + Assert.assertEquals(7, tree.size()); + } + + @Test + public void testRemoveLeaf() { + tree.remove(3); + BinaryTreeNode root= tree.getRoot(); + Assert.assertEquals(4, root.left.right.data.intValue()); + + } + @Test + public void testRemoveMiddleNode1() { + tree.remove(4); + BinaryTreeNode root= tree.getRoot(); + Assert.assertEquals(5, root.left.right.data.intValue()); + Assert.assertEquals(3, root.left.right.left.data.intValue()); + } + @Test + public void testRemoveMiddleNode2() { + tree.remove(2); + BinaryTreeNode root= tree.getRoot(); + Assert.assertEquals(3, root.left.data.intValue()); + Assert.assertEquals(4, root.left.right.data.intValue()); + } + + @Test + public void testLevelVisit() { + List values = tree.levelVisit(); + Assert.assertEquals("[6, 2, 8, 1, 4, 3, 5]", values.toString()); + + } + @Test + public void testLCA(){ + Assert.assertEquals(2,tree.getLowestCommonAncestor(1, 5).intValue()); + Assert.assertEquals(2,tree.getLowestCommonAncestor(1, 4).intValue()); + Assert.assertEquals(6,tree.getLowestCommonAncestor(3, 8).intValue()); + } + @Test + public void testIsValid() { + + Assert.assertTrue(tree.isValid()); + + BinaryTreeNode root = new BinaryTreeNode(6); + root.left = new BinaryTreeNode(2); + root.right = new BinaryTreeNode(8); + root.left.left = new BinaryTreeNode(4); + root.left.right = new BinaryTreeNode(1); + root.left.right.left = new BinaryTreeNode(3); + tree = new BinarySearchTree(root); + + Assert.assertFalse(tree.isValid()); + } + @Test + public void testGetNodesBetween(){ + List numbers = this.tree.getNodesBetween(3, 8); + Assert.assertEquals("[3, 4, 5, 6, 8]",numbers.toString()); + } +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/tree/BinaryTreeNode.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/tree/BinaryTreeNode.java new file mode 100644 index 0000000000..3f6f4d2b44 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/tree/BinaryTreeNode.java @@ -0,0 +1,36 @@ +package com.coding.basic.tree; + +public class BinaryTreeNode { + + public T data; + public BinaryTreeNode left; + public BinaryTreeNode right; + + public BinaryTreeNode(T data){ + this.data=data; + } + public T getData() { + return data; + } + public void setData(T data) { + this.data = data; + } + public BinaryTreeNode getLeft() { + return left; + } + public void setLeft(BinaryTreeNode left) { + this.left = left; + } + public BinaryTreeNode getRight() { + return right; + } + public void setRight(BinaryTreeNode right) { + this.right = right; + } + + public BinaryTreeNode insert(Object o){ + return null; + } + + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/tree/BinaryTreeUtil.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/tree/BinaryTreeUtil.java new file mode 100644 index 0000000000..f2a6515fa6 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/tree/BinaryTreeUtil.java @@ -0,0 +1,116 @@ +package com.coding.basic.tree; + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +public class BinaryTreeUtil { + /** + * 用递归的方式实现对二叉树的前序遍历, 需要通过BinaryTreeUtilTest测试 + * + * @param root + * @return + */ + public static List preOrderVisit(BinaryTreeNode root) { + List result = new ArrayList(); + preOrderVisit(root, result); + return result; + } + + /** + * 用递归的方式实现对二叉树的中遍历 + * + * @param root + * @return + */ + public static List inOrderVisit(BinaryTreeNode root) { + List result = new ArrayList(); + inOrderVisit(root, result); + return result; + } + + /** + * 用递归的方式实现对二叉树的后遍历 + * + * @param root + * @return + */ + public static List postOrderVisit(BinaryTreeNode root) { + List result = new ArrayList(); + postOrderVisit(root, result); + return result; + } + + public static List preOrderWithoutRecursion(BinaryTreeNode root) { + + List result = new ArrayList(); + Stack> stack = new Stack>(); + + BinaryTreeNode node = root; + + if(node != null){ + stack.push(node); + } + + while(!stack.isEmpty()){ + node = stack.pop(); + result.add(node.data); + + if(node.right != null){ + stack.push(node.right); + } + + if(node.left != null){ + stack.push(node.right); + } + } + return result; + } + + public static List inOrderWithoutRecursion(BinaryTreeNode root) { + + List result = new ArrayList(); + BinaryTreeNode node = root; + Stack> stack = new Stack>(); + + while (node != null || !stack.isEmpty()) { + + while (node != null) { + stack.push(node); + node = node.left; + } + BinaryTreeNode currentNode = stack.pop(); + result.add(currentNode.data); + node = currentNode.right; + } + return result; + } + + private static void preOrderVisit(BinaryTreeNode node, List result) { + if (node == null) { + return; + } + result.add(node.getData()); + preOrderVisit(node.getLeft(), result); + preOrderVisit(node.getRight(), result); + } + + private static void inOrderVisit(BinaryTreeNode node, List result) { + if (node == null) { + return; + } + inOrderVisit(node.getLeft(), result); + result.add(node.getData()); + inOrderVisit(node.getRight(), result); + } + + private static void postOrderVisit(BinaryTreeNode node, List result) { + if (node == null) { + return; + } + postOrderVisit(node.getLeft(), result); + postOrderVisit(node.getRight(), result); + result.add(node.getData()); + } + +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/tree/BinaryTreeUtilTest.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/tree/BinaryTreeUtilTest.java new file mode 100644 index 0000000000..41857e137d --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/tree/BinaryTreeUtilTest.java @@ -0,0 +1,75 @@ +package com.coding.basic.tree; + +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class BinaryTreeUtilTest { + + BinaryTreeNode root = null; + @Before + public void setUp() throws Exception { + root = new BinaryTreeNode(1); + root.setLeft(new BinaryTreeNode(2)); + root.setRight(new BinaryTreeNode(5)); + root.getLeft().setLeft(new BinaryTreeNode(3)); + root.getLeft().setRight(new BinaryTreeNode(4)); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testPreOrderVisit() { + + List result = BinaryTreeUtil.preOrderVisit(root); + Assert.assertEquals("[1, 2, 3, 4, 5]", result.toString()); + + + } + @Test + public void testInOrderVisit() { + + + List result = BinaryTreeUtil.inOrderVisit(root); + Assert.assertEquals("[3, 2, 4, 1, 5]", result.toString()); + + } + + @Test + public void testPostOrderVisit() { + + + List result = BinaryTreeUtil.postOrderVisit(root); + Assert.assertEquals("[3, 4, 2, 5, 1]", result.toString()); + + } + + + @Test + public void testInOrderVisitWithoutRecursion() { + BinaryTreeNode node = root.getLeft().getRight(); + node.setLeft(new BinaryTreeNode(6)); + node.setRight(new BinaryTreeNode(7)); + + List result = BinaryTreeUtil.inOrderWithoutRecursion(root); + Assert.assertEquals("[3, 2, 6, 4, 7, 1, 5]", result.toString()); + + } + @Test + public void testPreOrderVisitWithoutRecursion() { + BinaryTreeNode node = root.getLeft().getRight(); + node.setLeft(new BinaryTreeNode(6)); + node.setRight(new BinaryTreeNode(7)); + + List result = BinaryTreeUtil.preOrderWithoutRecursion(root); + Assert.assertEquals("[1, 2, 3, 4, 6, 7, 5]", result.toString()); + + } +} diff --git a/students/250103158/data-structure/answer/src/main/java/com/coding/basic/tree/FileList.java b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/tree/FileList.java new file mode 100644 index 0000000000..85fb8ab2a4 --- /dev/null +++ b/students/250103158/data-structure/answer/src/main/java/com/coding/basic/tree/FileList.java @@ -0,0 +1,34 @@ +package com.coding.basic.tree; + +import java.io.File; + +public class FileList { + public void list(File f) { + list(f, 0); + } + + public void list(File f, int depth) { + printName(f, depth); + if (f.isDirectory()) { + File[] files = f.listFiles(); + for (File i : files) + list(i, depth + 1); + } + } + + void printName(File f, int depth) { + String name = f.getName(); + for (int i = 0; i < depth; i++) + System.out.print("+"); + if (f.isDirectory()) + System.out.println("Dir: " + name); + else + System.out.println(f.getName() + " " + f.length()); + } + + public static void main(String args[]) { + FileList L = new FileList(); + File f = new File("C:\\coderising\\tmp"); + L.list(f); + } +} diff --git a/students/250103158/data-structure/assignment/pom.xml b/students/250103158/data-structure/assignment/pom.xml new file mode 100644 index 0000000000..5024466d17 --- /dev/null +++ b/students/250103158/data-structure/assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ds-assignment + 0.0.1-SNAPSHOT + jar + + ds-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/DownloadThread.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/DownloadThread.java new file mode 100644 index 0000000000..900a3ad358 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/DownloadThread.java @@ -0,0 +1,20 @@ +package com.coderising.download; + +import com.coderising.download.api.Connection; + +public class DownloadThread extends Thread{ + + Connection conn; + int startPos; + int endPos; + + public DownloadThread( Connection conn, int startPos, int endPos){ + + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + } + public void run(){ + + } +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/FileDownloader.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/FileDownloader.java new file mode 100644 index 0000000000..c3c8a3f27d --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/FileDownloader.java @@ -0,0 +1,73 @@ +package com.coderising.download; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionException; +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; + + +public class FileDownloader { + + String url; + + DownloadListener listener; + + ConnectionManager cm; + + + public FileDownloader(String _url) { + this.url = _url; + + } + + public void execute(){ + // 在这里实现你的代码, 注意: 需要用多线程实现下载 + // 这个类依赖于其他几个接口, 你需要写这几个接口的实现代码 + // (1) ConnectionManager , 可以打开一个连接,通过Connection可以读取其中的一段(用startPos, endPos来指定) + // (2) DownloadListener, 由于是多线程下载, 调用这个类的客户端不知道什么时候结束,所以你需要实现当所有 + // 线程都执行完以后, 调用listener的notifiedFinished方法, 这样客户端就能收到通知。 + // 具体的实现思路: + // 1. 需要调用ConnectionManager的open方法打开连接, 然后通过Connection.getContentLength方法获得文件的长度 + // 2. 至少启动3个线程下载, 注意每个线程需要先调用ConnectionManager的open方法 + // 然后调用read方法, read方法中有读取文件的开始位置和结束位置的参数, 返回值是byte[]数组 + // 3. 把byte数组写入到文件中 + // 4. 所有的线程都下载完成以后, 需要调用listener的notifiedFinished方法 + + // 下面的代码是示例代码, 也就是说只有一个线程, 你需要改造成多线程的。 + Connection conn = null; + try { + + conn = cm.open(this.url); + + int length = conn.getContentLength(); + + new DownloadThread(conn,0,length-1).start(); + + } catch (ConnectionException e) { + e.printStackTrace(); + }finally{ + if(conn != null){ + conn.close(); + } + } + + + + + } + + public void setListener(DownloadListener listener) { + this.listener = listener; + } + + + + public void setConnectionManager(ConnectionManager ucm){ + this.cm = ucm; + } + + public DownloadListener getListener(){ + return this.listener; + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/FileDownloaderTest.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/FileDownloaderTest.java new file mode 100644 index 0000000000..4ff7f46ae0 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/FileDownloaderTest.java @@ -0,0 +1,59 @@ +package com.coderising.download; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; +import com.coderising.download.impl.ConnectionManagerImpl; + +public class FileDownloaderTest { + boolean downloadFinished = false; + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testDownload() { + + String url = "http://localhost:8080/test.jpg"; + + FileDownloader downloader = new FileDownloader(url); + + + ConnectionManager cm = new ConnectionManagerImpl(); + downloader.setConnectionManager(cm); + + downloader.setListener(new DownloadListener() { + @Override + public void notifyFinished() { + downloadFinished = true; + } + + }); + + + downloader.execute(); + + // 等待多线程下载程序执行完毕 + while (!downloadFinished) { + try { + System.out.println("还没有下载完成,休眠五秒"); + //休眠5秒 + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + System.out.println("下载完成!"); + + + + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/api/Connection.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/api/Connection.java new file mode 100644 index 0000000000..0957eaf7f4 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/api/Connection.java @@ -0,0 +1,23 @@ +package com.coderising.download.api; + +import java.io.IOException; + +public interface Connection { + /** + * 给定开始和结束位置, 读取数据, 返回值是字节数组 + * @param startPos 开始位置, 从0开始 + * @param endPos 结束位置 + * @return + */ + public byte[] read(int startPos,int endPos) throws IOException; + /** + * 得到数据内容的长度 + * @return + */ + public int getContentLength(); + + /** + * 关闭连接 + */ + public void close(); +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/api/ConnectionException.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/api/ConnectionException.java new file mode 100644 index 0000000000..1551a80b3d --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/api/ConnectionException.java @@ -0,0 +1,5 @@ +package com.coderising.download.api; + +public class ConnectionException extends Exception { + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/api/ConnectionManager.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/api/ConnectionManager.java new file mode 100644 index 0000000000..ce045393b1 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/api/ConnectionManager.java @@ -0,0 +1,10 @@ +package com.coderising.download.api; + +public interface ConnectionManager { + /** + * 给定一个url , 打开一个连接 + * @param url + * @return + */ + public Connection open(String url) throws ConnectionException; +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/api/DownloadListener.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/api/DownloadListener.java new file mode 100644 index 0000000000..bf9807b307 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/api/DownloadListener.java @@ -0,0 +1,5 @@ +package com.coderising.download.api; + +public interface DownloadListener { + public void notifyFinished(); +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/impl/ConnectionImpl.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..36a9d2ce15 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/impl/ConnectionImpl.java @@ -0,0 +1,27 @@ +package com.coderising.download.impl; + +import java.io.IOException; + +import com.coderising.download.api.Connection; + +public class ConnectionImpl implements Connection{ + + @Override + public byte[] read(int startPos, int endPos) throws IOException { + + return null; + } + + @Override + public int getContentLength() { + + return 0; + } + + @Override + public void close() { + + + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/impl/ConnectionManagerImpl.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..172371dd55 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,15 @@ +package com.coderising.download.impl; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionException; +import com.coderising.download.api.ConnectionManager; + +public class ConnectionManagerImpl implements ConnectionManager { + + @Override + public Connection open(String url) throws ConnectionException { + + return null; + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/litestruts/LoginAction.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/litestruts/LoginAction.java new file mode 100644 index 0000000000..dcdbe226ed --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/litestruts/LoginAction.java @@ -0,0 +1,39 @@ +package com.coderising.litestruts; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * @author liuxin + * + */ +public class LoginAction{ + private String name ; + private String password; + private String message; + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String execute(){ + if("test".equals(name) && "1234".equals(password)){ + this.message = "login successful"; + return "success"; + } + this.message = "login failed,please check your user/pwd"; + return "fail"; + } + + public void setName(String name){ + this.name = name; + } + public void setPassword(String password){ + this.password = password; + } + public String getMessage(){ + return this.message; + } +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/litestruts/Struts.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/litestruts/Struts.java new file mode 100644 index 0000000000..85e2e22de3 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/litestruts/Struts.java @@ -0,0 +1,34 @@ +package com.coderising.litestruts; + +import java.util.Map; + + + +public class Struts { + + public static View runAction(String actionName, Map parameters) { + + /* + + 0. 读取配置文件struts.xml + + 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + ("name"="test" , "password"="1234") , + 那就应该调用 setName和setPassword方法 + + 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + + 3. 通过反射找到对象的所有getter方法(例如 getMessage), + 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + 放到View对象的parameters + + 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + 放到View对象的jsp字段中。 + + */ + + return null; + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/litestruts/StrutsTest.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/litestruts/StrutsTest.java new file mode 100644 index 0000000000..b8c81faf3c --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/litestruts/StrutsTest.java @@ -0,0 +1,43 @@ +package com.coderising.litestruts; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + + + + + +public class StrutsTest { + + @Test + public void testLoginActionSuccess() { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/litestruts/View.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/litestruts/View.java new file mode 100644 index 0000000000..07df2a5dab --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/litestruts/View.java @@ -0,0 +1,23 @@ +package com.coderising.litestruts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/litestruts/struts.xml b/students/250103158/data-structure/assignment/src/main/java/com/coderising/litestruts/struts.xml new file mode 100644 index 0000000000..e5d9aebba8 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/Course.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/Course.java new file mode 100644 index 0000000000..436d092f58 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/Course.java @@ -0,0 +1,24 @@ +package com.coderising.ood.course.bad; + +import java.util.List; + +public class Course { + private String id; + private String desc; + private int duration ; + + List prerequisites; + + public List getPrerequisites() { + return prerequisites; + } + + + public boolean equals(Object o){ + if(o == null || !(o instanceof Course)){ + return false; + } + Course c = (Course)o; + return (c != null) && c.id.equals(id); + } +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/CourseOffering.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/CourseOffering.java new file mode 100644 index 0000000000..ab8c764584 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/CourseOffering.java @@ -0,0 +1,26 @@ +package com.coderising.ood.course.bad; + +import java.util.ArrayList; +import java.util.List; + + +public class CourseOffering { + private Course course; + private String location; + private String teacher; + private int maxStudents; + + List students = new ArrayList(); + + public int getMaxStudents() { + return maxStudents; + } + + public List getStudents() { + return students; + } + + public Course getCourse() { + return course; + } +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/CourseService.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/CourseService.java new file mode 100644 index 0000000000..8c34bad0c3 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/CourseService.java @@ -0,0 +1,16 @@ +package com.coderising.ood.course.bad; + + + +public class CourseService { + + public void chooseCourse(Student student, CourseOffering sc){ + //如果学生上过该科目的先修科目,并且该课程还未满, 则学生可以加入该课程 + if(student.getCoursesAlreadyTaken().containsAll( + sc.getCourse().getPrerequisites()) + && sc.getMaxStudents() > sc.getStudents().size()){ + sc.getStudents().add(student); + } + + } +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/Student.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/Student.java new file mode 100644 index 0000000000..a651923ef5 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/bad/Student.java @@ -0,0 +1,14 @@ +package com.coderising.ood.course.bad; + +import java.util.ArrayList; +import java.util.List; + +public class Student { + private String id; + private String name; + private List coursesAlreadyTaken = new ArrayList(); + + public List getCoursesAlreadyTaken() { + return coursesAlreadyTaken; + } +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/good/Course.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/good/Course.java new file mode 100644 index 0000000000..aefc9692bb --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/good/Course.java @@ -0,0 +1,18 @@ +package com.coderising.ood.course.good; + +import java.util.List; + +public class Course { + private String id; + private String desc; + private int duration ; + + List prerequisites; + + public List getPrerequisites() { + return prerequisites; + } + +} + + diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/good/CourseOffering.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/good/CourseOffering.java new file mode 100644 index 0000000000..8660ec8109 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/good/CourseOffering.java @@ -0,0 +1,34 @@ +package com.coderising.ood.course.good; + +import java.util.ArrayList; +import java.util.List; + +public class CourseOffering { + private Course course; + private String location; + private String teacher; + private int maxStudents; + + List students = new ArrayList(); + + public List getStudents() { + return students; + } + public int getMaxStudents() { + return maxStudents; + } + public Course getCourse() { + return course; + } + + + // 第二步: 把主要逻辑移动到CourseOffering 中 + public void addStudent(Student student){ + + if(student.canAttend(course) + && this.maxStudents > students.size()){ + students.add(student); + } + } + // 第三步: 重构CourseService +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/good/CourseService.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/good/CourseService.java new file mode 100644 index 0000000000..22ba4a5450 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/good/CourseService.java @@ -0,0 +1,14 @@ +package com.coderising.ood.course.good; + + + +public class CourseService { + + public void chooseCourse(Student student, CourseOffering sc){ + //第一步:重构: canAttend , 但是还有问题 + if(student.canAttend(sc.getCourse()) + && sc.getMaxStudents() > sc.getStudents().size()){ + sc.getStudents().add(student); + } + } +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/good/Student.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/good/Student.java new file mode 100644 index 0000000000..2c7e128b2a --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/course/good/Student.java @@ -0,0 +1,21 @@ +package com.coderising.ood.course.good; + +import java.util.ArrayList; +import java.util.List; + +public class Student { + private String id; + private String name; + private List coursesAlreadyTaken = new ArrayList(); + + public List getCoursesAlreadyTaken() { + return coursesAlreadyTaken; + } + + public boolean canAttend(Course course){ + return this.coursesAlreadyTaken.containsAll( + course.getPrerequisites()); + } +} + + diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java new file mode 100644 index 0000000000..b6cf28c096 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return null; + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/ocp/Logger.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/ocp/Logger.java new file mode 100644 index 0000000000..0357c4d912 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/ocp/Logger.java @@ -0,0 +1,38 @@ +package com.coderising.ood.ocp; + +public class Logger { + + public final int RAW_LOG = 1; + public final int RAW_LOG_WITH_DATE = 2; + public final int EMAIL_LOG = 1; + public final int SMS_LOG = 2; + public final int PRINT_LOG = 3; + + int type = 0; + int method = 0; + + public Logger(int logType, int logMethod){ + this.type = logType; + this.method = logMethod; + } + public void log(String msg){ + + String logMsg = msg; + + if(this.type == RAW_LOG){ + logMsg = msg; + } else if(this.type == RAW_LOG_WITH_DATE){ + String txtDate = DateUtil.getCurrentDateAsString(); + logMsg = txtDate + ": " + msg; + } + + if(this.method == EMAIL_LOG){ + MailUtil.send(logMsg); + } else if(this.method == SMS_LOG){ + SMSUtil.send(logMsg); + } else if(this.method == PRINT_LOG){ + System.out.println(logMsg); + } + } +} + diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java new file mode 100644 index 0000000000..ec54b839c5 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class MailUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java new file mode 100644 index 0000000000..13cf802418 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class SMSUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..9f9e749af7 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..781587a846 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,199 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery = null; + + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected String productID = null; + protected String productDesc = null; + + private static Configuration config; + + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + + + config = new Configuration(); + + setSMTPHost(); + setAltSMTPHost(); + + + setFromAddress(); + + + setLoadQuery(); + + sendEMails(mailDebug, loadMailingList()); + + + } + + + + + protected void setProductID(String productID) + { + this.productID = productID; + + } + + protected String getproductID() + { + return productID; + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected void setSMTPHost() + { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() + { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + protected void setFromAddress() + { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setMessage(HashMap userInfo) throws IOException + { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + + + + } + + + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + private void setProductDesc(String desc) { + this.productDesc = desc; + } + + + protected void configureEMail(HashMap userInfo) throws IOException + { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try + { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } + + else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..a98917f829 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo R15 +P4955 Vivo X20 \ No newline at end of file diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/Iterator.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/Iterator.java new file mode 100644 index 0000000000..06ef6311b2 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/Iterator.java @@ -0,0 +1,7 @@ +package com.coding.basic; + +public interface Iterator { + public boolean hasNext(); + public Object next(); + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/List.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/List.java new file mode 100644 index 0000000000..10d13b5832 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/List.java @@ -0,0 +1,9 @@ +package com.coding.basic; + +public interface List { + public void add(Object o); + public void add(int index, Object o); + public Object get(int index); + public Object remove(int index); + public int size(); +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/array/ArrayList.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/array/ArrayList.java new file mode 100644 index 0000000000..4576c016af --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/array/ArrayList.java @@ -0,0 +1,35 @@ +package com.coding.basic.array; + +import com.coding.basic.Iterator; +import com.coding.basic.List; + +public class ArrayList implements List { + + private int size = 0; + + private Object[] elementData = new Object[100]; + + public void add(Object o){ + + } + public void add(int index, Object o){ + + } + + public Object get(int index){ + return null; + } + + public Object remove(int index){ + return null; + } + + public int size(){ + return -1; + } + + public Iterator iterator(){ + return null; + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/array/ArrayUtil.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/array/ArrayUtil.java new file mode 100644 index 0000000000..45740e6d57 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/array/ArrayUtil.java @@ -0,0 +1,96 @@ +package com.coding.basic.array; + +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 + 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] + 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * @param origin + * @return + */ + public void reverseArray(int[] origin){ + + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: + * {1,3,4,5,6,6,5,4,7,6,7,5} + * @param oldArray + * @return + */ + + public int[] removeZero(int[] oldArray){ + return null; + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 + * 例如 a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * @param array1 + * @param array2 + * @return + */ + + public int[] merge(int[] array1, int[] array2){ + return null; + } + /** + * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size + * 注意,老数组的元素在新数组中需要保持 + * 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 + * [2,3,6,0,0,0] + * @param oldArray + * @param size + * @return + */ + public int[] grow(int [] oldArray, int size){ + return null; + } + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 + * 例如, max = 15 , 则返回的数组应该为 [1,1,2,3,5,8,13] + * max = 1, 则返回空数组 [] + * @param max + * @return + */ + public int[] fibonacci(int max){ + return null; + } + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public int[] getPrimes(int max){ + return null; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 + * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * @param max + * @return + */ + public int[] getPerfectNumbers(int max){ + return null; + } + + /** + * 用seperator 把数组 array给连接起来 + * 例如array= [3,8,9], seperator = "-" + * 则返回值为"3-8-9" + * @param array + * @param s + * @return + */ + public String join(int[] array, String seperator){ + return null; + } + + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/linklist/LRUPageFrame.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/linklist/LRUPageFrame.java new file mode 100644 index 0000000000..994a241a3d --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/linklist/LRUPageFrame.java @@ -0,0 +1,57 @@ +package com.coding.basic.linklist; + + +public class LRUPageFrame { + + private static class Node { + + Node prev; + Node next; + int pageNum; + + Node() { + } + } + + private int capacity; + + private int currentSize; + private Node first;// 链表头 + private Node last;// 链表尾 + + + public LRUPageFrame(int capacity) { + this.currentSize = 0; + this.capacity = capacity; + + } + + /** + * 获取缓存中对象 + * + * @param key + * @return + */ + public void access(int pageNum) { + + + } + + + public String toString(){ + StringBuilder buffer = new StringBuilder(); + Node node = first; + while(node != null){ + buffer.append(node.pageNum); + + node = node.next; + if(node != null){ + buffer.append(","); + } + } + return buffer.toString(); + } + + + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/linklist/LRUPageFrameTest.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/linklist/LRUPageFrameTest.java new file mode 100644 index 0000000000..7fd72fc2b4 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/linklist/LRUPageFrameTest.java @@ -0,0 +1,34 @@ +package com.coding.basic.linklist; + +import org.junit.Assert; + +import org.junit.Test; + + +public class LRUPageFrameTest { + + @Test + public void testAccess() { + LRUPageFrame frame = new LRUPageFrame(3); + frame.access(7); + frame.access(0); + frame.access(1); + Assert.assertEquals("1,0,7", frame.toString()); + frame.access(2); + Assert.assertEquals("2,1,0", frame.toString()); + frame.access(0); + Assert.assertEquals("0,2,1", frame.toString()); + frame.access(0); + Assert.assertEquals("0,2,1", frame.toString()); + frame.access(3); + Assert.assertEquals("3,0,2", frame.toString()); + frame.access(0); + Assert.assertEquals("0,3,2", frame.toString()); + frame.access(4); + Assert.assertEquals("4,0,3", frame.toString()); + frame.access(5); + Assert.assertEquals("5,4,0", frame.toString()); + + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/linklist/LinkedList.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/linklist/LinkedList.java new file mode 100644 index 0000000000..f4c7556a2e --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/linklist/LinkedList.java @@ -0,0 +1,125 @@ +package com.coding.basic.linklist; + +import com.coding.basic.Iterator; +import com.coding.basic.List; + +public class LinkedList implements List { + + private Node head; + + public void add(Object o){ + + } + public void add(int index , Object o){ + + } + public Object get(int index){ + return null; + } + public Object remove(int index){ + return null; + } + + public int size(){ + return -1; + } + + public void addFirst(Object o){ + + } + public void addLast(Object o){ + + } + public Object removeFirst(){ + return null; + } + public Object removeLast(){ + return null; + } + public Iterator iterator(){ + return null; + } + + + private static class Node{ + Object data; + Node next; + + } + + /** + * 把该链表逆置 + * 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + + */ + public void removeFirstHalf(){ + + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * @param i + * @param length + */ + public void remove(int i, int length){ + + } + /** + * 假定当前链表和listB均包含已升序排列的整数 + * 从当前链表中取出那些listB所指定的元素 + * 例如当前链表 = 11->101->201->301->401->501->601->701 + * listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + * @param list + */ + public int[] getElements(LinkedList list){ + return null; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 从当前链表中中删除在listB中出现的元素 + + * @param list + */ + + public void subtract(LinkedList list){ + + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues(){ + + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * @param min + * @param max + */ + public void removeRange(int min, int max){ + + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * @param list + */ + public LinkedList intersection( LinkedList list){ + return null; + } +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/queue/CircleQueue.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/queue/CircleQueue.java new file mode 100644 index 0000000000..2e0550c67e --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/queue/CircleQueue.java @@ -0,0 +1,39 @@ +package com.coding.basic.queue; + +/** + * 用数组实现循环队列 + * @author liuxin + * + * @param + */ +public class CircleQueue { + + private final static int DEFAULT_SIZE = 10; + + //用数组来保存循环队列的元素 + private Object[] elementData = new Object[DEFAULT_SIZE] ; + + //队头 + private int front = 0; + //队尾 + private int rear = 0; + + public boolean isEmpty() { + return false; + + } + + public int size() { + return -1; + } + + + + public void enQueue(E data) { + + } + + public E deQueue() { + return null; + } +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/queue/Josephus.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/queue/Josephus.java new file mode 100644 index 0000000000..6a3ea639b9 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/queue/Josephus.java @@ -0,0 +1,18 @@ +package com.coding.basic.queue; + +import java.util.List; + +/** + * 用Queue来实现Josephus问题 + * 在这个古老的问题当中, N个深陷绝境的人一致同意用这种方式减少生存人数: N个人围成一圈(位置记为0到N-1), 并且从第一个人报数, 报到M的人会被杀死, 直到最后一个人留下来 + * 该方法返回一个List, 包含了被杀死人的次序 + * @author liuxin + * + */ +public class Josephus { + + public static List execute(int n, int m){ + return null; + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/queue/JosephusTest.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/queue/JosephusTest.java new file mode 100644 index 0000000000..7d90318b51 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/queue/JosephusTest.java @@ -0,0 +1,27 @@ +package com.coding.basic.queue; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class JosephusTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testExecute() { + + Assert.assertEquals("[1, 3, 5, 0, 4, 2, 6]", Josephus.execute(7, 2).toString()); + + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/queue/Queue.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/queue/Queue.java new file mode 100644 index 0000000000..c4c4b7325e --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/queue/Queue.java @@ -0,0 +1,61 @@ +package com.coding.basic.queue; + +import java.util.NoSuchElementException; + +public class Queue { + private Node first; + private Node last; + private int size; + + + private static class Node { + private E item; + private Node next; + } + + + public Queue() { + first = null; + last = null; + size = 0; + } + + + public boolean isEmpty() { + return first == null; + } + + public int size() { + return size; + } + + + + public void enQueue(E data) { + Node oldlast = last; + last = new Node(); + last.item = data; + last.next = null; + if (isEmpty()) { + first = last; + } + else{ + oldlast.next = last; + } + size++; + } + + public E deQueue() { + if (isEmpty()) { + throw new NoSuchElementException("Queue underflow"); + } + E item = first.item; + first = first.next; + size--; + if (isEmpty()) { + last = null; + } + return item; + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/queue/QueueWithTwoStacks.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/queue/QueueWithTwoStacks.java new file mode 100644 index 0000000000..cef19a8b59 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/queue/QueueWithTwoStacks.java @@ -0,0 +1,47 @@ +package com.coding.basic.queue; + +import java.util.Stack; + +/** + * 用两个栈来实现一个队列 + * @author liuxin + * + * @param + */ +public class QueueWithTwoStacks { + private Stack stack1; + private Stack stack2; + + + public QueueWithTwoStacks() { + stack1 = new Stack(); + stack2 = new Stack(); + } + + + + + public boolean isEmpty() { + return false; + } + + + + public int size() { + return -1; + } + + + + public void enQueue(E item) { + + } + + public E deQueue() { + return null; + } + + + + } + diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/QuickMinStack.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/QuickMinStack.java new file mode 100644 index 0000000000..f391d92b8f --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/QuickMinStack.java @@ -0,0 +1,19 @@ +package com.coding.basic.stack; + +/** + * 设计一个栈,支持栈的push和pop操作,以及第三种操作findMin, 它返回改数据结构中的最小元素 + * finMin操作最坏的情形下时间复杂度应该是O(1) , 简单来讲,操作一次就可以得到最小值 + * @author liuxin + * + */ +public class QuickMinStack { + public void push(int data){ + + } + public int pop(){ + return -1; + } + public int findMin(){ + return -1; + } +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/Stack.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/Stack.java new file mode 100644 index 0000000000..fedb243604 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/Stack.java @@ -0,0 +1,24 @@ +package com.coding.basic.stack; + +import com.coding.basic.array.ArrayList; + +public class Stack { + private ArrayList elementData = new ArrayList(); + + public void push(Object o){ + } + + public Object pop(){ + return null; + } + + public Object peek(){ + return null; + } + public boolean isEmpty(){ + return false; + } + public int size(){ + return -1; + } +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/StackUtil.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/StackUtil.java new file mode 100644 index 0000000000..b0ec38161d --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/StackUtil.java @@ -0,0 +1,48 @@ +package com.coding.basic.stack; +import java.util.Stack; +public class StackUtil { + + + + /** + * 假设栈中的元素是Integer, 从栈顶到栈底是 : 5,4,3,2,1 调用该方法后, 元素次序变为: 1,2,3,4,5 + * 注意:只能使用Stack的基本操作,即push,pop,peek,isEmpty, 可以使用另外一个栈来辅助 + */ + public static void reverse(Stack s) { + + + + } + + /** + * 删除栈中的某个元素 注意:只能使用Stack的基本操作,即push,pop,peek,isEmpty, 可以使用另外一个栈来辅助 + * + * @param o + */ + public static void remove(Stack s,Object o) { + + } + + /** + * 从栈顶取得len个元素, 原来的栈中元素保持不变 + * 注意:只能使用Stack的基本操作,即push,pop,peek,isEmpty, 可以使用另外一个栈来辅助 + * @param len + * @return + */ + public static Object[] getTop(Stack s,int len) { + return null; + } + /** + * 字符串s 可能包含这些字符: ( ) [ ] { }, a,b,c... x,yz + * 使用堆栈检查字符串s中的括号是不是成对出现的。 + * 例如s = "([e{d}f])" , 则该字符串中的括号是成对出现, 该方法返回true + * 如果 s = "([b{x]y})", 则该字符串中的括号不是成对出现的, 该方法返回false; + * @param s + * @return + */ + public static boolean isValidPairs(String s){ + return false; + } + + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/StackUtilTest.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/StackUtilTest.java new file mode 100644 index 0000000000..76f2cb7668 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/StackUtilTest.java @@ -0,0 +1,65 @@ +package com.coding.basic.stack; + +import java.util.Stack; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +public class StackUtilTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void testReverse() { + Stack s = new Stack(); + s.push(1); + s.push(2); + s.push(3); + s.push(4); + s.push(5); + Assert.assertEquals("[1, 2, 3, 4, 5]", s.toString()); + StackUtil.reverse(s); + Assert.assertEquals("[5, 4, 3, 2, 1]", s.toString()); + } + + @Test + public void testRemove() { + Stack s = new Stack(); + s.push(1); + s.push(2); + s.push(3); + StackUtil.remove(s, 2); + Assert.assertEquals("[1, 3]", s.toString()); + } + + @Test + public void testGetTop() { + Stack s = new Stack(); + s.push(1); + s.push(2); + s.push(3); + s.push(4); + s.push(5); + { + Object[] values = StackUtil.getTop(s, 3); + Assert.assertEquals(5, values[0]); + Assert.assertEquals(4, values[1]); + Assert.assertEquals(3, values[2]); + } + } + + @Test + public void testIsValidPairs() { + Assert.assertTrue(StackUtil.isValidPairs("([e{d}f])")); + Assert.assertFalse(StackUtil.isValidPairs("([b{x]y})")); + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/StackWithTwoQueues.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/StackWithTwoQueues.java new file mode 100644 index 0000000000..d0ab4387d2 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/StackWithTwoQueues.java @@ -0,0 +1,16 @@ +package com.coding.basic.stack; + + +public class StackWithTwoQueues { + + + public void push(int data) { + + } + + public int pop() { + return -1; + } + + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/TwoStackInOneArray.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/TwoStackInOneArray.java new file mode 100644 index 0000000000..e86d056a24 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/TwoStackInOneArray.java @@ -0,0 +1,57 @@ +package com.coding.basic.stack; + +/** + * 用一个数组实现两个栈 + * 将数组的起始位置看作是第一个栈的栈底,将数组的尾部看作第二个栈的栈底,压栈时,栈顶指针分别向中间移动,直到两栈顶指针相遇,则扩容。 + * @author liuxin + * + */ +public class TwoStackInOneArray { + Object[] data = new Object[10]; + + /** + * 向第一个栈中压入元素 + * @param o + */ + public void push1(Object o){ + + } + /** + * 从第一个栈中弹出元素 + * @return + */ + public Object pop1(){ + return null; + } + + /** + * 获取第一个栈的栈顶元素 + * @return + */ + + public Object peek1(){ + return null; + } + /* + * 向第二个栈压入元素 + */ + public void push2(Object o){ + + } + /** + * 从第二个栈弹出元素 + * @return + */ + public Object pop2(){ + return null; + } + /** + * 获取第二个栈的栈顶元素 + * @return + */ + + public Object peek2(){ + return null; + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/InfixExpr.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/InfixExpr.java new file mode 100644 index 0000000000..ef85ff007f --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/InfixExpr.java @@ -0,0 +1,15 @@ +package com.coding.basic.stack.expr; + +public class InfixExpr { + String expr = null; + + public InfixExpr(String expr) { + this.expr = expr; + } + + public float evaluate() { + return 0.0f; + } + + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/InfixExprTest.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/InfixExprTest.java new file mode 100644 index 0000000000..20e34e8852 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/InfixExprTest.java @@ -0,0 +1,52 @@ +package com.coding.basic.stack.expr; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + +public class InfixExprTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testEvaluate() { + //InfixExpr expr = new InfixExpr("300*20+12*5-20/4"); + { + InfixExpr expr = new InfixExpr("2+3*4+5"); + Assert.assertEquals(19.0, expr.evaluate(), 0.001f); + } + { + InfixExpr expr = new InfixExpr("3*20+12*5-40/2"); + Assert.assertEquals(100.0, expr.evaluate(), 0.001f); + } + + { + InfixExpr expr = new InfixExpr("3*20/2"); + Assert.assertEquals(30, expr.evaluate(), 0.001f); + } + + { + InfixExpr expr = new InfixExpr("20/2*3"); + Assert.assertEquals(30, expr.evaluate(), 0.001f); + } + + { + InfixExpr expr = new InfixExpr("10-30+50"); + Assert.assertEquals(30, expr.evaluate(), 0.001f); + } + { + InfixExpr expr = new InfixExpr("10-2*3+50"); + Assert.assertEquals(54, expr.evaluate(), 0.001f); + } + + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/InfixToPostfix.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/InfixToPostfix.java new file mode 100644 index 0000000000..96a2194a67 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/InfixToPostfix.java @@ -0,0 +1,14 @@ +package com.coding.basic.stack.expr; + +import java.util.List; + +public class InfixToPostfix { + + public static List convert(String expr) { + + return null; + } + + + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PostfixExpr.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PostfixExpr.java new file mode 100644 index 0000000000..dcbb18be4b --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PostfixExpr.java @@ -0,0 +1,18 @@ +package com.coding.basic.stack.expr; + +import java.util.List; +import java.util.Stack; + +public class PostfixExpr { +String expr = null; + + public PostfixExpr(String expr) { + this.expr = expr; + } + + public float evaluate() { + return 0.0f; + } + + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PostfixExprTest.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PostfixExprTest.java new file mode 100644 index 0000000000..c0435a2db5 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PostfixExprTest.java @@ -0,0 +1,41 @@ +package com.coding.basic.stack.expr; + + + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class PostfixExprTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testEvaluate() { + { + PostfixExpr expr = new PostfixExpr("6 5 2 3 + 8 * + 3 + *"); + Assert.assertEquals(288, expr.evaluate(),0.0f); + } + { + //9+(3-1)*3+10/2 + PostfixExpr expr = new PostfixExpr("9 3 1-3*+ 10 2/+"); + Assert.assertEquals(20, expr.evaluate(),0.0f); + } + + { + //10-2*3+50 + PostfixExpr expr = new PostfixExpr("10 2 3 * - 50 +"); + Assert.assertEquals(54, expr.evaluate(),0.0f); + } + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PrefixExpr.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PrefixExpr.java new file mode 100644 index 0000000000..956927e2df --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PrefixExpr.java @@ -0,0 +1,18 @@ +package com.coding.basic.stack.expr; + +import java.util.List; +import java.util.Stack; + +public class PrefixExpr { + String expr = null; + + public PrefixExpr(String expr) { + this.expr = expr; + } + + public float evaluate() { + return 0.0f; + } + + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PrefixExprTest.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PrefixExprTest.java new file mode 100644 index 0000000000..5cec210e75 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/PrefixExprTest.java @@ -0,0 +1,45 @@ +package com.coding.basic.stack.expr; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + +public class PrefixExprTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testEvaluate() { + { + // 2*3+4*5 + PrefixExpr expr = new PrefixExpr("+ * 2 3* 4 5"); + Assert.assertEquals(26, expr.evaluate(),0.001f); + } + { + // 4*2 + 6+9*2/3 -8 + PrefixExpr expr = new PrefixExpr("-++6/*2 9 3 * 4 2 8"); + Assert.assertEquals(12, expr.evaluate(),0.001f); + } + { + //(3+4)*5-6 + PrefixExpr expr = new PrefixExpr("- * + 3 4 5 6"); + Assert.assertEquals(29, expr.evaluate(),0.001f); + } + { + //1+((2+3)*4)-5 + PrefixExpr expr = new PrefixExpr("- + 1 * + 2 3 4 5"); + Assert.assertEquals(16, expr.evaluate(),0.001f); + } + + + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/Token.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/Token.java new file mode 100644 index 0000000000..8579743fe9 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/Token.java @@ -0,0 +1,50 @@ +package com.coding.basic.stack.expr; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +class Token { + public static final List OPERATORS = Arrays.asList("+", "-", "*", "/"); + private static final Map priorities = new HashMap<>(); + static { + priorities.put("+", 1); + priorities.put("-", 1); + priorities.put("*", 2); + priorities.put("/", 2); + } + static final int OPERATOR = 1; + static final int NUMBER = 2; + String value; + int type; + public Token(int type, String value){ + this.type = type; + this.value = value; + } + + public boolean isNumber() { + return type == NUMBER; + } + + public boolean isOperator() { + return type == OPERATOR; + } + + public int getIntValue() { + return Integer.valueOf(value).intValue(); + } + public String toString(){ + return value; + } + + public boolean hasHigherPriority(Token t){ + if(!this.isOperator() && !t.isOperator()){ + throw new RuntimeException("numbers can't compare priority"); + } + return priorities.get(this.value) - priorities.get(t.value) > 0; + } + + + +} \ No newline at end of file diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/TokenParser.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/TokenParser.java new file mode 100644 index 0000000000..d3b0f167e1 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/TokenParser.java @@ -0,0 +1,57 @@ +package com.coding.basic.stack.expr; + +import java.util.ArrayList; +import java.util.List; + +public class TokenParser { + + + public List parse(String expr) { + List tokens = new ArrayList<>(); + + int i = 0; + + while (i < expr.length()) { + + char c = expr.charAt(i); + + if (isOperator(c)) { + + Token t = new Token(Token.OPERATOR, String.valueOf(c)); + tokens.add(t); + i++; + + } else if (Character.isDigit(c)) { + + int nextOperatorIndex = indexOfNextOperator(i, expr); + String value = expr.substring(i, nextOperatorIndex); + Token t = new Token(Token.NUMBER, value); + tokens.add(t); + i = nextOperatorIndex; + + } else{ + System.out.println("char :["+c+"] is not number or operator,ignore"); + i++; + } + + } + return tokens; + } + + private int indexOfNextOperator(int i, String expr) { + + while (Character.isDigit(expr.charAt(i))) { + i++; + if (i == expr.length()) { + break; + } + } + return i; + + } + + private boolean isOperator(char c) { + String sc = String.valueOf(c); + return Token.OPERATORS.contains(sc); + } +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/TokenParserTest.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/TokenParserTest.java new file mode 100644 index 0000000000..399d3e857e --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/stack/expr/TokenParserTest.java @@ -0,0 +1,41 @@ +package com.coding.basic.stack.expr; + +import static org.junit.Assert.*; + +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class TokenParserTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void test() { + + TokenParser parser = new TokenParser(); + List tokens = parser.parse("300*20+12*5-20/4"); + + Assert.assertEquals(300, tokens.get(0).getIntValue()); + Assert.assertEquals("*", tokens.get(1).toString()); + Assert.assertEquals(20, tokens.get(2).getIntValue()); + Assert.assertEquals("+", tokens.get(3).toString()); + Assert.assertEquals(12, tokens.get(4).getIntValue()); + Assert.assertEquals("*", tokens.get(5).toString()); + Assert.assertEquals(5, tokens.get(6).getIntValue()); + Assert.assertEquals("-", tokens.get(7).toString()); + Assert.assertEquals(20, tokens.get(8).getIntValue()); + Assert.assertEquals("/", tokens.get(9).toString()); + Assert.assertEquals(4, tokens.get(10).getIntValue()); + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/tree/BinarySearchTree.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/tree/BinarySearchTree.java new file mode 100644 index 0000000000..4536ee7a2b --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/tree/BinarySearchTree.java @@ -0,0 +1,55 @@ +package com.coding.basic.tree; + +import java.util.ArrayList; +import java.util.List; + +import com.coding.basic.queue.Queue; + +public class BinarySearchTree { + + BinaryTreeNode root; + public BinarySearchTree(BinaryTreeNode root){ + this.root = root; + } + public BinaryTreeNode getRoot(){ + return root; + } + public T findMin(){ + return null; + } + public T findMax(){ + return null; + } + public int height() { + return -1; + } + public int size() { + return -1; + } + public void remove(T e){ + + } + public List levelVisit(){ + + return null; + } + public boolean isValid(){ + return false; + } + public T getLowestCommonAncestor(T n1, T n2){ + return null; + + } + /** + * 返回所有满足下列条件的节点的值: n1 <= n <= n2 , n 为 + * 该二叉查找树中的某一节点 + * @param n1 + * @param n2 + * @return + */ + public List getNodesBetween(T n1, T n2){ + return null; + } + +} + diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/tree/BinarySearchTreeTest.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/tree/BinarySearchTreeTest.java new file mode 100644 index 0000000000..4a53dbe2f1 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/tree/BinarySearchTreeTest.java @@ -0,0 +1,109 @@ +package com.coding.basic.tree; + +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class BinarySearchTreeTest { + + BinarySearchTree tree = null; + + @Before + public void setUp() throws Exception { + BinaryTreeNode root = new BinaryTreeNode(6); + root.left = new BinaryTreeNode(2); + root.right = new BinaryTreeNode(8); + root.left.left = new BinaryTreeNode(1); + root.left.right = new BinaryTreeNode(4); + root.left.right.left = new BinaryTreeNode(3); + root.left.right.right = new BinaryTreeNode(5); + tree = new BinarySearchTree(root); + } + + @After + public void tearDown() throws Exception { + tree = null; + } + + @Test + public void testFindMin() { + Assert.assertEquals(1, tree.findMin().intValue()); + + } + + @Test + public void testFindMax() { + Assert.assertEquals(8, tree.findMax().intValue()); + } + + @Test + public void testHeight() { + Assert.assertEquals(4, tree.height()); + } + + @Test + public void testSize() { + Assert.assertEquals(7, tree.size()); + } + + @Test + public void testRemoveLeaf() { + tree.remove(3); + BinaryTreeNode root= tree.getRoot(); + Assert.assertEquals(4, root.left.right.data.intValue()); + + } + @Test + public void testRemoveMiddleNode1() { + tree.remove(4); + BinaryTreeNode root= tree.getRoot(); + Assert.assertEquals(5, root.left.right.data.intValue()); + Assert.assertEquals(3, root.left.right.left.data.intValue()); + } + @Test + public void testRemoveMiddleNode2() { + tree.remove(2); + BinaryTreeNode root= tree.getRoot(); + Assert.assertEquals(3, root.left.data.intValue()); + Assert.assertEquals(4, root.left.right.data.intValue()); + } + + @Test + public void testLevelVisit() { + List values = tree.levelVisit(); + Assert.assertEquals("[6, 2, 8, 1, 4, 3, 5]", values.toString()); + + } + @Test + public void testLCA(){ + Assert.assertEquals(2,tree.getLowestCommonAncestor(1, 5).intValue()); + Assert.assertEquals(2,tree.getLowestCommonAncestor(1, 4).intValue()); + Assert.assertEquals(6,tree.getLowestCommonAncestor(3, 8).intValue()); + } + @Test + public void testIsValid() { + + Assert.assertTrue(tree.isValid()); + + BinaryTreeNode root = new BinaryTreeNode(6); + root.left = new BinaryTreeNode(2); + root.right = new BinaryTreeNode(8); + root.left.left = new BinaryTreeNode(4); + root.left.right = new BinaryTreeNode(1); + root.left.right.left = new BinaryTreeNode(3); + tree = new BinarySearchTree(root); + + Assert.assertFalse(tree.isValid()); + } + @Test + public void testGetNodesBetween(){ + List numbers = this.tree.getNodesBetween(3, 8); + System.out.println(numbers.toString()); + + } +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/tree/BinaryTreeNode.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/tree/BinaryTreeNode.java new file mode 100644 index 0000000000..c1421cd398 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/tree/BinaryTreeNode.java @@ -0,0 +1,35 @@ +package com.coding.basic.tree; + +public class BinaryTreeNode { + + public T data; + public BinaryTreeNode left; + public BinaryTreeNode right; + + public BinaryTreeNode(T data){ + this.data=data; + } + public T getData() { + return data; + } + public void setData(T data) { + this.data = data; + } + public BinaryTreeNode getLeft() { + return left; + } + public void setLeft(BinaryTreeNode left) { + this.left = left; + } + public BinaryTreeNode getRight() { + return right; + } + public void setRight(BinaryTreeNode right) { + this.right = right; + } + + public BinaryTreeNode insert(Object o){ + return null; + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/tree/BinaryTreeUtil.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/tree/BinaryTreeUtil.java new file mode 100644 index 0000000000..b033cbe1d5 --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/tree/BinaryTreeUtil.java @@ -0,0 +1,66 @@ +package com.coding.basic.tree; + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +public class BinaryTreeUtil { + /** + * 用递归的方式实现对二叉树的前序遍历, 需要通过BinaryTreeUtilTest测试 + * + * @param root + * @return + */ + public static List preOrderVisit(BinaryTreeNode root) { + List result = new ArrayList(); + + return result; + } + + /** + * 用递归的方式实现对二叉树的中遍历 + * + * @param root + * @return + */ + public static List inOrderVisit(BinaryTreeNode root) { + List result = new ArrayList(); + + return result; + } + + /** + * 用递归的方式实现对二叉树的后遍历 + * + * @param root + * @return + */ + public static List postOrderVisit(BinaryTreeNode root) { + List result = new ArrayList(); + + return result; + } + /** + * 用非递归的方式实现对二叉树的前序遍历 + * @param root + * @return + */ + public static List preOrderWithoutRecursion(BinaryTreeNode root) { + + List result = new ArrayList(); + + return result; + } + /** + * 用非递归的方式实现对二叉树的中序遍历 + * @param root + * @return + */ + public static List inOrderWithoutRecursion(BinaryTreeNode root) { + + List result = new ArrayList(); + + return result; + } + +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/tree/BinaryTreeUtilTest.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/tree/BinaryTreeUtilTest.java new file mode 100644 index 0000000000..41857e137d --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/tree/BinaryTreeUtilTest.java @@ -0,0 +1,75 @@ +package com.coding.basic.tree; + +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class BinaryTreeUtilTest { + + BinaryTreeNode root = null; + @Before + public void setUp() throws Exception { + root = new BinaryTreeNode(1); + root.setLeft(new BinaryTreeNode(2)); + root.setRight(new BinaryTreeNode(5)); + root.getLeft().setLeft(new BinaryTreeNode(3)); + root.getLeft().setRight(new BinaryTreeNode(4)); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testPreOrderVisit() { + + List result = BinaryTreeUtil.preOrderVisit(root); + Assert.assertEquals("[1, 2, 3, 4, 5]", result.toString()); + + + } + @Test + public void testInOrderVisit() { + + + List result = BinaryTreeUtil.inOrderVisit(root); + Assert.assertEquals("[3, 2, 4, 1, 5]", result.toString()); + + } + + @Test + public void testPostOrderVisit() { + + + List result = BinaryTreeUtil.postOrderVisit(root); + Assert.assertEquals("[3, 4, 2, 5, 1]", result.toString()); + + } + + + @Test + public void testInOrderVisitWithoutRecursion() { + BinaryTreeNode node = root.getLeft().getRight(); + node.setLeft(new BinaryTreeNode(6)); + node.setRight(new BinaryTreeNode(7)); + + List result = BinaryTreeUtil.inOrderWithoutRecursion(root); + Assert.assertEquals("[3, 2, 6, 4, 7, 1, 5]", result.toString()); + + } + @Test + public void testPreOrderVisitWithoutRecursion() { + BinaryTreeNode node = root.getLeft().getRight(); + node.setLeft(new BinaryTreeNode(6)); + node.setRight(new BinaryTreeNode(7)); + + List result = BinaryTreeUtil.preOrderWithoutRecursion(root); + Assert.assertEquals("[1, 2, 3, 4, 6, 7, 5]", result.toString()); + + } +} diff --git a/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/tree/FileList.java b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/tree/FileList.java new file mode 100644 index 0000000000..6e65192e4a --- /dev/null +++ b/students/250103158/data-structure/assignment/src/main/java/com/coding/basic/tree/FileList.java @@ -0,0 +1,10 @@ +package com.coding.basic.tree; + +import java.io.File; + +public class FileList { + public void list(File f) { + } + + +} diff --git a/students/250103158/ood/ood-assignment/pom.xml b/students/250103158/ood/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/250103158/ood/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/250103158/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/250103158/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/250103158/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/250103158/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/250103158/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/250103158/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/250103158/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/250103158/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/250103158/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/250103158/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/250103158/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..9f9e749af7 --- /dev/null +++ b/students/250103158/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/250103158/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/250103158/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..781587a846 --- /dev/null +++ b/students/250103158/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,199 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery = null; + + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected String productID = null; + protected String productDesc = null; + + private static Configuration config; + + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + + + config = new Configuration(); + + setSMTPHost(); + setAltSMTPHost(); + + + setFromAddress(); + + + setLoadQuery(); + + sendEMails(mailDebug, loadMailingList()); + + + } + + + + + protected void setProductID(String productID) + { + this.productID = productID; + + } + + protected String getproductID() + { + return productID; + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected void setSMTPHost() + { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() + { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + protected void setFromAddress() + { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setMessage(HashMap userInfo) throws IOException + { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + + + + } + + + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + private void setProductDesc(String desc) { + this.productDesc = desc; + } + + + protected void configureEMail(HashMap userInfo) throws IOException + { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try + { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } + + else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/250103158/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/250103158/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/250103158/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/251822722/ocp/logType/LogType.java b/students/251822722/ocp/logType/LogType.java new file mode 100644 index 0000000000..a5e4774518 --- /dev/null +++ b/students/251822722/ocp/logType/LogType.java @@ -0,0 +1,12 @@ +package ocp.logType; + +/** + * ocp.ocp + * Created by Eric Wang on 6/21/17. + */ +public interface LogType { + + void setMessage(String message); + + String getMessage(); +} diff --git a/students/251822722/ocp/logType/RawLog.java b/students/251822722/ocp/logType/RawLog.java new file mode 100644 index 0000000000..cdbd4931fe --- /dev/null +++ b/students/251822722/ocp/logType/RawLog.java @@ -0,0 +1,21 @@ +package ocp.logType; + +/** + * ocp.ocp.logType + * Created by Eric Wang on 6/21/17. + */ +public class RawLog implements LogType{ + + private String logMsg; + + @Override + public void setMessage(String message) { + logMsg = message; + + } + + @Override + public String getMessage() { + return logMsg; + } +} diff --git a/students/251822722/ocp/logType/RawLogWithDate.java b/students/251822722/ocp/logType/RawLogWithDate.java new file mode 100644 index 0000000000..03044c7229 --- /dev/null +++ b/students/251822722/ocp/logType/RawLogWithDate.java @@ -0,0 +1,26 @@ +package ocp.logType; + +import ocp.util.DateUtil; + +/** + * ocp.ocp.logType + * Created by Eric Wang on 6/21/17. + */ +public class RawLogWithDate implements LogType { + + + private String logMsg; + + @Override + public void setMessage(String message) { + + String txtDate = DateUtil.getCurrentDateAsString(); + logMsg = txtDate + ": " + message; + + } + + @Override + public String getMessage() { + return logMsg; + } +} diff --git a/students/251822722/ocp/logger/DateLogger.java b/students/251822722/ocp/logger/DateLogger.java new file mode 100644 index 0000000000..ddffbc0d91 --- /dev/null +++ b/students/251822722/ocp/logger/DateLogger.java @@ -0,0 +1,23 @@ +package ocp.logger; + +import ocp.logType.LogType; + +/** + * ocp.ocp.logger + * Created by Eric Wang on 6/21/17. + */ +public class DateLogger extends Logger { + + LogType logType; + + public DateLogger(LogType logType) { + this.logType = logType; + } + + + public void log(String msg) { + + this.logType.setMessage(msg); + System.out.println(logType.getMessage()); + } +} diff --git a/students/251822722/ocp/logger/Logger.java b/students/251822722/ocp/logger/Logger.java new file mode 100644 index 0000000000..2c72f293de --- /dev/null +++ b/students/251822722/ocp/logger/Logger.java @@ -0,0 +1,60 @@ +package ocp.logger; + +import ocp.logType.LogType; +import ocp.logType.RawLog; +import ocp.logType.RawLogWithDate; + +public class Logger { + + public final int RAW_LOG = 1; + public final int RAW_LOG_WITH_DATE = 2; + public final int EMAIL_LOG = 1; + public final int SMS_LOG = 2; + public final int PRINT_LOG = 3; + + public Logger(){ + + } + + + + public Logger getLogger(int logType, int logMethod) { + + LogType logTypeClass; + Logger logger; + + + switch (logType) { + case RAW_LOG: + logTypeClass = new RawLog(); + break; + case RAW_LOG_WITH_DATE: + logTypeClass = new RawLogWithDate(); + break; + default: + logTypeClass = new RawLog(); + + } + + + switch (logMethod) { + case EMAIL_LOG: + logger = new MailLogger(logTypeClass); + break; + case SMS_LOG: + logger = new SMSLogger(logTypeClass); + break; + case PRINT_LOG: + logger = new DateLogger(logTypeClass); + break; + default: + logger = new MailLogger(logTypeClass); + + } + + return logger; + + + } +} + diff --git a/students/251822722/ocp/logger/MailLogger.java b/students/251822722/ocp/logger/MailLogger.java new file mode 100644 index 0000000000..02878d1172 --- /dev/null +++ b/students/251822722/ocp/logger/MailLogger.java @@ -0,0 +1,24 @@ +package ocp.logger; + +import ocp.util.MailUtil; +import ocp.logType.LogType; + +/** + * ocp.ocp.logger + * Created by Eric Wang on 6/21/17. + */ +public class MailLogger extends Logger { + + LogType logType; + + public MailLogger(LogType logType) { + this.logType = logType; + } + + + public void log(String msg) { + + this.logType.setMessage(msg); + MailUtil.send(logType.getMessage()); + } +} diff --git a/students/251822722/ocp/logger/SMSLogger.java b/students/251822722/ocp/logger/SMSLogger.java new file mode 100644 index 0000000000..d9c5ca30f7 --- /dev/null +++ b/students/251822722/ocp/logger/SMSLogger.java @@ -0,0 +1,24 @@ +package ocp.logger; + +import ocp.util.SMSUtil; +import ocp.logType.LogType; + +/** + * ocp.ocp.logger + * Created by Eric Wang on 6/21/17. + */ +public class SMSLogger extends Logger { + + LogType logType; + + public SMSLogger(LogType logType) { + this.logType = logType; + } + + + public void log(String msg) { + + this.logType.setMessage(msg); + SMSUtil.send(logType.getMessage()); + } +} diff --git a/students/251822722/ocp/util/DateUtil.java b/students/251822722/ocp/util/DateUtil.java new file mode 100644 index 0000000000..a4361d96c0 --- /dev/null +++ b/students/251822722/ocp/util/DateUtil.java @@ -0,0 +1,10 @@ +package ocp.util; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return null; + } + +} diff --git a/students/251822722/ocp/util/MailUtil.java b/students/251822722/ocp/util/MailUtil.java new file mode 100644 index 0000000000..63c497f111 --- /dev/null +++ b/students/251822722/ocp/util/MailUtil.java @@ -0,0 +1,10 @@ +package ocp.util; + +public class MailUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/251822722/ocp/util/SMSUtil.java b/students/251822722/ocp/util/SMSUtil.java new file mode 100644 index 0000000000..a31e93837c --- /dev/null +++ b/students/251822722/ocp/util/SMSUtil.java @@ -0,0 +1,10 @@ +package ocp.util; + +public class SMSUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/251822722/srp/DBUtil.java b/students/251822722/srp/DBUtil.java new file mode 100644 index 0000000000..87eef49802 --- /dev/null +++ b/students/251822722/srp/DBUtil.java @@ -0,0 +1,42 @@ +package com.coderising.ood.srp; + +import com.coderising.ood.srp.product.Product; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * + * @param sql + * @return + */ + public static List query(String sql) { + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "user" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } + + + public static Product queryProduct( + String productDesc, + + String productID) { + + //TODO + + return new Product(); + } + + +} diff --git a/students/251822722/srp/MailUtil.java b/students/251822722/srp/MailUtil.java new file mode 100644 index 0000000000..22b08893fa --- /dev/null +++ b/students/251822722/srp/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost + ) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/251822722/srp/PromotionMailTest.java b/students/251822722/srp/PromotionMailTest.java new file mode 100644 index 0000000000..3f70beac6a --- /dev/null +++ b/students/251822722/srp/PromotionMailTest.java @@ -0,0 +1,62 @@ +package com.coderising.ood.srp; + +import com.coderising.ood.srp.product.Product; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class PromotionMailTest { + + + public static void main(String[] args) throws Exception { + + + //load change info + File file = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + List products = getUpdateProduct(file); + + + //update message for user + products.stream().forEach(p -> { + p.notifyUserPriceChange(); + }); + + + } + + + protected static List getUpdateProduct(File file) throws IOException // @02C + { + + List productMap = new ArrayList(); + + + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + + + String temp = br.readLine(); + String[] data = temp.split(" "); + + Product product = DBUtil.queryProduct(data[0], data[1]); + productMap.add(product); + + System.out.println("产品ID = " + data[0] + "\n"); + System.out.println("产品描述 = " + data[1] + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + + return productMap; + } + + +} diff --git a/students/251822722/srp/mail/Mail.java b/students/251822722/srp/mail/Mail.java new file mode 100644 index 0000000000..6e0d145c07 --- /dev/null +++ b/students/251822722/srp/mail/Mail.java @@ -0,0 +1,15 @@ +package com.coderising.ood.srp.mail; + +import com.coderising.ood.srp.product.Product; +import com.coderising.ood.srp.user.User; + + +/** + * com.coderising.ood.srp + * Created by Eric Wang on 6/19/17. + */ +public interface Mail { + + + void sendPriceChangeEmail(User user, Product product); +} diff --git a/students/251822722/srp/mail/PromotionMail.java b/students/251822722/srp/mail/PromotionMail.java new file mode 100644 index 0000000000..a6bbc98bf6 --- /dev/null +++ b/students/251822722/srp/mail/PromotionMail.java @@ -0,0 +1,94 @@ +package com.coderising.ood.srp.mail; + +import com.coderising.ood.srp.product.Product; +import com.coderising.ood.srp.server.SmtpMailServer; +import com.coderising.ood.srp.setting.SystemSetting; +import com.coderising.ood.srp.user.User; + +import java.io.File; + +/** + * com.coderising.ood.srp.mail + * Created by Eric Wang on 6/19/17. + */ +public class PromotionMail implements Mail { + + String form; + String to; + String subject; + String message; + + SmtpMailServer smtpMailServer = new SmtpMailServer(); + + + private void createPriceChangeEmailBody(User user, Product product) { + + + subject = "您关注的产品降价了"; + message = "尊敬的 " + user.getUserName() + ", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!"; + + + } + + @Override + public void sendPriceChangeEmail(User user, Product product) { + + createPriceChangeEmailBody(user, product); + setFrom(); + setTo(user); + + smtpMailServer.sendEmail(this); + + + + } + + private void setTo(User user) { + to=user.getUserEmail(); + } + + private void setFrom() { + form= SystemSetting.getAdmin(); + } + + + public String getForm() { + return form; + } + + public void setForm(String form) { + this.form = form; + } + + public String getTo() { + return to; + } + + public void setTo(String to) { + this.to = to; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public SmtpMailServer getSmtpMailServer() { + return smtpMailServer; + } + + public void setSmtpMailServer(SmtpMailServer smtpMailServer) { + this.smtpMailServer = smtpMailServer; + } +} diff --git a/students/251822722/srp/product/Product.java b/students/251822722/srp/product/Product.java new file mode 100644 index 0000000000..4aafee3637 --- /dev/null +++ b/students/251822722/srp/product/Product.java @@ -0,0 +1,57 @@ +package com.coderising.ood.srp.product; + +import com.coderising.ood.srp.DBUtil; +import com.coderising.ood.srp.user.User; + +import java.util.List; + +/** + * com.coderising.ood.srp.product + * Created by Eric Wang on 6/19/17. + */ +public class Product { + String productDesc = null; + + String productID = null; + + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + + public void notifyUserPriceChange() { + + + List userList = DBUtil.query(setLoadQuery(this.productID)); + + userList.stream().forEach(user -> { + user.sendPriceChangeEmail(this); + }); + + } + + private String setLoadQuery(String productID) { + + System.out.println("loadQuery set"); + + return "Select name from subscriptions " + + "where product_id= '" + productID + "' " + + "and send_mail=1 "; + + + } + +} diff --git a/students/251822722/srp/product_promotion.txt b/students/251822722/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/251822722/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/251822722/srp/server/SmtpMailServer.java b/students/251822722/srp/server/SmtpMailServer.java new file mode 100644 index 0000000000..d7ff260587 --- /dev/null +++ b/students/251822722/srp/server/SmtpMailServer.java @@ -0,0 +1,42 @@ +package com.coderising.ood.srp.server; + +import com.coderising.ood.srp.MailUtil; +import com.coderising.ood.srp.mail.PromotionMail; +import com.coderising.ood.srp.setting.SystemSetting; +import com.coderising.ood.srp.setting.config.ConfigurationKeys; + +/** + * com.coderising.ood.srp + * Created by Eric Wang on 6/19/17. + */ +public class SmtpMailServer { + + + private static final String smtpHost = SystemSetting.getConfig().getProperty(ConfigurationKeys.SMTP_SERVER); + ; + private static final String altSmtpHost = SystemSetting.getConfig().getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + + public void sendEmail(PromotionMail promotionMail) { + + + System.out.println("开始发送邮件"); + + try { + MailUtil.sendEmail(promotionMail.getTo(), promotionMail.getForm(), promotionMail.getSubject(), promotionMail.getMessage(), smtpHost); + } catch (Exception e) { + + try { + MailUtil.sendEmail(promotionMail.getTo(), promotionMail.getForm(), promotionMail.getSubject(), promotionMail.getMessage(), altSmtpHost); + + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + +} + + + diff --git a/students/251822722/srp/setting/SystemSetting.java b/students/251822722/srp/setting/SystemSetting.java new file mode 100644 index 0000000000..6e99d923fe --- /dev/null +++ b/students/251822722/srp/setting/SystemSetting.java @@ -0,0 +1,26 @@ +package com.coderising.ood.srp.setting; + +import com.coderising.ood.srp.setting.config.Configuration; +import com.coderising.ood.srp.setting.config.ConfigurationKeys; + +/** + * com.coderising.ood.srp.setting + * Created by Eric Wang on 6/19/17. + */ +public class SystemSetting { + + + private static Configuration config = new Configuration(); + + + + public static Configuration getConfig() { + return config; + } + + public static String getAdmin() { + + return config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + +} diff --git a/students/251822722/srp/setting/config/Configuration.java b/students/251822722/srp/setting/config/Configuration.java new file mode 100644 index 0000000000..c81fc885ed --- /dev/null +++ b/students/251822722/srp/setting/config/Configuration.java @@ -0,0 +1,27 @@ +package com.coderising.ood.srp.setting.config; + +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap(); + + static { + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/251822722/srp/setting/config/ConfigurationKeys.java b/students/251822722/srp/setting/config/ConfigurationKeys.java new file mode 100644 index 0000000000..3a5d230e78 --- /dev/null +++ b/students/251822722/srp/setting/config/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp.setting.config; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/251822722/srp/user/User.java b/students/251822722/srp/user/User.java new file mode 100644 index 0000000000..da7d3ecbb5 --- /dev/null +++ b/students/251822722/srp/user/User.java @@ -0,0 +1,41 @@ +package com.coderising.ood.srp.user; + +import com.coderising.ood.srp.mail.Mail; +import com.coderising.ood.srp.mail.PromotionMail; +import com.coderising.ood.srp.product.Product; + + +/** + * com.coderising.ood.srp.user + * Created by Eric Wang on 6/19/17. + */ +public class User { + + Mail mail = new PromotionMail(); + + String userName ; + + String userEmail; + + public void sendPriceChangeEmail(Product product) { + + mail.sendPriceChangeEmail(this, product); + + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getUserEmail() { + return userEmail; + } + + public void setUserEmail(String userEmail) { + this.userEmail = userEmail; + } +} diff --git a/students/252705978/ood/srp/pom.xml b/students/252705978/ood/srp/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/252705978/ood/srp/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/Configuration.java b/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/ConfigurationUtil.java b/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/ConfigurationUtil.java new file mode 100644 index 0000000000..3f5d95cc50 --- /dev/null +++ b/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/ConfigurationUtil.java @@ -0,0 +1,31 @@ +package com.coderising.ood.srp; + +import java.util.HashMap; + +/** + * 邮件配置工具类 + * + * @author lin + * @since + */ +public class ConfigurationUtil { + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + public static void configure(PromotionMail mail, Configuration config) { + mail.smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + mail.altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + mail.fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + + } + + public static void configure2(PromotionMail mail, HashMap userInfo, Product product) { + mail.toAddress = (String) userInfo.get(EMAIL_KEY); + if (mail.toAddress.length() > 0) { + String name = (String) userInfo.get(NAME_KEY); + + mail.subject = "您关注的产品降价了"; + mail.message = "尊敬的 " + name + ", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!"; + } + } +} diff --git a/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/FileUtil.java b/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/FileUtil.java new file mode 100644 index 0000000000..f9c67fea16 --- /dev/null +++ b/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/FileUtil.java @@ -0,0 +1,28 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +/** + * 文件工具类 + * + * @author lin + * @since + */ +public class FileUtil { + public static String[] readFile(File file) throws IOException { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + return data; + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } +} diff --git a/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..04bab2b8a9 --- /dev/null +++ b/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,52 @@ +package com.coderising.ood.srp; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, boolean debug) { + // 假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + @SuppressWarnings("rawtypes") + public static void sendEMails(PromotionMail mail, Configuration config, boolean debug, Product product, List mailingList) throws IOException { + + System.out.println("开始发送邮件"); + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + ConfigurationUtil.configure2(mail, (HashMap) iter.next(), product); + try { + if (mail.toAddress.length() > 0) + MailUtil.sendEmail(mail.toAddress, mail.fromAddress, mail.subject, mail.message, mail.smtpHost, debug); + } catch (Exception e) { + + try { + MailUtil.sendEmail(mail.toAddress, mail.fromAddress, mail.subject, mail.message, mail.altSmtpHost, debug); + + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + } + + else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/Product.java b/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..833b2a98f5 --- /dev/null +++ b/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,41 @@ +package com.coderising.ood.srp; + +/** + * 产品实体类 + * + * @author lin + * @since + */ +public class Product { + private String productID; + private String productDesc; + + public Product() { + } + + public Product(String productID, String productDesc) { + this.productID = productID; + this.productDesc = productDesc; + } + + public Product(String[] strs) { + setProductID(strs[0]); + setProductDesc(strs[1]); + } + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git a/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..83af138d3b --- /dev/null +++ b/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,27 @@ +package com.coderising.ood.srp; + +import java.io.File; + +public class PromotionMail { + + protected String sendMailQuery = null; + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + public PromotionMail() { + }; + + public static void main(String[] args) throws Exception { + PromotionMail mail = new PromotionMail(); + Product product = new Product(FileUtil.readFile(new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"))); + Configuration config = new Configuration(); + ConfigurationUtil.configure(mail, config); + MailUtil.sendEMails(mail, config, false, product, DBUtil.query(mail.sendMailQuery)); + } + +} diff --git a/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/252705978/ood/srp/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/254647832/src/com/coderising/ood/bean/MailBean.java b/students/254647832/src/com/coderising/ood/bean/MailBean.java new file mode 100644 index 0000000000..2befb197fe --- /dev/null +++ b/students/254647832/src/com/coderising/ood/bean/MailBean.java @@ -0,0 +1,57 @@ +package com.coderising.ood.bean; + +/** + *

Title: MailBean

+ *

Description: 邮件信息

+ *

Company: smartisan

+ * @author Administrator + * @date 2017年6月18日 + */ +public class MailBean { + + /** + * 收件箱地址 + */ + private String toAddress; + + /** + * 邮件主题 + */ + private String subject; + + /** + * 邮件内容 + */ + private String message; + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @Override + public String toString() { + return "MailBean [toAddress=" + toAddress + ", subject=" + subject + + ", message=" + message + "]"; + } + +} diff --git a/students/254647832/src/com/coderising/ood/bean/ProductBean.java b/students/254647832/src/com/coderising/ood/bean/ProductBean.java new file mode 100644 index 0000000000..f8ae0bfb00 --- /dev/null +++ b/students/254647832/src/com/coderising/ood/bean/ProductBean.java @@ -0,0 +1,56 @@ +package com.coderising.ood.bean; + +import java.util.List; + +/** + *

Title: ProductBean

+ *

Description: 产品信息

+ *

Company: smartisan

+ * @author Administrator + * @date 2017年6月18日 + */ +public class ProductBean { + + /** + * 产品编号 + */ + private String productID; + + /** + * 产品描述 + */ + private String productDesc; + + private List users; + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + + public List getUsers() { + return users; + } + + public void setUsers(List users) { + this.users = users; + } + + @Override + public String toString() { + return "ProductBean [productID=" + productID + ", productDesc=" + + productDesc + ", users=" + users + "]"; + } + +} diff --git a/students/254647832/src/com/coderising/ood/bean/UserBean.java b/students/254647832/src/com/coderising/ood/bean/UserBean.java new file mode 100644 index 0000000000..c1f36a3ef7 --- /dev/null +++ b/students/254647832/src/com/coderising/ood/bean/UserBean.java @@ -0,0 +1,85 @@ +package com.coderising.ood.bean; + +import java.util.List; + +/** + *

Title: UserBean

+ *

Description: 用户信息

+ *

Company: smartisan

+ * @author Administrator + * @date 2017年6月18日 + */ +public class UserBean { + + /** + * 用户ID + */ + private String userid; + + /** + * 用户姓名 + */ + private String name; + + /** + * 邮箱 + */ + private String email; + + /** + * 邮件推送标识 0-不推送;1-推送 + */ + private String sendFlag; + + /** + * 关注的产品 + */ + private List pros; + + public String getUserid() { + return userid; + } + + public void setUserid(String userid) { + this.userid = userid; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getSendFlag() { + return sendFlag; + } + + public void setSendFlag(String sendFlag) { + this.sendFlag = sendFlag; + } + + public List getPros() { + return pros; + } + + public void setPros(List pros) { + this.pros = pros; + } + + @Override + public String toString() { + return "UserBean [userid=" + userid + ", name=" + name + ", email=" + + email + ", sendFlag=" + sendFlag + ", pros=" + pros + "]"; + } + +} diff --git a/students/254647832/src/com/coderising/ood/srp/Configuration.java b/students/254647832/src/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..5e384821d0 --- /dev/null +++ b/students/254647832/src/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,30 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +/** + *

Title: Configuration

+ *

Description: 获取配置信息

+ *

Company: smartisan

+ * @author Administrator + * @date 2017年6月18日 + */ +public class Configuration { + //封装成私有变量 + private static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/254647832/src/com/coderising/ood/srp/ConfigurationKeys.java b/students/254647832/src/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..70606dda99 --- /dev/null +++ b/students/254647832/src/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,16 @@ +package com.coderising.ood.srp; + +/** + *

Title: ConfigurationKeys

+ *

Description: 邮件服务器配置参数

+ *

Company: smartisan

+ * @author Administrator + * @date 2017年6月18日 + */ +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/254647832/src/com/coderising/ood/srp/DBUtil.java b/students/254647832/src/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..4cb4d8ac30 --- /dev/null +++ b/students/254647832/src/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,60 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import com.coderising.ood.bean.ProductBean; +import com.coderising.ood.bean.UserBean; + +/** + *

Title: DBUtil

+ *

Description: 数据库操作

+ *

Company: smartisan

+ * @author Administrator + * @date 2017年6月18日 + */ +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * 用户和关注的产品,应该是多对多的关系,应该有张多对多的表[用户id + 产品id] + * 先根据产品id查询出用户id,再根据用户id查询出用户信息。此处省略这部分的处理 + * @param sql + * @return + */ + public static List query(Set proIds){ + + /** + * SELECT name, email FROM user WHERE userid IN( + * SELECT userid FROM user_pro WHERE proId in(proIds)) + */ + StringBuilder sendMailQuery = new StringBuilder(); + sendMailQuery.append("Select name from subscriptions where send_mail=1 and product_id in("); + + Iterator iter = proIds.iterator(); + while(iter.hasNext()){ + sendMailQuery.append("'" + iter.next() + "',"); + } + sendMailQuery.delete(sendMailQuery.length()-1, sendMailQuery.length()).append(")"); + + List proList = new ArrayList(); + ProductBean proBean = null; + List userList = new ArrayList(); + UserBean userInfo = null; + for (int i = 1; i <= 3; i++) { + userInfo = new UserBean(); + userInfo.setName("User_" + i); + userInfo.setEmail("aa@bb.com_" + i); + proBean = new ProductBean(); + proBean.setProductID("pro_" + i); + proBean.setProductDesc("proDesc_" + i); + proList.add(proBean); + userInfo.setPros(proList); + userList.add(userInfo); + } + + return userList; + } + +} diff --git a/students/254647832/src/com/coderising/ood/srp/MailUtil.java b/students/254647832/src/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..9763abc625 --- /dev/null +++ b/students/254647832/src/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,108 @@ +package com.coderising.ood.srp; + +import java.util.ArrayList; +import java.util.List; + +import com.coderising.ood.bean.MailBean; +import com.coderising.ood.bean.ProductBean; +import com.coderising.ood.bean.UserBean; + +/** + *

Title: MailUtil

+ *

Description: 邮件工具类

+ *

Company: smartisan

+ * @author Administrator + * @date 2017年6月18日 + */ +public class MailUtil { + + /** + * 获取邮件正文信息 + * @param user 用户信息 + * @return 邮件正文 + */ + private static String getMassege(UserBean user){ + List list = user.getPros(); + StringBuilder s = new StringBuilder(); + s.append("尊敬的 "); + s.append(user.getName()); + s.append(", 您关注的产品 "); + for(ProductBean pro : list){ + s.append(pro.getProductDesc()).append("、"); + } + s.delete(s.length()-1, s.length()); + s.append(" 降价了,欢迎购买!"); + return s.toString(); + } + + /** + * 获取待发送的邮件信息列表 + * @param users 用户信息 + * @return 待发送邮件列表 + */ + private static List getMailInf(List users){ + List retList = new ArrayList(); + MailBean mailInf; + //获取邮件服务器配置信息 + if (!users.isEmpty()) { + for(UserBean bean : users){ + mailInf = new MailBean(); + mailInf.setToAddress(bean.getEmail()); + mailInf.setSubject("您关注的产品降价了"); + mailInf.setMessage(getMassege(bean)); + retList.add(mailInf); + } + } + return retList; + } + + /** + * 发送邮件 + * @param users 待发送的用户 + */ + public static void sendEmail(List users) { + List mailList = getMailInf(users); + if(!mailList.isEmpty()){ + //获取邮件服务器信息 + Configuration config = new Configuration(); + String server = config.getProperty(ConfigurationKeys.SMTP_SERVER); + String altServer = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + System.out.println("开始发送邮件..."); + System.out.println("发件箱:" + config.getProperty(ConfigurationKeys.EMAIL_ADMIN)); + + for(MailBean mailInf : mailList){ + try{ + send(server, mailInf); + }catch (Exception e){ + try { + send(altServer, mailInf); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + System.out.println("邮件发送结束..."); + }else{ + System.out.println("没有邮件发送"); + } + + } + + /** + * 邮件发送主方法 + * @param server 发送服务器 + */ + public static void send(String server, MailBean mailInf){ + + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + + buffer.append("To:").append(mailInf.getToAddress()).append("\n"); + buffer.append("Subject:").append(mailInf.getSubject()).append("\n"); + buffer.append("Content:").append(mailInf.getMessage()).append("\n"); + + System.out.println(buffer.toString()); + } + +} diff --git a/students/254647832/src/com/coderising/ood/srp/PromotionMail.java b/students/254647832/src/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..9af969c773 --- /dev/null +++ b/students/254647832/src/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,65 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import com.coderising.ood.bean.UserBean; + +/** + *

Title: PromotionMail

+ *

Description: 邮件发送处理

+ *

Company: smartisan

+ * @author Administrator + * @date 2017年6月18日 + */ +public class PromotionMail { + + public static void main(String[] args) throws Exception { + + //1、获取降价产品信息 + File f = new File("E:\\gitpro\\liuxin\\coding2017\\liuxin\\ood\\ood-assignment\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"); + Set proIds = readFile(f); + + //2、根据降价产品的ID获取关注该产品的用户信息 + List users = DBUtil.query(proIds); + + //3、向这些用户发送邮件 + MailUtil.sendEmail(users); + } + + /** + * 读取文件,获取降价产品信息 + * @param file + * @return 产品信息的ID + * @throws IOException + */ + private static Set readFile(File file) throws IOException{ + Set proIds = new HashSet(); + BufferedReader br = null; + boolean flag = true; + try { + br = new BufferedReader(new FileReader(file)); + while(flag){ + String temp = br.readLine(); + if(temp != null && !"".equals(temp)){ + String[] data = temp.split(" "); + proIds.add(data[0]); + System.out.println("产品ID = " + data[0]); + System.out.println("产品描述 = " + data[1] + "\n"); + }else{ + flag = false; + } + } + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + return proIds; + } +} diff --git a/students/254647832/src/pom.xml b/students/254647832/src/pom.xml new file mode 100644 index 0000000000..1be81576cc --- /dev/null +++ b/students/254647832/src/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/2756638003/srp/pom.xml b/students/2756638003/srp/pom.xml new file mode 100644 index 0000000000..5024466d17 --- /dev/null +++ b/students/2756638003/srp/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ds-assignment + 0.0.1-SNAPSHOT + jar + + ds-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/2756638003/srp/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..6f743552bb --- /dev/null +++ b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,131 @@ +package com.coderising.ood.srp; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import com.coderising.ood.srp.conf.Configuration; +import com.coderising.ood.srp.conf.ConfigurationKeys; +import com.coderising.ood.srp.conf.EmailStatus; +import com.coderising.ood.srp.domain.Product; +import com.coderising.ood.srp.domain.Subscriber; +import com.coderising.ood.srp.util.ConfigUtil; +import com.coderising.ood.srp.util.Email; +import com.coderising.ood.srp.util.MailUtil; +import com.coderising.ood.srp.util.SubscriberUtil; + +public class PromotionMail { + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + + private static Configuration config; + + public static void main(String[] args) throws Exception { + File file = new File("XX/product_promotion.txt"); + boolean emailDebug = false; + new PromotionMail(file, emailDebug); + } + + /** + * 从配置文件中读取商品信息 + */ + private List loadFile(File file) throws IOException { + Map conf = ConfigUtil.readTextFile(file); + List productList = new ArrayList(16); + Set> entrySet = conf.entrySet(); + for (Entry entry : entrySet) { + productList.add(new Product(entry.getKey(), entry.getValue())); + } + return productList; + } + + /** + * 根据商品查询订阅的用户信息 + */ + private List querySubscribersFormFile(List productList) + throws IOException { + StringBuilder query = new StringBuilder( + "Select name from Subscriber where product_id in( "); + for (int i = 0, len = productList.size(); i < len - 1; i++) { + query.append(productList.get(i).getProductID() + " ,"); + } + query.append(productList.get(productList.size() - 1).getProductID()); + query.append(") and send_mail = ?"); + return SubscriberUtil.loadSubscriberList(query.toString(), + EmailStatus.READY); + } + + /** + * 根据订阅者信息生成邮件 + */ + private Email generatorEmail(Subscriber subscriber, String host) { + String subject = "您关注的产品降价了"; + String message = "尊敬的 " + subscriber.getName() + ", 您关注的产品 " + + subscriber.getProduct().getProductDesc() + " 降价了,欢迎购买!"; + return new Email(subscriber.getEmail(), fromAddress, subject, message, + host); + } + + public PromotionMail(File file, boolean mailDebug) throws Exception { + config = new Configuration(); + setSMTPHost(); + setAltSMTPHost(); + setFromAddress(); + // 从配置文件中读取商品信息 + List productList = loadFile(file); + // 根据商品查询订阅的用户信息 + List subscriberList = querySubscribersFormFile(productList); + // 发送邮件 + sendEMails(mailDebug, subscriberList); + } + + /** + * 发送邮件 + */ + protected void sendEMails(boolean debug, List subscriberList) + throws IOException { + System.out.println("开始发送邮件"); + if (subscriberList != null && subscriberList.size() > 0) { + Iterator iter = subscriberList.iterator(); + Subscriber subscriber = null; + + while (iter.hasNext()) { + subscriber = iter.next(); + try { + MailUtil.sendEmail(generatorEmail(subscriber, smtpHost), + debug); + } catch (Exception e) { + try { + MailUtil.sendEmail( + generatorEmail(subscriber, altSmtpHost), debug); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + + e2.getMessage()); + } + } + } + } else { + System.out.println("没有邮件发送"); + } + } + + protected void setSMTPHost() { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + protected void setAltSMTPHost() { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + } + + protected void setFromAddress() { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + +} diff --git a/students/2756638003/srp/src/main/java/com/coderising/ood/srp/conf/Configuration.java b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/conf/Configuration.java new file mode 100644 index 0000000000..444e4cf912 --- /dev/null +++ b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/conf/Configuration.java @@ -0,0 +1,29 @@ +package com.coderising.ood.srp.conf; + +import java.util.HashMap; +import java.util.Map; + +/** + * 邮件服务器配置文件 + */ +public class Configuration { + + static Map configurations = new HashMap<>(); + + static { + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * + * @param key + * @return + */ + public String getProperty(String key) { + return configurations.get(key); + } + +} diff --git a/students/2756638003/srp/src/main/java/com/coderising/ood/srp/conf/ConfigurationKeys.java b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/conf/ConfigurationKeys.java new file mode 100644 index 0000000000..36009abc3d --- /dev/null +++ b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/conf/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp.conf; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/2756638003/srp/src/main/java/com/coderising/ood/srp/conf/EmailStatus.java b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/conf/EmailStatus.java new file mode 100644 index 0000000000..3245a8d468 --- /dev/null +++ b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/conf/EmailStatus.java @@ -0,0 +1,31 @@ +package com.coderising.ood.srp.conf; + +/** + * 邮件发送状态常量 + */ +public enum EmailStatus { + /** + * 未发送 + */ + READY(0), + /** + * 已发送 + */ + SEND(1), + /** + * 已查阅 + */ + RECEIVED(2), + /** + * 被退回 + */ + REJECTED(3); + + @SuppressWarnings("unused") + private int value; + + private EmailStatus(int value) { + this.value = value; + } + +} diff --git a/students/2756638003/srp/src/main/java/com/coderising/ood/srp/conf/product_promotion.txt b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/conf/product_promotion.txt new file mode 100644 index 0000000000..a98917f829 --- /dev/null +++ b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/conf/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo R15 +P4955 Vivo X20 \ No newline at end of file diff --git a/students/2756638003/srp/src/main/java/com/coderising/ood/srp/domain/Product.java b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/domain/Product.java new file mode 100644 index 0000000000..52656e0389 --- /dev/null +++ b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/domain/Product.java @@ -0,0 +1,43 @@ +package com.coderising.ood.srp.domain; + +/** + * 商品类 + */ +public class Product { + + private String productID; + private String productDesc; + + public Product(String productID, String productDesc) { + super(); + this.productID = productID; + this.productDesc = productDesc; + } + + public Product() { + super(); + } + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + + @Override + public String toString() { + return "Product [productID=" + productID + ", productDesc=" + + productDesc + "]"; + } + +} diff --git a/students/2756638003/srp/src/main/java/com/coderising/ood/srp/domain/Subscriber.java b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/domain/Subscriber.java new file mode 100644 index 0000000000..cdef11498f --- /dev/null +++ b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/domain/Subscriber.java @@ -0,0 +1,74 @@ +package com.coderising.ood.srp.domain; + +/** + * 订阅者 + */ +public class Subscriber { + + private String subscriberId; + private String name; + private String email; + private Product product; + private Integer sendStatus; + + public Subscriber(String subscriberId, String name, String email, + Product product) { + super(); + this.subscriberId = subscriberId; + this.name = name; + this.email = email; + this.product = product; + } + + public Subscriber() { + super(); + } + + public String getSubscriberId() { + return subscriberId; + } + + public void setSubscriberId(String subscriberId) { + this.subscriberId = subscriberId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public Product getProduct() { + return product; + } + + public void setProduct(Product product) { + this.product = product; + } + + public Integer getSendStatus() { + return sendStatus; + } + + public void setSendStatus(Integer sendStatus) { + this.sendStatus = sendStatus; + } + + @Override + public String toString() { + return "Subscriber [subscriberId=" + subscriberId + ", name=" + name + + ", email=" + email + ", product=" + product + ", sendStatus=" + + sendStatus + "]"; + } + +} diff --git a/students/2756638003/srp/src/main/java/com/coderising/ood/srp/util/ConfigUtil.java b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/util/ConfigUtil.java new file mode 100644 index 0000000000..4494739dd6 --- /dev/null +++ b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/util/ConfigUtil.java @@ -0,0 +1,33 @@ +package com.coderising.ood.srp.util; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/** + * 配置文件读写工具类 + * + */ +public class ConfigUtil { + + public static Map readTextFile(File file) + throws IOException { + Map conf = new HashMap(); + try (BufferedReader br = new BufferedReader(new FileReader(file));) { + String temp = null; + while ((temp = br.readLine()) != null) { + int indexOf = temp.indexOf(' '); + if (indexOf > -1) { + conf.put(temp.substring(0, indexOf), + temp.substring(indexOf)); + } + } + } catch (IOException e) { + throw new IOException(e.getMessage()); + } + return conf; + } +} diff --git a/students/2756638003/srp/src/main/java/com/coderising/ood/srp/util/DBUtil.java b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/util/DBUtil.java new file mode 100644 index 0000000000..a4facaff0b --- /dev/null +++ b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/util/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp.util; + +import java.util.ArrayList; +import java.util.List; + +import com.coderising.ood.srp.domain.Product; +import com.coderising.ood.srp.domain.Subscriber; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * + * @param sql + * @return + */ + public static List query(String sql, Object... args) { + List list = new ArrayList(16); + for (int i = 1; i <= 3; i++) { + list.add(new Subscriber(String.valueOf(i), "User" + i, "user-" + i + + "@bb.com", new Product("P8756", " iPhone8"))); + } + return list; + } +} diff --git a/students/2756638003/srp/src/main/java/com/coderising/ood/srp/util/Email.java b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/util/Email.java new file mode 100644 index 0000000000..3422aebb2a --- /dev/null +++ b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/util/Email.java @@ -0,0 +1,75 @@ +package com.coderising.ood.srp.util; + +/** + * 邮件类 + */ +public class Email { + + private String toAddress; + private String fromAddress; + private String subject; + private String message; + private String smtpHost; + + public Email(String toAddress, String fromAddress, String subject, + String message, String smtpHost) { + super(); + this.toAddress = toAddress; + this.fromAddress = fromAddress; + this.subject = subject; + this.message = message; + this.smtpHost = smtpHost; + } + + public Email() { + super(); + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getSmtpHost() { + return smtpHost; + } + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + + @Override + public String toString() { + return "Email [toAddress=" + toAddress + ", fromAddress=" + fromAddress + + ", subject=" + subject + ", message=" + message + + ", smtpHost=" + smtpHost + "]"; + } + +} diff --git a/students/2756638003/srp/src/main/java/com/coderising/ood/srp/util/MailUtil.java b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/util/MailUtil.java new file mode 100644 index 0000000000..7994870bef --- /dev/null +++ b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/util/MailUtil.java @@ -0,0 +1,17 @@ +package com.coderising.ood.srp.util; + +/** + * 邮件发送工具类 + */ +public class MailUtil { + public static void sendEmail(Email email, boolean debug) { + // 假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(email.getFromAddress()).append("\n"); + buffer.append("To:").append(email.getToAddress()).append("\n"); + buffer.append("Subject:").append(email.getSubject()).append("\n"); + buffer.append("Content:").append(email.getMessage()).append("\n"); + System.out.println(buffer.toString()); + } + +} diff --git a/students/2756638003/srp/src/main/java/com/coderising/ood/srp/util/SubscriberUtil.java b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/util/SubscriberUtil.java new file mode 100644 index 0000000000..2410a45950 --- /dev/null +++ b/students/2756638003/srp/src/main/java/com/coderising/ood/srp/util/SubscriberUtil.java @@ -0,0 +1,17 @@ +package com.coderising.ood.srp.util; + +import java.util.List; + +import com.coderising.ood.srp.domain.Subscriber; + +/** + * 订阅者查询工具类 + */ +public class SubscriberUtil { + + public static List loadSubscriberList(String sql, + Object... args) { + return DBUtil.query(sql); + } + +} diff --git a/students/275677638/1.txt b/students/275677638/1.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/students/275677638/README.md b/students/275677638/README.md new file mode 100644 index 0000000000..aa7a31b814 --- /dev/null +++ b/students/275677638/README.md @@ -0,0 +1,3 @@ +愿意自荐代码的,可以每个人一个目录 以自己的QQ号命名 ,把自荐的代码放到里边去 + +diff diff --git a/students/276137509/276137509Learning/readme.md b/students/276137509/276137509Learning/readme.md new file mode 100644 index 0000000000..7c847014a2 --- /dev/null +++ b/students/276137509/276137509Learning/readme.md @@ -0,0 +1 @@ +### This is my first project just for testing \ No newline at end of file diff --git a/students/276137509/readme.md b/students/276137509/readme.md new file mode 100644 index 0000000000..065efcdbbe --- /dev/null +++ b/students/276137509/readme.md @@ -0,0 +1 @@ +#### Nightn (杭州-莱顿) 代码仓库 \ No newline at end of file diff --git a/students/277093528/ood-assignment/pom.xml b/students/277093528/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/277093528/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..1cd9f713c8 --- /dev/null +++ b/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,12 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + public static final String MESSAGE_FILE_PATH = "D:\\BaiduYunDownload\\Second_Season\\ood-assignment\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"; + + public static final String NAME_KEY = "NAME"; + public static final String EMAIL_KEY = "EMAIL"; +} diff --git a/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtils.java b/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtils.java new file mode 100644 index 0000000000..e206b0aa24 --- /dev/null +++ b/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtils.java @@ -0,0 +1,39 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +public class FileUtils { + /** + * 解析文件内容 + * @return + * @throws IOException + */ + public static Product readFile() throws IOException { + + BufferedReader br = null; + try { + Product product = new Product(); + File file = new File( ConfigurationKeys.MESSAGE_FILE_PATH ); + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + product.setProductID(data[0]); + product.setProductDesc(data[1]); + + System.out.println("产品ID = " + data[0] + "\n"); + System.out.println("产品描述 = " + data[1] + "\n"); + return product; + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + + } + +} diff --git a/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..5765cb0070 --- /dev/null +++ b/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,82 @@ +package com.coderising.ood.srp; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class MailUtil { + + private static String smtpHost = null; + private static String altSmtpHost = null; + private static String fromAddress = null; + private static String toAddress = null; + private static String subject = null; + private static String message = null; + + static { + Configuration config = new Configuration(); + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected static void sendEmail(String toAddress, String subject, String message, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + protected static void sendEMails(boolean debug,Product product, List mailingList) throws IOException { + + System.out.println("开始发送邮件"); + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next(),product); + try + { + if ( toAddress.length() > 0 ) + sendEmail(toAddress, subject, message, debug); + } + catch (Exception e) + { + + try { + sendEmail(toAddress, subject, message, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + } else { + System.out.println("没有邮件发送"); + + } + + } + + private static void setMessage( HashMap userInfo,Product product) throws IOException { + String name = (String) userInfo.get( ConfigurationKeys.NAME_KEY ); + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!" ; + } + + private static void configureEMail(HashMap userInfo,Product product) throws IOException + { + toAddress = (String) userInfo.get( ConfigurationKeys.EMAIL_KEY ); + if (toAddress.length() > 0) + setMessage( userInfo, product ); + } + + +} diff --git a/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java b/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..ba93dd2f1b --- /dev/null +++ b/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,26 @@ +package com.coderising.ood.srp; + + +public class Product { + + private String productID = null; + + private String productDesc = null; + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + +} diff --git a/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..5c10796dbf --- /dev/null +++ b/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,40 @@ +package com.coderising.ood.srp; + +import java.util.List; + +public class PromotionMail { + + protected String sendMailQuery = null; + private Product product = null; + + public static void main(String[] args) throws Exception { + + boolean emailDebug = false; + PromotionMail pe = new PromotionMail( emailDebug ); + + } + + public PromotionMail( boolean mailDebug ) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + product = FileUtils.readFile(); + + setLoadQuery(); + + MailUtil.sendEMails(mailDebug, product ,loadMailingList()); + + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + product.getProductID() +"' " + + "and send_mail=1 "; + System.out.println("loadQuery set"); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + +} diff --git a/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/277093528/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/279069328/readme.md b/students/279069328/readme.md new file mode 100644 index 0000000000..e84336bfe0 --- /dev/null +++ b/students/279069328/readme.md @@ -0,0 +1,3 @@ +# Coding 2017 + +KevinSmile@coderising \ No newline at end of file diff --git a/students/2816977791/ood/ood-assignment/pom.xml b/students/2816977791/ood/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/bridge/Circle.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/bridge/Circle.java new file mode 100644 index 0000000000..f0395794a4 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/bridge/Circle.java @@ -0,0 +1,35 @@ +package com.coderings.dp.bridge; + +public class Circle implements Shape { + + int x; + int y; + int r; + + private GraphicLibrary graphicLibrary; + + public Circle(int x, int y, int r, GraphicLibrary graphicLibrary) { + this.x = x; + this.y = y; + this.r = r; + this.graphicLibrary = graphicLibrary; + } + + public int getX() { + return x; + } + + public int getY() { + return y; + } + + public int getR() { + return r; + } + + @Override + public void draw() { + graphicLibrary.drawCircle(this); + } + +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/bridge/ClientMain.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/bridge/ClientMain.java new file mode 100644 index 0000000000..0414dd6df9 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/bridge/ClientMain.java @@ -0,0 +1,19 @@ +package com.coderings.dp.bridge; + +/** + * @author nvarchar + * date 2017/7/28 + */ +public class ClientMain { + public static void main(String[] args) { + Shape line = new Line(1,2,1,2,new GraphicLibrary1()); + Shape line2 = new Line(1,2,1,2,new GraphicLibrary2()); + Shape circle = new Circle(1,2,2,new GraphicLibrary1()); + Shape circle2 = new Circle(1,2,1,new GraphicLibrary2()); + + line.draw(); + line2.draw(); + circle.draw(); + circle2.draw(); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/bridge/GraphicLibrary.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/bridge/GraphicLibrary.java new file mode 100644 index 0000000000..d9fcb6ae5a --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/bridge/GraphicLibrary.java @@ -0,0 +1,11 @@ +package com.coderings.dp.bridge; + +/** + * @author nvarchar + * date 2017/7/28 + */ +public interface GraphicLibrary { + void drawLine(Shape shape); + + void drawCircle(Shape shape); +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/bridge/GraphicLibrary1.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/bridge/GraphicLibrary1.java new file mode 100644 index 0000000000..31776b21d8 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/bridge/GraphicLibrary1.java @@ -0,0 +1,24 @@ +package com.coderings.dp.bridge; + +public class GraphicLibrary1 implements GraphicLibrary{ + + @Override + public void drawLine(Shape shape) { + Line line = (Line)shape; + draw_a_line(line.getX1(), line.getY1(), line.getX2(), line.getY2()); + } + + @Override + public void drawCircle(Shape shape) { + Circle circle = (Circle)shape; + draw_a_circle(circle.getX(), circle.getY(), circle.getY()); + } + + public void draw_a_line(int x1, int y1, int x2, int y2){ + System.out.println("graphic1 draw a line..."); + } + public void draw_a_circle(int x,int y, int r){ + System.out.println("graphic1 draw a circle..."); + } + +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/bridge/GraphicLibrary2.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/bridge/GraphicLibrary2.java new file mode 100644 index 0000000000..ee9d7e8685 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/bridge/GraphicLibrary2.java @@ -0,0 +1,23 @@ +package com.coderings.dp.bridge; + +public class GraphicLibrary2 implements GraphicLibrary{ + @Override + public void drawLine(Shape shape) { + Line line = (Line)shape; + drawLine(line.getX1(), line.getX2(), line.getY1(), line.getY2()); + } + + @Override + public void drawCircle(Shape shape) { + Circle circle = (Circle)shape; + drawCircle(circle.getX(), circle.getY(), circle.getY()); + } + + public void drawLine(int x1, int x2, int y1, int y2){ + System.out.println("graphic2 draw a line..."); + } + public void drawCircle(int x,int y, int r){ + System.out.println("graphic2 draw a circle..."); + } + +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/bridge/Line.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/bridge/Line.java new file mode 100644 index 0000000000..3d0b7a9077 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/bridge/Line.java @@ -0,0 +1,40 @@ +package com.coderings.dp.bridge; + +public class Line implements Shape { + private int x1; + private int y1; + private int x2; + private int y2; + + private GraphicLibrary graphicLibrary; + + public Line(int x1, int y1, int x2, int y2, GraphicLibrary graphicLibrary) { + this.x1 = x1; + this.y1 = y1; + this.x2 = x2; + this.y2 = y2; + this.graphicLibrary = graphicLibrary; + } + + public int getX1() { + return x1; + } + + public int getY1() { + return y1; + } + + public int getX2() { + return x2; + } + + public int getY2() { + return y2; + } + + @Override + public void draw() { + graphicLibrary.drawLine(this); + } + +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/bridge/Shape.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/bridge/Shape.java new file mode 100644 index 0000000000..658219a872 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/bridge/Shape.java @@ -0,0 +1,5 @@ +package com.coderings.dp.bridge; + +public interface Shape { + public void draw(); +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/builder/TagBuilder.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/builder/TagBuilder.java new file mode 100644 index 0000000000..becc6a3d37 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/builder/TagBuilder.java @@ -0,0 +1,49 @@ +package com.coderings.dp.builder; + +public class TagBuilder { + + final TagNode rootNode; + + TagNode iteratorNode; + + TagNode prevIteratorNode; + + public TagBuilder(String rootTagName) { + rootNode = new TagNode(rootTagName); + iteratorNode = rootNode; + prevIteratorNode = rootNode; + } + + public TagBuilder addChild(String childTagName) { + TagNode tagNode = new TagNode(childTagName); + iteratorNode.add(tagNode); + + prevIteratorNode = iteratorNode; + iteratorNode = tagNode; + + return this; + } + + public TagBuilder addSibling(String siblingTagName) { + TagNode tagNode = new TagNode(siblingTagName); + prevIteratorNode.add(tagNode); + + iteratorNode = tagNode; + + return this; + } + + public TagBuilder setAttribute(String name, String value) { + iteratorNode.setAttribute(name, value); + return this; + } + + public TagBuilder setText(String value) { + iteratorNode.setValue(value); + return this; + } + + public String toXML() { + return rootNode.toXML(); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/builder/TagBuilderTest.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/builder/TagBuilderTest.java new file mode 100644 index 0000000000..2d6dae918b --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/builder/TagBuilderTest.java @@ -0,0 +1,40 @@ +package com.coderings.dp.builder; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class TagBuilderTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testToXML() { + + TagBuilder builder = new TagBuilder("order"); + + String xml = builder.addChild("line-items") + .addChild("line-item").setAttribute("pid", "P3677").setAttribute("qty", "3") + .addSibling("line-item").setAttribute("pid", "P9877").setAttribute("qty", "10") + .toXML(); + + String expected = "" + + "" + + "" + + "" + + "" + + ""; + + System.out.println(xml); + assertEquals(expected, xml); + } + +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/builder/TagNode.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/builder/TagNode.java new file mode 100644 index 0000000000..28fb0f54b8 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/builder/TagNode.java @@ -0,0 +1,83 @@ +package com.coderings.dp.builder; + +import java.util.ArrayList; +import java.util.List; + +public class TagNode { + private String tagName; + private String tagValue; + private List children = new ArrayList<>(); + private List attributes = new ArrayList<>(); + + public TagNode(String name){ + this.tagName = name; + } + public void add(TagNode child){ + this.children.add(child); + } + public void setAttribute(String name, String value) { + Attribute attr = findAttribute(name); + if(attr != null){ + attr.value = value; + return; + } + + attributes.add(new Attribute(name,value)); + } + private Attribute findAttribute(String name){ + for(Attribute attr : attributes){ + if(attr.name.equals(name)){ + return attr; + } + } + return null; + } + public void setValue(String value) { + this.tagValue = value; + + } + public String getTagName() { + return tagName; + } + public List getChildren() { + return children; + } + + private static class Attribute{ + public Attribute(String name, String value) { + this.name = name; + this.value = value; + } + String name; + String value; + + } + public String toXML(){ + return toXML(this); + } + private String toXML(TagNode node){ + StringBuilder buffer = new StringBuilder(); + buffer.append("<").append(node.tagName); + if(node.attributes.size()> 0){ + for(int i=0;i"); + return buffer.toString(); + } + buffer.append(">"); + for(TagNode childNode : node.children){ + buffer.append(toXML(childNode)); + } + buffer.append(""); + + + return buffer.toString(); + } + private String toXML(Attribute attr){ + return attr.name+"=\""+attr.value + "\""; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/chain/Client.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/chain/Client.java new file mode 100644 index 0000000000..2293c779b3 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/chain/Client.java @@ -0,0 +1,18 @@ +package com.coderings.dp.chain; + + +/** + * @author nvarchar + * date 2017/8/11 + */ +public class Client { + + public static void main(String[] args) { + Logger logger = new StdoutLogger(Logger.DEBUG) + .setNext(new EmailLogger(Logger.NOTICE).setNext(new FileLogger(Logger.ERR).setNext(new EmailLogger(Logger.DEBUG)))); + + logger.message("进入计算函数", Logger.DEBUG); + logger.message("第一步已经完成", Logger.NOTICE); + logger.message("一个致命错误发生", Logger.ERR); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/chain/EmailLogger.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/chain/EmailLogger.java new file mode 100644 index 0000000000..6cde3435de --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/chain/EmailLogger.java @@ -0,0 +1,30 @@ +package com.coderings.dp.chain; + +/** + * @author nvarchar + * date 2017/8/11 + */ +public class EmailLogger implements Logger{ + private int level; + private Logger next; + + public EmailLogger(int level) { + this.level = level; + } + + @Override + public void message(String context, int level) { + if (level >= this.level) { + System.out.println("email :" + context); + } + if (this.next != null) { + this.next.message(context, level); + } + } + + @Override + public Logger setNext(Logger next) { + this.next = next; + return this; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/chain/FileLogger.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/chain/FileLogger.java new file mode 100644 index 0000000000..651e3f0701 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/chain/FileLogger.java @@ -0,0 +1,30 @@ +package com.coderings.dp.chain; + +/** + * @author nvarchar + * date 2017/8/11 + */ +public class FileLogger implements Logger { + private int level; + private Logger next; + + public FileLogger(int level) { + this.level = level; + } + + @Override + public void message(String context, int level) { + if (level >= this.level) { + System.out.println("file :" + context); + } + if (this.next != null) { + this.next.message(context, level); + } + } + + @Override + public Logger setNext(Logger next) { + this.next = next; + return this; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/chain/Logger.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/chain/Logger.java new file mode 100644 index 0000000000..2d707e2ae7 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/chain/Logger.java @@ -0,0 +1,15 @@ +package com.coderings.dp.chain; + +/** + * @author nvarchar + * date 2017/8/11 + */ +public interface Logger { + public static final int DEBUG = 0; + public static final int NOTICE = 1; + public static final int ERR = 2; + + public void message(String context, int level); + + public Logger setNext(Logger next); +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/chain/StdoutLogger.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/chain/StdoutLogger.java new file mode 100644 index 0000000000..ea08e790b4 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/chain/StdoutLogger.java @@ -0,0 +1,30 @@ +package com.coderings.dp.chain; + +/** + * @author nvarchar + * date 2017/8/11 + */ +public class StdoutLogger implements Logger { + private int level; + private Logger next; + + public StdoutLogger(int level) { + this.level = level; + } + + @Override + public void message(String context, int level) { + if (level >= this.level) { + System.out.println("console :" + context); + } + if (this.next != null) { + this.next.message(context, level); + } + } + + @Override + public Logger setNext(Logger next) { + this.next = next; + return this; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/command/Client.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/command/Client.java new file mode 100644 index 0000000000..8dd4ad4c76 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/command/Client.java @@ -0,0 +1,23 @@ +package com.coderings.dp.command; + +/** + * @author nvarchar + * date 2017/8/11 + */ +public class Client { + public static void main(String[] args) { + Cook cook = new Cook(); + + Waiter waiter = new Waiter(); + + Command command1 = new OrderPorkCommand(cook); + Command command2 = new OrderSteakCommand(cook); + Command command3 = new OrderSteakCommand(cook); + + waiter.addOrder(command1); + waiter.addOrder(command2); + waiter.addOrder(command3); + + waiter.sendOrders(); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/command/Command.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/command/Command.java new file mode 100644 index 0000000000..ddc3465eda --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/command/Command.java @@ -0,0 +1,9 @@ +package com.coderings.dp.command; + +/** + * @author nvarchar + * date 2017/8/11 + */ +public interface Command { + void execute(); +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/command/Cook.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/command/Cook.java new file mode 100644 index 0000000000..01d3934d35 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/command/Cook.java @@ -0,0 +1,15 @@ +package com.coderings.dp.command; + +/** + * @author nvarchar + * date 2017/8/11 + */ +public class Cook { + void cookSteak() { + System.out.println("steak is ready"); + } + + void cookPork() { + System.out.println("pork is ready"); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/command/OrderPorkCommand.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/command/OrderPorkCommand.java new file mode 100644 index 0000000000..a575094089 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/command/OrderPorkCommand.java @@ -0,0 +1,18 @@ +package com.coderings.dp.command; + +/** + * @author nvarchar + * date 2017/8/11 + */ +public class OrderPorkCommand implements Command{ + private Cook cook; + + public OrderPorkCommand(Cook cook) { + this.cook = cook; + } + + @Override + public void execute() { + cook.cookPork(); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/command/OrderSteakCommand.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/command/OrderSteakCommand.java new file mode 100644 index 0000000000..716a2953c2 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/command/OrderSteakCommand.java @@ -0,0 +1,18 @@ +package com.coderings.dp.command; + +/** + * @author nvarchar + * date 2017/8/11 + */ +public class OrderSteakCommand implements Command{ + private Cook cook; + + public OrderSteakCommand(Cook cook) { + this.cook = cook; + } + + @Override + public void execute() { + cook.cookSteak(); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/command/Waiter.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/command/Waiter.java new file mode 100644 index 0000000000..9bce5d54c8 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/command/Waiter.java @@ -0,0 +1,22 @@ +package com.coderings.dp.command; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author nvarchar + * date 2017/8/11 + */ +public class Waiter { + private List commands = new ArrayList<>(); + + public void addOrder(Command command) { + commands.add(command); + } + + public void sendOrders() { + for (Command command : commands) { + command.execute(); + } + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/ClientMain.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/ClientMain.java new file mode 100644 index 0000000000..62b6c44a11 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/ClientMain.java @@ -0,0 +1,16 @@ +package com.coderings.dp.composite; + +/** + * @author nvarchar + * date 2017/7/28 + */ +public class ClientMain { + public static void main(String[] args) { + CompositeShape compositeShape = new CompositeShape(); + compositeShape.add(new Line()); + compositeShape.add(new Square()); + compositeShape.add(new Rectangle()); + compositeShape.add(new Text()); + compositeShape.draw(); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/ComponetShape.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/ComponetShape.java new file mode 100644 index 0000000000..9992c45c2d --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/ComponetShape.java @@ -0,0 +1,9 @@ +package com.coderings.dp.composite; + +/** + * @author nvarchar + * date 2017/7/28 + */ +public abstract class ComponetShape implements Shape { + public abstract void add(Shape shape); +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/CompositeShape.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/CompositeShape.java new file mode 100644 index 0000000000..2fe2e164e0 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/CompositeShape.java @@ -0,0 +1,26 @@ +package com.coderings.dp.composite; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author nvarchar + * date 2017/7/28 + */ +public class CompositeShape extends ComponetShape{ + + private List shapes = new ArrayList<>(); + + @Override + public void draw() { + for(Shape shape : shapes){ + shape.draw(); + } + } + + @Override + public void add(Shape shape) { + shapes.add(shape); + } + +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/Line.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/Line.java new file mode 100644 index 0000000000..cc1f6c858a --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/Line.java @@ -0,0 +1,10 @@ +package com.coderings.dp.composite; + +public class Line implements Shape { + + @Override + public void draw() { + System.out.println("draw line"); + } + +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/Rectangle.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/Rectangle.java new file mode 100644 index 0000000000..95a91e522a --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/Rectangle.java @@ -0,0 +1,11 @@ +package com.coderings.dp.composite; + +public class Rectangle implements Shape { + + @Override + public void draw() { + // TODO Auto-generated method stub + System.out.println("draw rectangle"); + } + +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/Shape.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/Shape.java new file mode 100644 index 0000000000..ea353dad66 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/Shape.java @@ -0,0 +1,5 @@ +package com.coderings.dp.composite; + +public interface Shape { + public void draw(); +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/Square.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/Square.java new file mode 100644 index 0000000000..2f6b44bdad --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/Square.java @@ -0,0 +1,11 @@ +package com.coderings.dp.composite; + +public class Square implements Shape { + + @Override + public void draw() { + // TODO Auto-generated method stub + System.out.println("draw square"); + } + +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/Text.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/Text.java new file mode 100644 index 0000000000..e44cb39591 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/composite/Text.java @@ -0,0 +1,11 @@ +package com.coderings.dp.composite; + +public class Text implements Shape { + + @Override + public void draw() { + // TODO Auto-generated method stub + System.out.println("draw text"); + } + +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/decorator/Email.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/decorator/Email.java new file mode 100644 index 0000000000..f06ce0174f --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/decorator/Email.java @@ -0,0 +1,6 @@ +package com.coderings.dp.decorator; + +public interface Email { + public String getContent(); +} + diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/decorator/EmailDecorator.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/decorator/EmailDecorator.java new file mode 100644 index 0000000000..acb9cb5ec5 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/decorator/EmailDecorator.java @@ -0,0 +1,13 @@ +package com.coderings.dp.decorator; + +public abstract class EmailDecorator implements Email{ + protected Email email; + + public EmailDecorator(Email email) { + this.email = email; + } + + public String getContent() { + return email.getContent(); + } +} \ No newline at end of file diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/decorator/EmailImpl.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/decorator/EmailImpl.java new file mode 100644 index 0000000000..2d0abae365 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/decorator/EmailImpl.java @@ -0,0 +1,12 @@ +package com.coderings.dp.decorator; + +public class EmailImpl implements Email { + private String content; + + public EmailImpl(String content) { + this.content = content; + } + public String getContent() { + return content; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/decorator/EmailMain.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/decorator/EmailMain.java new file mode 100644 index 0000000000..e2822ab9de --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/decorator/EmailMain.java @@ -0,0 +1,15 @@ +package com.coderings.dp.decorator; + +/** + * @author nvarchar + * date 2017/7/28 + */ +public class EmailMain { + public static void main(String[] args) { + Email stateEmail = new StatementEmailImpl(new EmailImpl("发邮件")); + Email encryptEmail = new EncryptEmailImpl(new EmailImpl("发邮件")); + + System.out.println(stateEmail.getContent()); + System.out.println(encryptEmail.getContent()); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/decorator/EncryptEmailImpl.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/decorator/EncryptEmailImpl.java new file mode 100644 index 0000000000..5a63aa84cf --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/decorator/EncryptEmailImpl.java @@ -0,0 +1,20 @@ +package com.coderings.dp.decorator; + +/** + * @author nvarchar + * date 2017/7/26 + */ +public class EncryptEmailImpl extends EmailDecorator { + + public EncryptEmailImpl(Email email) { + super(email); + } + + private String encrypt(String content) { + return "****" + content + "****"; + } + + public String getContent() { + return encrypt(email.getContent()); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/decorator/StatementEmailImpl.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/decorator/StatementEmailImpl.java new file mode 100644 index 0000000000..a71b0dd7ac --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/decorator/StatementEmailImpl.java @@ -0,0 +1,17 @@ +package com.coderings.dp.decorator; + +/** + * @author nvarchar + * date 2017/7/26 + */ +public class StatementEmailImpl extends EmailDecorator { + + public StatementEmailImpl(Email email) { + super(email); + } + + public String getContent(){ + String state = "本邮件仅代表个人立场,不代表公司立场;"; + return email.getContent() + state; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/singleton/jdk_singleton.md b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/singleton/jdk_singleton.md new file mode 100644 index 0000000000..69df72e73d --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderings/dp/singleton/jdk_singleton.md @@ -0,0 +1,38 @@ +#Singleton in JDK + +## java.lang.Runtime + + private static Runtime currentRuntime = new Runtime(); + + public static Runtime getRuntime() { + return currentRuntime; + } + +## java.awt.Desktop + + private DesktopPeer peer; + + private Desktop() { + peer = Toolkit.getDefaultToolkit().createDesktopPeer(this); + } + + + public static synchronized Desktop getDesktop(){ + Desktop desktop = (Desktop)context.get(Desktop.class); + + if (desktop == null) { + desktop = new Desktop(); + context.put(Desktop.class, desktop); + } + + return desktop; + } + +## java.lang.System + + private static volatile SecurityManager security = null; + + public static SecurityManager getSecurityManager() { + return security; + } + \ No newline at end of file diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/Atm.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/Atm.java new file mode 100644 index 0000000000..9728b39bfb --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/Atm.java @@ -0,0 +1,166 @@ +package com.coderising.ood.atmSimulation.atm; + +import com.coderising.ood.atmSimulation.atm.console.SuperKeypad; +import com.coderising.ood.atmSimulation.atm.print.Printer; +import com.coderising.ood.atmSimulation.atm.proxy.BankProxy; +import com.coderising.ood.atmSimulation.atm.reader.CardReader; +import com.coderising.ood.atmSimulation.atm.slot.CashDepensier; +import com.coderising.ood.atmSimulation.atm.slot.DepositSlot; +import com.coderising.ood.atmSimulation.atm.transaction.*; +import com.coderising.ood.atmSimulation.card.Card; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public class Atm { + //存钱口 + private DepositSlot depositSlot; + //取钱口 + private CashDepensier cashDepensier; + //超级键盘 + private SuperKeypad superKeypad; + //读卡器 + private CardReader cardReader; + //bankProxy + private BankProxy bankProxy; + //打印器 + private Printer printer; + + public Atm(DepositSlot depositSlot, CashDepensier cashDepensier, + SuperKeypad superKeypad, CardReader cardReader, BankProxy bankProxy, Printer printer) { + this.depositSlot = depositSlot; + this.cashDepensier = cashDepensier; + this.superKeypad = superKeypad; + this.cardReader = cardReader; + this.bankProxy = bankProxy; + this.printer = printer; + } + + //账号|密码 + private String account; + private String password; + + private List list = new ArrayList<>(); + + public String getAccount() { + return account; + } + + public String getPassword() { + return password; + } + + public boolean hasEnoughMoney(int amount) { + return cashDepensier.hasEnoughMoney(amount); + } + + public boolean dipenseMoney(int amount) { + return cashDepensier.dispenseMoney(amount); + } + + public int retriveMoney() { + Random random = new Random(); + int money = random.nextInt(10000); + return depositSlot.retriveMoney(money); + } + + //插卡 + public void insertCard(Card card) { + account = cardReader.readCard(card); + } + + //输入密码 + public void writePassword() { + int count = 1; + while (count <= 3) { + count++; + password = superKeypad.inputPassword(); + if (bankProxy.verify(account, password)) { + return; + } + } + superKeypad.display("吞卡啦,到前台吧~"); + throw new RuntimeException("atm eat card"); + } + + //查询 + public void query() { + superKeypad.display("查询"); + QueryBalanceTx tx = new QueryBalanceTx(); + if (tx.preProcess(this)) { + String response = bankProxy.process(tx, this); + tx.setAmount(Integer.valueOf(response)); + superKeypad.display("查询操作余额为:" + response); + } + list.add(tx); + tx.postProcess(this); + } + + //转账 + public void transfer() { + superKeypad.display("转账"); + String toCard = superKeypad.inputCardNumber(); + int amount = superKeypad.inputAmount(); + TransferTx tx = new TransferTx(toCard, amount); + if (tx.preProcess(this)) { + String response = bankProxy.process(tx, this); + superKeypad.display("转账后,余额为:" + response); + } + list.add(tx); + tx.postProcess(this); + } + + //取款 + public void dependesier() { + superKeypad.display("取款"); + int amount = superKeypad.inputAmount(); + WithdrawTx tx = new WithdrawTx(amount); + if (tx.preProcess(this)) { + String response = bankProxy.process(tx, this); + superKeypad.display("取款后,余额为:" + response); + } + list.add(tx); + tx.postProcess(this); + } + + //存钱 + public void deposit() { + superKeypad.display("存款"); + DepositTx tx = new DepositTx(retriveMoney()); + if (tx.preProcess(this)) { + String response = bankProxy.process(tx, this); + superKeypad.display("存钱后,余额为:" + response); + } + list.add(tx); + tx.postProcess(this); + } + + //打印 + public void print() { + superKeypad.display("------打印操作-------"); + printer.print(list); + superKeypad.display("------打印完毕-------"); + } + + //退卡 + public void ejectCard(Card card) { + cardReader.ejectCard(card); + superKeypad.display("退卡成功"); + } + + //引导 + public void showGuide() { + superKeypad.display("请选择操作:"); + superKeypad.display("1:查询"); + superKeypad.display("2:存钱"); + superKeypad.display("3:取款"); + superKeypad.display("4:转账"); + superKeypad.display("5:退卡"); + } + +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/Main.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/Main.java new file mode 100644 index 0000000000..caf9ef2869 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/Main.java @@ -0,0 +1,97 @@ +package com.coderising.ood.atmSimulation.atm; + +import com.coderising.ood.atmSimulation.atm.console.Display; +import com.coderising.ood.atmSimulation.atm.console.KeyBoard; +import com.coderising.ood.atmSimulation.atm.console.SuperKeypad; +import com.coderising.ood.atmSimulation.atm.print.Printer; +import com.coderising.ood.atmSimulation.atm.proxy.BankProxy; +import com.coderising.ood.atmSimulation.atm.proxy.Network; +import com.coderising.ood.atmSimulation.atm.reader.CardReader; +import com.coderising.ood.atmSimulation.atm.slot.CashDepensier; +import com.coderising.ood.atmSimulation.atm.slot.DepositSlot; +import com.coderising.ood.atmSimulation.atm.slot.MoneySlot; +import com.coderising.ood.atmSimulation.bank.Bank; +import com.coderising.ood.atmSimulation.bank.account.Account; +import com.coderising.ood.atmSimulation.bank.proxy.ATMProxy; +import com.coderising.ood.atmSimulation.card.Card; + +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +/** + * @author nvarchar + * date 2017/7/16 + */ +public class Main { + + public static void main(String[] args) { + //mock bank + List accounts = new ArrayList<>(); + Account account = new Account("55005500", "123456", 10000); + accounts.add(account); + Bank bank = new Bank(accounts); + + //mock atmproxy + ATMProxy atmproxy = new ATMProxy(bank); + + //mock network + Network network = new Network(atmproxy); + + //mock bankProxy + BankProxy bankProxy = new BankProxy(network); + + //mock atm + DepositSlot depositSlot = new DepositSlot(); + CashDepensier cashDepensier = new CashDepensier(); + + Display display = new Display(); + KeyBoard keyBoard = new KeyBoard(); + SuperKeypad superKeypad = new SuperKeypad(display, keyBoard); + CardReader cardReader = new CardReader(); + Printer printer = new Printer(); + Atm atm = new Atm(depositSlot, cashDepensier, superKeypad, cardReader, bankProxy, printer); + + MoneySlot.setMoney(1000000); + + //mock card + Card card = new Card("55005500"); + + + atm.insertCard(card); + atm.writePassword(); + + atm.showGuide(); + + Scanner sca = new Scanner(System.in); + + boolean exit = false; + while (!exit) { + int ch = sca.nextInt(); + switch (ch) { + case 1: + atm.query(); + break; + case 2: + atm.deposit(); + break; + case 3: + atm.dependesier(); + break; + case 4: + atm.transfer(); + break; + case 5: + atm.ejectCard(card); + exit = true; + break; + default: + exit = true; + break; + } + } + + atm.print(); + + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/console/Display.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/console/Display.java new file mode 100644 index 0000000000..bae9135b4f --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/console/Display.java @@ -0,0 +1,13 @@ +package com.coderising.ood.atmSimulation.atm.console; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public class Display { + + public void showMessage(String message) { + System.out.println(message); + } + +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/console/KeyBoard.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/console/KeyBoard.java new file mode 100644 index 0000000000..8cbfa6fd71 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/console/KeyBoard.java @@ -0,0 +1,26 @@ +package com.coderising.ood.atmSimulation.atm.console; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public class KeyBoard { + + public String input() { + + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + String input = ""; + + try { + input = in.readLine(); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return input; + } + +} \ No newline at end of file diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/console/SuperKeypad.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/console/SuperKeypad.java new file mode 100644 index 0000000000..97256872da --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/console/SuperKeypad.java @@ -0,0 +1,45 @@ +package com.coderising.ood.atmSimulation.atm.console; + +import com.coderising.ood.atmSimulation.atm.transaction.Trasaction; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public class SuperKeypad { + private Display display; + private KeyBoard keyBoard; + + public SuperKeypad() { + } + + public SuperKeypad(Display display, KeyBoard keyBoard) { + this.display = display; + this.keyBoard = keyBoard; + } + + public void display(String message) { + display.showMessage(message); + } + + public String inputPassword() { + display("input your password: "); + String password = keyBoard.input(); + display(password.replaceAll("(?s).", "*")); + return password; + } + + public String inputCardNumber() { + display("input your transfer card number"); + return keyBoard.input(); + } + + public int inputAmount() { + display("input your amount"); + return Integer.valueOf(keyBoard.input()); + } + + public Trasaction getTrasaction() { + return null; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/print/Printer.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/print/Printer.java new file mode 100644 index 0000000000..41d492cc77 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/print/Printer.java @@ -0,0 +1,17 @@ +package com.coderising.ood.atmSimulation.atm.print; + +import com.coderising.ood.atmSimulation.atm.transaction.Trasaction; + +import java.util.List; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public class Printer { + public void print(List list) { + for (Trasaction trasaction : list) { + System.out.println(trasaction.toPrint()); + } + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/proxy/BankProxy.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/proxy/BankProxy.java new file mode 100644 index 0000000000..4f227e8959 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/proxy/BankProxy.java @@ -0,0 +1,29 @@ +package com.coderising.ood.atmSimulation.atm.proxy; + +import com.coderising.ood.atmSimulation.atm.Atm; +import com.coderising.ood.atmSimulation.atm.transaction.Trasaction; +import com.coderising.ood.atmSimulation.serialization.JsonConvert; +import com.coderising.ood.atmSimulation.serialization.NetPackage; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public class BankProxy { + private Network network; + + public BankProxy(Network network) { + this.network = network; + } + + public String process(Trasaction tx, Atm atm) { + String response = network.sendData(tx.toNetWorkPackage(atm)); + return response; + } + + public boolean verify(String account, String password) { + NetPackage netPackage = new NetPackage(account, password); + String response = network.sendData(JsonConvert.encode(netPackage)); + return "true".equals(response); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/proxy/Network.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/proxy/Network.java new file mode 100644 index 0000000000..a16917db06 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/proxy/Network.java @@ -0,0 +1,20 @@ +package com.coderising.ood.atmSimulation.atm.proxy; + +import com.coderising.ood.atmSimulation.bank.proxy.ATMProxy; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public class Network { + + private ATMProxy atmProxy; + + public Network(ATMProxy atmProxy) { + this.atmProxy = atmProxy; + } + + public String sendData(String data) { + return atmProxy.getData(data); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/reader/CardReader.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/reader/CardReader.java new file mode 100644 index 0000000000..a347337548 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/reader/CardReader.java @@ -0,0 +1,18 @@ +package com.coderising.ood.atmSimulation.atm.reader; + +import com.coderising.ood.atmSimulation.card.Card; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public class CardReader { + + public String readCard(Card card) { + return card.getAccount(); + } + + public void ejectCard(Card card){ + System.out.println("退卡"); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/slot/CashDepensier.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/slot/CashDepensier.java new file mode 100644 index 0000000000..256d4bb911 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/slot/CashDepensier.java @@ -0,0 +1,16 @@ +package com.coderising.ood.atmSimulation.atm.slot; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public class CashDepensier { + public boolean hasEnoughMoney(int amount) { + return MoneySlot.getMoney() - amount >= 0; + } + + public boolean dispenseMoney(int amount) { + MoneySlot.minusMoney(amount); + return true; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/slot/DepositSlot.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/slot/DepositSlot.java new file mode 100644 index 0000000000..2841e9f505 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/slot/DepositSlot.java @@ -0,0 +1,12 @@ +package com.coderising.ood.atmSimulation.atm.slot; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public class DepositSlot { + public int retriveMoney(int amount) { + //mock put money + return amount; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/slot/MoneySlot.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/slot/MoneySlot.java new file mode 100644 index 0000000000..171f9be15a --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/slot/MoneySlot.java @@ -0,0 +1,28 @@ +package com.coderising.ood.atmSimulation.atm.slot; + +/** + * manage atm money + * + * @author nvarchar + * date 2017/7/15 + */ +public class MoneySlot { + + private static long money; + + public static long getMoney() { + return money; + } + + public static void setMoney(long amount) { + MoneySlot.money = amount; + } + + public static void addMoney(long amount) { + money += amount; + } + + public static void minusMoney(long amount) { + money -= amount; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/transaction/DepositTx.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/transaction/DepositTx.java new file mode 100644 index 0000000000..770fe603ea --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/transaction/DepositTx.java @@ -0,0 +1,43 @@ +package com.coderising.ood.atmSimulation.atm.transaction; + +import com.coderising.ood.atmSimulation.atm.Atm; +import com.coderising.ood.atmSimulation.serialization.JsonConvert; +import com.coderising.ood.atmSimulation.serialization.NetPackage; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public class DepositTx implements Trasaction { + + private int amount; + + public int getAmount() { + return amount; + } + + public DepositTx(int amount) { + this.amount = amount; + } + + @Override + public String toPrint() { + return "存款" + amount; + } + + @Override + public String toNetWorkPackage(Atm atm) { + NetPackage nt = new NetPackage(NetPackage.Type.DEPOSIT, atm, amount, null); + return JsonConvert.encode(nt); + } + + @Override + public boolean preProcess(Atm atm) { + return true; + } + + @Override + public boolean postProcess(Atm atm) { + return false; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/transaction/QueryBalanceTx.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/transaction/QueryBalanceTx.java new file mode 100644 index 0000000000..f0b8a54fb7 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/transaction/QueryBalanceTx.java @@ -0,0 +1,42 @@ +package com.coderising.ood.atmSimulation.atm.transaction; + +import com.coderising.ood.atmSimulation.atm.Atm; +import com.coderising.ood.atmSimulation.serialization.JsonConvert; +import com.coderising.ood.atmSimulation.serialization.NetPackage; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public class QueryBalanceTx implements Trasaction { + + private int amount; + + public QueryBalanceTx() { + } + + public void setAmount(int amount) { + this.amount = amount; + } + + @Override + public String toPrint() { + return "查询账户,余额为:" + amount; + } + + @Override + public String toNetWorkPackage(Atm atm) { + NetPackage nt = new NetPackage(NetPackage.Type.QUERY, atm, null, null); + return JsonConvert.encode(nt); + } + + @Override + public boolean preProcess(Atm atm) { + return true; + } + + @Override + public boolean postProcess(Atm atm) { + return true; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/transaction/TransferTx.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/transaction/TransferTx.java new file mode 100644 index 0000000000..c3cb593ccd --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/transaction/TransferTx.java @@ -0,0 +1,44 @@ +package com.coderising.ood.atmSimulation.atm.transaction; + +import com.coderising.ood.atmSimulation.atm.Atm; +import com.coderising.ood.atmSimulation.serialization.JsonConvert; +import com.coderising.ood.atmSimulation.serialization.NetPackage; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public class TransferTx implements Trasaction { + private String toCard; + private int amount; + + public TransferTx(String toCard, int amount) { + this.toCard = toCard; + this.amount = amount; + } + + public int getAmount() { + return amount; + } + + @Override + public String toPrint() { + return "转账" + amount + "元到" + toCard; + } + + @Override + public String toNetWorkPackage(Atm atm) { + NetPackage nt = new NetPackage(NetPackage.Type.TRANSFER, atm, amount, toCard); + return JsonConvert.encode(nt); + } + + @Override + public boolean preProcess(Atm atm) { + return atm.hasEnoughMoney(getAmount()); + } + + @Override + public boolean postProcess(Atm atm) { + return true; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/transaction/Trasaction.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/transaction/Trasaction.java new file mode 100644 index 0000000000..c3c58978ce --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/transaction/Trasaction.java @@ -0,0 +1,17 @@ +package com.coderising.ood.atmSimulation.atm.transaction; + +import com.coderising.ood.atmSimulation.atm.Atm; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public interface Trasaction { + public String toNetWorkPackage(Atm atm); + + public boolean preProcess(Atm atm); + + public boolean postProcess(Atm atm); + + public String toPrint(); +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/transaction/WithdrawTx.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/transaction/WithdrawTx.java new file mode 100644 index 0000000000..c783326e02 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/atm/transaction/WithdrawTx.java @@ -0,0 +1,42 @@ +package com.coderising.ood.atmSimulation.atm.transaction; + +import com.coderising.ood.atmSimulation.atm.Atm; +import com.coderising.ood.atmSimulation.serialization.JsonConvert; +import com.coderising.ood.atmSimulation.serialization.NetPackage; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public class WithdrawTx implements Trasaction { + private int amount; + + public WithdrawTx(int amount) { + this.amount = amount; + } + + public int getAmount() { + return amount; + } + + @Override + public String toPrint() { + return "取款" + amount; + } + + @Override + public String toNetWorkPackage(Atm atm) { + NetPackage nt = new NetPackage(NetPackage.Type.WITHDRAW, atm, amount, null); + return JsonConvert.encode(nt); + } + + @Override + public boolean preProcess(Atm atm) { + return atm.hasEnoughMoney(getAmount()); + } + + @Override + public boolean postProcess(Atm atm) { + return atm.dipenseMoney(getAmount()); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/Bank.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/Bank.java new file mode 100644 index 0000000000..02550318bb --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/Bank.java @@ -0,0 +1,97 @@ +package com.coderising.ood.atmSimulation.bank; + +import com.coderising.ood.atmSimulation.bank.account.Account; +import com.coderising.ood.atmSimulation.bank.transaction.DepositTx; +import com.coderising.ood.atmSimulation.bank.transaction.QueryBalanceTx; +import com.coderising.ood.atmSimulation.bank.transaction.TransferTx; +import com.coderising.ood.atmSimulation.bank.transaction.WithdrawTx; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public class Bank { + private List accounts = new ArrayList<>(); + + public Bank(List accounts) { + this.accounts = accounts; + } + + //查询 + public String query(String cardNumber, String password) { + QueryBalanceTx tx = new QueryBalanceTx(cardNumber, password); + if (tx.preProcess(this)) { + return tx.process(this); + } + tx.postProcess(this); + return null; + } + + //转账 + public String transfer(String cardNumber, String password, + String toCard, int amount) { + TransferTx tx = new TransferTx(cardNumber, password, + toCard, amount); + + if (tx.preProcess(this)) { + return tx.process(this); + } + tx.postProcess(this); + return null; + } + + //取款 + public String withDraw(String cardNumber, String password, + int amount) { + WithdrawTx tx = new WithdrawTx(cardNumber, password, amount); + + if (tx.preProcess(this)) { + return tx.process(this); + } + tx.postProcess(this); + return null; + } + + //存钱 + public String deposit(String cardNumber, String password, + int amount) { + DepositTx tx = new DepositTx(cardNumber, password, amount); + + if (tx.preProcess(this)) { + return tx.process(this); + } + tx.postProcess(this); + return null; + } + + //验证 + public boolean verify(String account, String password) { + return isExist(account, password); + } + + //查询是否 + private boolean isExist(String cardNumber, String password) { + for (Account account : accounts) { + if (cardNumber.equals(account.getCardNumber()) + && password.equals(account.getPassword())) { + return true; + } + } + return false; + } + + //获取账户 + public Account getAccount(String cardNumber, String password) { + for (Account account : accounts) { + if (cardNumber.equals(account.getCardNumber()) + && password.equals(account.getPassword())) { + return account; + } + } + return null; + } + +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/account/Account.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/account/Account.java new file mode 100644 index 0000000000..3bbf50f600 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/account/Account.java @@ -0,0 +1,49 @@ +package com.coderising.ood.atmSimulation.bank.account; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public class Account { + private String cardNumber; + private int money; + private String password; + + public Account() { + } + + public Account(String cardNumber, String password, int money) { + this.cardNumber = cardNumber; + this.money = money; + this.password = password; + } + + public String getCardNumber() { + return cardNumber; + } + + public int getMoney() { + return money; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public boolean hasEnoughMoney(int amount) { + return money >= amount; + } + + public boolean dipenseMoney(int amount) { + money -= amount; + return true; + } + + public void retriveMoney(int amount) { + money += amount; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/proxy/ATMProxy.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/proxy/ATMProxy.java new file mode 100644 index 0000000000..a4083ff454 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/proxy/ATMProxy.java @@ -0,0 +1,34 @@ +package com.coderising.ood.atmSimulation.bank.proxy; + +import com.coderising.ood.atmSimulation.bank.Bank; +import com.coderising.ood.atmSimulation.serialization.JsonConvert; +import com.coderising.ood.atmSimulation.serialization.NetPackage; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public class ATMProxy { + private Bank bank; + + public ATMProxy(Bank bank) { + this.bank = bank; + } + + public String getData(String data) { + NetPackage np = JsonConvert.decode(data); + switch (np.getType()) { + case QUERY: + return bank.query(np.getAccount(), np.getPassword()); + case Verify: + return String.valueOf(bank.verify(np.getAccount(), np.getPassword())); + case DEPOSIT: + return bank.deposit(np.getAccount(), np.getPassword(), np.getAmount()); + case TRANSFER: + return bank.transfer(np.getAccount(), np.getPassword(), np.getToCard(), np.getAmount()); + case WITHDRAW: + return bank.withDraw(np.getAccount(), np.getPassword(), np.getAmount()); + } + return "no such method"; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/transaction/DepositTx.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/transaction/DepositTx.java new file mode 100644 index 0000000000..636df1e60d --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/transaction/DepositTx.java @@ -0,0 +1,38 @@ +package com.coderising.ood.atmSimulation.bank.transaction; + +import com.coderising.ood.atmSimulation.bank.Bank; +import com.coderising.ood.atmSimulation.bank.account.Account; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public class DepositTx implements Trasaction { + + private String account; + private String password; + private int amount; + + public DepositTx(String account, String password, int amount) { + this.account = account; + this.password = password; + this.amount = amount; + } + + @Override + public boolean preProcess(Bank bank) { + return true; + } + + @Override + public boolean postProcess(Bank bank) { + return true; + } + + @Override + public String process(Bank bank) { + Account queryAccount = bank.getAccount(account, password); + queryAccount.retriveMoney(amount); + return String.valueOf(queryAccount.getMoney()); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/transaction/QueryBalanceTx.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/transaction/QueryBalanceTx.java new file mode 100644 index 0000000000..c14bac18e0 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/transaction/QueryBalanceTx.java @@ -0,0 +1,38 @@ +package com.coderising.ood.atmSimulation.bank.transaction; + +import com.coderising.ood.atmSimulation.bank.Bank; +import com.coderising.ood.atmSimulation.bank.account.Account; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public class QueryBalanceTx implements Trasaction { + + private String account; + private String password; + + public QueryBalanceTx(String account, String password) { + this.account = account; + this.password = password; + } + + @Override + public boolean preProcess(Bank bank) { + return true; + } + + @Override + public boolean postProcess(Bank bank) { + return false; + } + + @Override + public String process(Bank bank) { + Account queryAccount = bank.getAccount(account, password); + if (account != null) { + return String.valueOf(queryAccount.getMoney()); + } + return null; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/transaction/TransferTx.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/transaction/TransferTx.java new file mode 100644 index 0000000000..91d0b82ed8 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/transaction/TransferTx.java @@ -0,0 +1,42 @@ +package com.coderising.ood.atmSimulation.bank.transaction; + +import com.coderising.ood.atmSimulation.bank.Bank; +import com.coderising.ood.atmSimulation.bank.account.Account; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public class TransferTx implements Trasaction { + + private String account; + private String password; + private String toCard; + private int amount; + + public TransferTx(String account, String password, String toCard, int amount) { + this.account = account; + this.password = password; + this.toCard = toCard; + this.amount = amount; + } + + @Override + public boolean preProcess(Bank bank) { + Account queryAccount = bank.getAccount(account, password); + return queryAccount.hasEnoughMoney(amount); + } + + @Override + public boolean postProcess(Bank bank) { + return true; + } + + @Override + public String process(Bank bank) { + Account queryAccount = bank.getAccount(account, password); + queryAccount.dipenseMoney(amount); + //mock add money to toCard + return String.valueOf(queryAccount.getMoney()); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/transaction/Trasaction.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/transaction/Trasaction.java new file mode 100644 index 0000000000..cd09230fd3 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/transaction/Trasaction.java @@ -0,0 +1,16 @@ +package com.coderising.ood.atmSimulation.bank.transaction; + +import com.coderising.ood.atmSimulation.bank.Bank; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public interface Trasaction { + + public boolean preProcess(Bank bank); + + public boolean postProcess(Bank bank); + + public String process(Bank bank); +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/transaction/WithdrawTx.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/transaction/WithdrawTx.java new file mode 100644 index 0000000000..5ff8efec7a --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/bank/transaction/WithdrawTx.java @@ -0,0 +1,39 @@ +package com.coderising.ood.atmSimulation.bank.transaction; + +import com.coderising.ood.atmSimulation.bank.Bank; +import com.coderising.ood.atmSimulation.bank.account.Account; + +/** + * @author nvarchar + * date 2017/7/14 + */ +public class WithdrawTx implements Trasaction{ + + private String account; + private String password; + private int amount; + + public WithdrawTx(String account, String password, int amount) { + this.account = account; + this.password = password; + this.amount = amount; + } + + @Override + public boolean preProcess(Bank bank) { + Account queryAccount = bank.getAccount(account, password); + return queryAccount.hasEnoughMoney(amount); + } + + @Override + public boolean postProcess(Bank bank) { + return true; + } + + @Override + public String process(Bank bank) { + Account queryAccount = bank.getAccount(account, password); + queryAccount.dipenseMoney(amount); + return String.valueOf(queryAccount.getMoney()); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/card/Card.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/card/Card.java new file mode 100644 index 0000000000..e1103c02ef --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/card/Card.java @@ -0,0 +1,17 @@ +package com.coderising.ood.atmSimulation.card; + +/** + * @author nvarchar + * date 2017/7/15 + */ +public class Card { + private String account; + + public Card(String account) { + this.account = account; + } + + public String getAccount() { + return account; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/serialization/JsonConvert.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/serialization/JsonConvert.java new file mode 100644 index 0000000000..be1934944b --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/serialization/JsonConvert.java @@ -0,0 +1,19 @@ +package com.coderising.ood.atmSimulation.serialization; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +/** + * @author nvarchar + * date 2017/7/16 + */ +public class JsonConvert { + + public static String encode(NetPackage np) { + return JSON.toJSONString(np); + } + + public static NetPackage decode(String code) { + return JSONObject.parseObject(code, NetPackage.class); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/serialization/NetPackage.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/serialization/NetPackage.java new file mode 100644 index 0000000000..99246a3d41 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/atmSimulation/serialization/NetPackage.java @@ -0,0 +1,76 @@ +package com.coderising.ood.atmSimulation.serialization; + +import com.coderising.ood.atmSimulation.atm.Atm; + +/** + * @author nvarchar + * date 2017/7/16 + */ +public class NetPackage { + + public enum Type {Verify, QUERY, TRANSFER, DEPOSIT, WITHDRAW} + + private String account; + private String password; + private Integer amount; + private Type type; + private String toCard; + + public void setAccount(String account) { + this.account = account; + } + + public void setPassword(String password) { + this.password = password; + } + + public void setAmount(Integer amount) { + this.amount = amount; + } + + public void setType(Type type) { + this.type = type; + } + + public void setToCard(String toCard) { + this.toCard = toCard; + } + + public String getAccount() { + return account; + } + + public String getPassword() { + return password; + } + + public Integer getAmount() { + return amount; + } + + public Type getType() { + return type; + } + + public String getToCard() { + return toCard; + } + + public NetPackage(Type type, Atm atm, Integer amount, String toCard) { + this.account = atm.getAccount(); + this.password = atm.getPassword(); + this.amount = amount; + this.type = type; + this.toCard = toCard; + } + + public NetPackage(String account, String password) { + this.type = Type.Verify; + this.account = account; + this.password = password; + } + + public NetPackage() { + } +} + diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java new file mode 100644 index 0000000000..0d0d01098f --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return null; + } + +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/LogMsgConvert.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/LogMsgConvert.java new file mode 100644 index 0000000000..a2c2d82a98 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/LogMsgConvert.java @@ -0,0 +1,9 @@ +package com.coderising.ood.ocp; + +/** + * @author nvarchar + * date 2017/6/28 + */ +public interface LogMsgConvert { + String getLogFromMsg(String msg); +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java new file mode 100644 index 0000000000..532dc9a611 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java @@ -0,0 +1,22 @@ +package com.coderising.ood.ocp; + +public class Logger { + + Sender sender; + LogMsgConvert convert; + + public Logger(int logType, int logMethod) { + convert = RawLogFactory.createFormatter(logType); + sender = SenderFactory.createSenderFormat(logMethod); + } + + public void log(String msg) { + sender.send(convert.getLogFromMsg(msg)); + } + + public static void main(String[] args) { + Logger logger = new Logger(1, 3); + logger.log("123"); + } +} + diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/MailSender.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/MailSender.java new file mode 100644 index 0000000000..5fa0c23759 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/MailSender.java @@ -0,0 +1,12 @@ +package com.coderising.ood.ocp; + +/** + * @author nvarchar + * date 2017/6/28 + */ +public class MailSender implements Sender { + @Override + public void send(String logMsg) { + MailUtil.send(logMsg); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java new file mode 100644 index 0000000000..59d77649a2 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class MailUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/PrintSender.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/PrintSender.java new file mode 100644 index 0000000000..7e69eb15d9 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/PrintSender.java @@ -0,0 +1,12 @@ +package com.coderising.ood.ocp; + +/** + * @author nvarchar + * date 2017/6/28 + */ +public class PrintSender implements Sender { + @Override + public void send(String logMsg) { + System.out.println(logMsg); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/RawLog.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/RawLog.java new file mode 100644 index 0000000000..ebcfce56b9 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/RawLog.java @@ -0,0 +1,14 @@ +package com.coderising.ood.ocp; + +/** + * @author nvarchar + * date 2017/6/28 + */ +public class RawLog implements LogMsgConvert{ + + @Override + public String getLogFromMsg(String msg) { + String logMsg = msg; + return logMsg; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/RawLogFactory.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/RawLogFactory.java new file mode 100644 index 0000000000..c593ae3ace --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/RawLogFactory.java @@ -0,0 +1,17 @@ +package com.coderising.ood.ocp; + +/** + * @author nvarchar + * date 2017/6/28 + */ +public class RawLogFactory { + public static LogMsgConvert createFormatter(int type) { + if (type == 1) { + return new RawLog(); + } + if (type == 2) { + return new RawLogWtihDate(); + } + return null; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/RawLogWtihDate.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/RawLogWtihDate.java new file mode 100644 index 0000000000..a30ad24665 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/RawLogWtihDate.java @@ -0,0 +1,15 @@ +package com.coderising.ood.ocp; + +/** + * @author nvarchar + * date 2017/6/28 + */ +public class RawLogWtihDate implements LogMsgConvert { + + @Override + public String getLogFromMsg(String msg) { + String txtDate = DateUtil.getCurrentDateAsString(); + String logMsg = txtDate + ": " + msg; + return logMsg; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSSender.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSSender.java new file mode 100644 index 0000000000..9a5f4a572a --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSSender.java @@ -0,0 +1,12 @@ +package com.coderising.ood.ocp; + +/** + * @author nvarchar + * date 2017/6/28 + */ +public class SMSSender implements Sender { + @Override + public void send(String logMsg) { + SMSUtil.send(logMsg); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java new file mode 100644 index 0000000000..fab4cd01b7 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class SMSUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/Sender.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/Sender.java new file mode 100644 index 0000000000..7d0c47ed22 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/Sender.java @@ -0,0 +1,9 @@ +package com.coderising.ood.ocp; + +/** + * @author nvarchar + * date 2017/6/28 + */ +public interface Sender { + void send(String logMsg); +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SenderFactory.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SenderFactory.java new file mode 100644 index 0000000000..32c09afb78 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SenderFactory.java @@ -0,0 +1,19 @@ +package com.coderising.ood.ocp; + +/** + * @author nvarchar + * date 2017/6/28 + */ +public class SenderFactory { + + public static Sender createSenderFormat(int method) { + if (method == 1) { + return new MailSender(); + } else if (method == 2) { + return new SMSSender(); + } else if (method == 3) { + return new PrintSender(); + } + return null; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/Employee.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/Employee.java new file mode 100644 index 0000000000..a19e993424 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/Employee.java @@ -0,0 +1,64 @@ +package com.coderising.ood.payroll; + +import com.coderising.ood.payroll.affiliation.Affiliation; +import com.coderising.ood.payroll.classfication.PaymentClassification; +import com.coderising.ood.payroll.method.PaymentMethod; +import com.coderising.ood.payroll.schedule.PaymentSchedule; + +import java.util.Date; + +public class Employee { + int id; + String name; + String address; + Affiliation affiliation; + + + PaymentClassification classification; + PaymentSchedule schedule; + PaymentMethod paymentMethod; + + public Employee(String name, String address) { + this.name = name; + this.address = address; + } + + public boolean isPayDay(Date d) { + return schedule.isPayDate(id, d); + } + + public boolean isPayed(Date d) { + return schedule.isPayed(id, d); + } + + public Date getPayPeriodStartDate(Date d) { + return schedule.getPayPeriodStartDate(d); + } + + public void payDay(Paycheck pc) { + + if (isPayDay(new Date()) && isPayed(new Date())) { + double grossPay = classification.calculatePay(pc); + double deduction = affiliation.calculateDeductions(pc); + double netPay = grossPay - deduction; + pc.setGrossPay(grossPay); + pc.setDeductions(deduction); + pc.setNetPay(netPay); + + paymentMethod.pay(pc, id); + } + } + + public void setClassification(PaymentClassification classification) { + this.classification = classification; + } + + public void setSchedule(PaymentSchedule schedule) { + this.schedule = schedule; + } + + public void setPaymentMethod(PaymentMethod paymentMethod) { + this.paymentMethod = paymentMethod; + } +} + diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/Paycheck.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/Paycheck.java new file mode 100644 index 0000000000..8704ba58c7 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/Paycheck.java @@ -0,0 +1,34 @@ +package com.coderising.ood.payroll; + +import java.util.Date; + +public class Paycheck { + private Date payPeriodStart; + private Date payPeriodEnd; + private double grossPay; + private double netPay; + private double deductions; + + public Paycheck(Date payPeriodStart, Date payPeriodEnd){ + this.payPeriodStart = payPeriodStart; + this.payPeriodEnd = payPeriodEnd; + } + public void setGrossPay(double grossPay) { + this.grossPay = grossPay; + + } + public void setDeductions(double deductions) { + this.deductions = deductions; + } + public void setNetPay(double netPay){ + this.netPay = netPay; + } + public Date getPayPeriodEndDate() { + + return this.payPeriodEnd; + } + public Date getPayPeriodStartDate() { + + return this.payPeriodStart; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/affiliation/Affiliation.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/affiliation/Affiliation.java new file mode 100644 index 0000000000..2b427068ae --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/affiliation/Affiliation.java @@ -0,0 +1,7 @@ +package com.coderising.ood.payroll.affiliation; + +import com.coderising.ood.payroll.Paycheck; + +public interface Affiliation { + public double calculateDeductions(Paycheck pc); +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/affiliation/NonAffiliation.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/affiliation/NonAffiliation.java new file mode 100644 index 0000000000..cab1542a14 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/affiliation/NonAffiliation.java @@ -0,0 +1,15 @@ +package com.coderising.ood.payroll.affiliation; + +import com.coderising.ood.payroll.Paycheck; + +/** + * @author nvarchar + * date 2017/7/10 + */ +public class NonAffiliation implements Affiliation { + + @Override + public double calculateDeductions(Paycheck pc) { + return 0; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/affiliation/ServiceCharge.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/affiliation/ServiceCharge.java new file mode 100644 index 0000000000..25847d650a --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/affiliation/ServiceCharge.java @@ -0,0 +1,28 @@ +package com.coderising.ood.payroll.affiliation; + +import java.util.Date; + +/** + * @author nvarchar + * date 2017/7/10 + */ +public class ServiceCharge { + private Date date; + private double amount; + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public double getAmount() { + return amount; + } + + public void setAmount(double amount) { + this.amount = amount; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/affiliation/UnionAffiliation.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/affiliation/UnionAffiliation.java new file mode 100644 index 0000000000..50e19e985f --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/affiliation/UnionAffiliation.java @@ -0,0 +1,53 @@ +package com.coderising.ood.payroll.affiliation; + +import com.coderising.ood.payroll.Paycheck; +import com.coderising.ood.payroll.util.DateUtil; + +import java.util.List; + +/** + * @author nvarchar + * date 2017/7/10 + */ +public class UnionAffiliation implements Affiliation{ + private int memberId; + private double weeklyDue; + private List serviceChargeList; + + @Override + public double calculateDeductions(Paycheck pc) { + int fridays = DateUtil.getFridayNumber(pc.getPayPeriodStartDate(), pc.getPayPeriodEndDate()); + double totalDue = fridays * weeklyDue; + double totalCharge = 0.0d; + for (ServiceCharge serviceCharge : serviceChargeList){ + if (DateUtil.isDuring(pc.getPayPeriodStartDate(), pc.getPayPeriodEndDate(), serviceCharge.getDate())){ + totalCharge += serviceCharge.getAmount(); + } + } + return totalCharge + totalDue; + } + + public int getMemberId() { + return memberId; + } + + public void setMemberId(int memberId) { + this.memberId = memberId; + } + + public double getWeeklyDue() { + return weeklyDue; + } + + public void setWeeklyDue(double weeklyDue) { + this.weeklyDue = weeklyDue; + } + + public List getServiceChargeList() { + return serviceChargeList; + } + + public void setServiceChargeList(List serviceChargeList) { + this.serviceChargeList = serviceChargeList; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/classfication/CommissionClassification.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/classfication/CommissionClassification.java new file mode 100644 index 0000000000..992b8142c1 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/classfication/CommissionClassification.java @@ -0,0 +1,17 @@ +package com.coderising.ood.payroll.classfication; + +import com.coderising.ood.payroll.Paycheck; + +/** + * @author nvarchar + * date 2017/7/10 + */ +public class CommissionClassification implements PaymentClassification { + + private double salary; + + @Override + public double calculatePay(Paycheck pc) { + return salary; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/classfication/HourlyClassification.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/classfication/HourlyClassification.java new file mode 100644 index 0000000000..de8ac05ae4 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/classfication/HourlyClassification.java @@ -0,0 +1,36 @@ +package com.coderising.ood.payroll.classfication; + +import com.coderising.ood.payroll.Paycheck; +import com.coderising.ood.payroll.util.DateUtil; + +import java.util.Date; +import java.util.Map; + +/** + * @author nvarchar + * date 2017/7/10 + */ +public class HourlyClassification implements PaymentClassification { + private double rate; + private Map timeCards; + + public void addTimeCard(TimeCard tc) { + timeCards.put(tc.getDate(), tc); + } + + @Override + public double calculatePay(Paycheck pc) { + double daysMoney = 0.0; + for (Date date : timeCards.keySet()) { + if (DateUtil.isDuring(pc.getPayPeriodStartDate(), pc.getPayPeriodEndDate(), date)) { + daysMoney += calculateHours(timeCards.get(date).getHours()); + } + } + return daysMoney; + } + + private double calculateHours(int hour) { + int extendHour = hour - 8 >= 0 ? hour - 8 : 0; + return hour * rate + extendHour * rate * 1.5; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/classfication/PaymentClassification.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/classfication/PaymentClassification.java new file mode 100644 index 0000000000..90cd991f75 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/classfication/PaymentClassification.java @@ -0,0 +1,7 @@ +package com.coderising.ood.payroll.classfication; + +import com.coderising.ood.payroll.Paycheck; + +public interface PaymentClassification { + public double calculatePay(Paycheck pc); +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/classfication/SalariedClassification.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/classfication/SalariedClassification.java new file mode 100644 index 0000000000..50c3a70d92 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/classfication/SalariedClassification.java @@ -0,0 +1,30 @@ +package com.coderising.ood.payroll.classfication; + +import com.coderising.ood.payroll.Paycheck; +import com.coderising.ood.payroll.util.DateUtil; + +import java.util.Date; +import java.util.Map; + +/** + * @author nvarchar + * date 2017/7/10 + */ +public class SalariedClassification implements PaymentClassification { + private double salary; + private double rate; + private Map salesReceiptMap; + + + @Override + public double calculatePay(Paycheck pc) { + double commission = 0.0; + for (Date date : salesReceiptMap.keySet()) { + if (DateUtil.isDuring(pc.getPayPeriodStartDate(), pc.getPayPeriodEndDate(), date)) { + commission += salesReceiptMap.get(date).getAmount() * rate; + } + } + + return salary + commission; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/classfication/SalesReceipt.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/classfication/SalesReceipt.java new file mode 100644 index 0000000000..5194c317c4 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/classfication/SalesReceipt.java @@ -0,0 +1,14 @@ +package com.coderising.ood.payroll.classfication; + +import java.util.Date; + +public class SalesReceipt { + private Date saleDate; + private double amount; + public Date getSaleDate() { + return saleDate; + } + public double getAmount() { + return amount; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/classfication/TimeCard.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/classfication/TimeCard.java new file mode 100644 index 0000000000..c0c70e95f8 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/classfication/TimeCard.java @@ -0,0 +1,15 @@ +package com.coderising.ood.payroll.classfication; + +import java.util.Date; + +public class TimeCard { + private Date date; + private int hours; + + public Date getDate() { + return date; + } + public int getHours() { + return hours; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/db/MockDB.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/db/MockDB.java new file mode 100644 index 0000000000..9529963626 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/db/MockDB.java @@ -0,0 +1,38 @@ +package com.coderising.ood.payroll.db; + +import com.coderising.ood.payroll.Paycheck; + +import java.util.HashMap; +import java.util.Map; +import java.util.Stack; + +/** + * @author nvarchar + * date 2017/7/10 + */ +public class MockDB { + + private static Map> map; + + static { + map = new HashMap>(); + } + + public static void put(int id, Paycheck pc) { + if (map.containsKey(id)) { + Stack stack = map.get(id); + stack.push(pc); + } else { + Stack stack = new Stack<>(); + stack.push(pc); + map.put(id, stack); + } + } + + public static Paycheck peek(int id) { + if (map.containsKey(id)) { + return map.get(id).peek(); + } + return null; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/method/BankMethod.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/method/BankMethod.java new file mode 100644 index 0000000000..257476c8b1 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/method/BankMethod.java @@ -0,0 +1,18 @@ +package com.coderising.ood.payroll.method; + +import com.coderising.ood.payroll.Paycheck; +import com.coderising.ood.payroll.db.MockDB; + +/** + * @author nvarchar + * date 2017/7/10 + */ +public class BankMethod implements PaymentMethod { + + @Override + public void pay(Paycheck pc, int employId) { + //pay to bank + System.out.println("pay to bank " + employId); + MockDB.put(employId, pc); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/method/HoldMethod.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/method/HoldMethod.java new file mode 100644 index 0000000000..92f1b08830 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/method/HoldMethod.java @@ -0,0 +1,18 @@ +package com.coderising.ood.payroll.method; + +import com.coderising.ood.payroll.Paycheck; +import com.coderising.ood.payroll.db.MockDB; + +/** + * @author nvarchar + * date 2017/7/10 + */ +public class HoldMethod implements PaymentMethod { + + @Override + public void pay(Paycheck pc, int employId) { + //hold the paycheck + System.out.println("hold paycheck " + employId); + MockDB.put(employId, pc); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/method/MailMethod.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/method/MailMethod.java new file mode 100644 index 0000000000..1cff304dc7 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/method/MailMethod.java @@ -0,0 +1,17 @@ +package com.coderising.ood.payroll.method; + +import com.coderising.ood.payroll.Paycheck; +import com.coderising.ood.payroll.db.MockDB; + +/** + * @author nvarchar + * date 2017/7/10 + */ +public class MailMethod implements PaymentMethod { + @Override + public void pay(Paycheck pc, int employId) { + //mail to employee + System.out.println("mail to employee " + employId); + MockDB.put(employId, pc); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/method/PaymentMethod.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/method/PaymentMethod.java new file mode 100644 index 0000000000..b0c88c21fa --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/method/PaymentMethod.java @@ -0,0 +1,7 @@ +package com.coderising.ood.payroll.method; + +import com.coderising.ood.payroll.Paycheck; + +public interface PaymentMethod{ + public void pay(Paycheck pc, int employId); +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/schedule/BiWeeklyPaymentSchedule.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/schedule/BiWeeklyPaymentSchedule.java new file mode 100644 index 0000000000..b36968d68b --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/schedule/BiWeeklyPaymentSchedule.java @@ -0,0 +1,28 @@ +package com.coderising.ood.payroll.schedule; + +import com.coderising.ood.payroll.db.MockDB; +import com.coderising.ood.payroll.util.DateUtil; + +import java.util.Date; + +/** + * @author nvarchar + * date 2017/7/10 + */ +public class BiWeeklyPaymentSchedule implements PaymentSchedule { + + @Override + public boolean isPayDate(int employedId, Date date) { + Date payedDate = MockDB.peek(employedId).getPayPeriodEndDate(); + if (payedDate == null) { + return DateUtil.isFriday(date); + } else { + return DateUtil.getInterval(payedDate, date) % 14 == 0; + } + } + + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.getStartDate(payPeriodEndDate, -13); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/schedule/MonthlyPaymentSchedule.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/schedule/MonthlyPaymentSchedule.java new file mode 100644 index 0000000000..b54682ab83 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/schedule/MonthlyPaymentSchedule.java @@ -0,0 +1,22 @@ +package com.coderising.ood.payroll.schedule; + +import com.coderising.ood.payroll.util.DateUtil; + +import java.util.Date; + +/** + * @author nvarchar + * date 2017/7/10 + */ +public class MonthlyPaymentSchedule implements PaymentSchedule { + + @Override + public boolean isPayDate(int employId, Date date) { + return DateUtil.isLastWorkDay(date); + } + + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.getStartOfMonth(); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/schedule/PaymentSchedule.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/schedule/PaymentSchedule.java new file mode 100644 index 0000000000..4fce5bac18 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/schedule/PaymentSchedule.java @@ -0,0 +1,15 @@ +package com.coderising.ood.payroll.schedule; + +import com.coderising.ood.payroll.db.MockDB; +import com.coderising.ood.payroll.util.DateUtil; + +import java.util.Date; + +public interface PaymentSchedule { + public boolean isPayDate(int employId, Date date); + public Date getPayPeriodStartDate(Date payPeriodEndDate); + + default public boolean isPayed(int employedId, Date date){ + return DateUtil.equalDay(MockDB.peek(employedId).getPayPeriodEndDate(), date); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/schedule/WeeklyPaymentSchedule.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/schedule/WeeklyPaymentSchedule.java new file mode 100644 index 0000000000..988b8c23ea --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/schedule/WeeklyPaymentSchedule.java @@ -0,0 +1,22 @@ +package com.coderising.ood.payroll.schedule; + +import com.coderising.ood.payroll.util.DateUtil; + +import java.util.Date; + +/** + * @author nvarchar + * date 2017/7/10 + */ +public class WeeklyPaymentSchedule implements PaymentSchedule { + + @Override + public boolean isPayDate(int employId,Date date) { + return DateUtil.isFriday(date); + } + + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.getStartDate(payPeriodEndDate, -6); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/util/DateUtil.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/util/DateUtil.java new file mode 100644 index 0000000000..b742fabef5 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/payroll/util/DateUtil.java @@ -0,0 +1,96 @@ +package com.coderising.ood.payroll.util; + +import java.util.Calendar; +import java.util.Date; + +/** + * @author nvarchar + * date 2017/7/10 + */ +public class DateUtil { + + public static boolean isDuring(Date start, Date end, Date date) { + long oneDay = 24 * 60 * 60 * 1000; + long d1 = start.getTime() / oneDay; + long d2 = end.getTime() / oneDay; + long d = date.getTime() / oneDay; + + if (d1 <= d && d <= d2) { + return true; + } + + return false; + } + + + public static int getFridayNumber(Date start, Date end) { + Calendar starCalendar = Calendar.getInstance(); + starCalendar.setTime(start); + Calendar endCalendar = Calendar.getInstance(); + endCalendar.setTime(end); + int result = 0; + while (starCalendar.before(endCalendar)) { + + starCalendar.add(Calendar.DATE, 1); + + if (starCalendar.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) { + result++; + starCalendar.add(Calendar.DATE, 6); + } + + } + return result; + } + + public static boolean isFriday(Date date) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) { + return true; + } + return false; + } + + public static boolean isLastWorkDay(Date date) { + + Calendar calToday = Calendar.getInstance(); + calToday.setTime(date); + + Calendar cal = Calendar.getInstance(); + cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE)); + while (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY && + cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { + cal.add(Calendar.DATE, -1); + } + + return cal.get(Calendar.DAY_OF_MONTH) == calToday.get(Calendar.DAY_OF_MONTH); + } + + public static Date getStartDate(Date endDate, int duringDay) { + Calendar cal = Calendar.getInstance(); + cal.setTime(endDate); + cal.add(Calendar.DATE, duringDay); + return cal.getTime(); + } + + public static Date getStartOfMonth() { + Calendar cal = Calendar.getInstance(); + cal.set(Calendar.DATE, cal.getActualMinimum(Calendar.DATE)); + return cal.getTime(); + } + + public static boolean equalDay(Date date1, Date date2) { + long oneDay = 24 * 60 * 60 * 1000; + long d1 = date1.getTime() / oneDay; + long d2 = date2.getTime() / oneDay; + return d1 == d2; + } + + public static long getInterval(Date start, Date end) { + long oneDay = 24 * 60 * 60 * 1000; + long d1 = start.getTime() / oneDay; + long d2 = end.getTime() / oneDay; + return d2 - d1; + } +} + diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtil.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtil.java new file mode 100644 index 0000000000..eb8896e527 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtil.java @@ -0,0 +1,16 @@ +package com.coderising.ood.srp; + +import java.io.File; +import java.io.IOException; + +/** + * @author nvarchar + * date 2017/6/26 + */ +public class FileUtil { + + protected static String[] readFile(File file) throws IOException // @02C + { + return null; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java new file mode 100644 index 0000000000..9a72ea60d6 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java @@ -0,0 +1,33 @@ +package com.coderising.ood.srp; + +import java.util.List; + +/** + * @author nvarchar + * date 2017/6/29 + */ +public class Mail { + private User user; + + public Mail(User u) { + this.user = u; + } + + public String getAddress() { + return user.getEMailAddress(); + } + + public String getSubject() { + return "您关注的产品降价了"; + } + + public String getBody() { + return "尊敬的 " + user.getName() + ", 您关注的产品 " + this.buildProductDescList() + " 降价了,欢迎购买!"; + } + + private String buildProductDescList() { + List products = user.getSubscribedProducts(); + //.... 实现略... + return null; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailService.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailService.java new file mode 100644 index 0000000000..3e6788915d --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailService.java @@ -0,0 +1,46 @@ +package com.coderising.ood.srp; + +/** + * 发送邮件 + * + * @author nvarchar + * date 2017/6/26 + */ +public class MailService { + private String fromAddress; + private String smtpHost; + private String altSmtpHost; + + public MailService(Configuration config) { + this.fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + this.smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + this.altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + } + + public void sendMail(Mail mail) { + try { + sendEmail(mail, this.smtpHost); + } catch (Exception e) { + try { + sendEmail(mail, this.altSmtpHost); + } catch (Exception ex) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + ex.getMessage()); + } + + } + } + + private void sendEmail(Mail mail, String smtpHost) { + String toAddress = mail.getAddress(); + String subject = mail.getSubject(); + String msg = mail.getBody(); + //发送邮件 + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(msg).append("\n"); + System.out.println(buffer.toString()); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..45cd069953 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,31 @@ +package com.coderising.ood.srp; + +/** + * @author nvarchar + * date 2017/6/29 + */ +public class Product { + private String id; + private String desc; + + public Product(String id, String desc) { + this.id = id; + this.desc = desc; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ProductService.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ProductService.java new file mode 100644 index 0000000000..b5c801e1a8 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ProductService.java @@ -0,0 +1,32 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * @author nvarchar + * date 2017/6/29 + */ +public class ProductService { + + public List getProductLists(String filePath) throws IOException { + List products = new ArrayList<>(); + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(filePath)); + String temp; + while ((temp = br.readLine()) != null) { + String[] data = temp.split(" "); + products.add(new Product(data[0], data[1])); + } + return products; + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMain.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMain.java new file mode 100644 index 0000000000..aea2699c2c --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMain.java @@ -0,0 +1,39 @@ +package com.coderising.ood.srp; + +import java.io.IOException; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * @author nvarchar + * date 2017/6/29 + */ +public class PromotionMain { + private ProductService productService = new ProductService(); + private UserService userService = new UserService(); + + public void run(String filepath) throws IOException { + + Configuration cfg = new Configuration(); + + List productList = productService.getProductLists(filepath); + + Set users = new HashSet<>(); + for (Product product : productList) { + List userList = userService.getUsers(product); + //todo 将userlist中的user和对应的product添加到users中 + } + MailService mailService = new MailService(cfg); + for (User user : users) { + mailService.sendMail(new Mail(user)); + } + } + + public static void main(String[] args) throws Exception { + String filePath = "/Users/nvarchar/Documents/github/coding2017-2/" + + "students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt"; + PromotionMain main = new PromotionMain(); + main.run(filePath); + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/User.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/User.java new file mode 100644 index 0000000000..4d2ea42edc --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/User.java @@ -0,0 +1,27 @@ +package com.coderising.ood.srp; + +import java.util.List; + +/** + * @author nvarchar + * date 2017/6/29 + */ +public class User { + private String name; + private String emailAddress; + + private List products; + + public String getName() { + return name; + } + + public String getEMailAddress() { + return emailAddress; + } + + public List getSubscribedProducts() { + return this.products; + } + +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/UserService.java b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/UserService.java new file mode 100644 index 0000000000..3b2e68fb31 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/UserService.java @@ -0,0 +1,15 @@ +package com.coderising.ood.srp; + +import java.util.List; + +/** + * @author nvarchar + * date 2017/6/29 + */ +public class UserService { + + public List getUsers(Product product){ + //调用DAO相关的类从数据库中读取订阅产品的用户列表 + return null; + } +} diff --git a/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/2816977791/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git "a/students/2816977791/ood/ood-assignment/uml\344\275\234\344\270\232.mdj" "b/students/2816977791/ood/ood-assignment/uml\344\275\234\344\270\232.mdj" new file mode 100644 index 0000000000..07a8fd5223 --- /dev/null +++ "b/students/2816977791/ood/ood-assignment/uml\344\275\234\344\270\232.mdj" @@ -0,0 +1,10991 @@ +{ + "_type": "Project", + "_id": "AAAAAAFF+h6SjaM2Hec=", + "name": "UML", + "ownedElements": [ + { + "_type": "UMLModel", + "_id": "AAAAAAFdF8bUGpzmKj4=", + "_parent": { + "$ref": "AAAAAAFF+h6SjaM2Hec=" + }, + "name": "UML", + "ownedElements": [ + { + "_type": "UMLClassDiagram", + "_id": "AAAAAAFdF8bUG5znYro=", + "_parent": { + "$ref": "AAAAAAFdF8bUGpzmKj4=" + }, + "name": "掷骰子类图", + "visible": true, + "defaultDiagram": false, + "ownedViews": [ + { + "_type": "UMLClassView", + "_id": "AAAAAAFdF9Jh5p1e1kg=", + "_parent": { + "$ref": "AAAAAAFdF8bUG5znYro=" + }, + "model": { + "$ref": "AAAAAAFdF9Jh5Z1ciZA=" + }, + "subViews": [ + { + "_type": "UMLNameCompartmentView", + "_id": "AAAAAAFdF9Jh551fLcE=", + "_parent": { + "$ref": "AAAAAAFdF9Jh5p1e1kg=" + }, + "model": { + "$ref": "AAAAAAFdF9Jh5Z1ciZA=" + }, + "subViews": [ + { + "_type": "LabelView", + "_id": "AAAAAAFdF9Jh551gGOA=", + "_parent": { + "$ref": "AAAAAAFdF9Jh551fLcE=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -64, + "top": -64, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdF9Jh6J1hmaI=", + "_parent": { + "$ref": "AAAAAAFdF9Jh551fLcE=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;1", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 93, + "top": 143, + "width": 136, + "height": 13, + "autoResize": false, + "underline": false, + "text": "Player", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdF9Jh6J1iK1E=", + "_parent": { + "$ref": "AAAAAAFdF9Jh551fLcE=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -64, + "top": -64, + "width": 65, + "height": 13, + "autoResize": false, + "underline": false, + "text": "(from UML)", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdF9Jh6J1jC4c=", + "_parent": { + "$ref": "AAAAAAFdF9Jh551fLcE=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -64, + "top": -64, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 1, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 88, + "top": 136, + "width": 146, + "height": 25, + "autoResize": false, + "stereotypeLabel": { + "$ref": "AAAAAAFdF9Jh551gGOA=" + }, + "nameLabel": { + "$ref": "AAAAAAFdF9Jh6J1hmaI=" + }, + "namespaceLabel": { + "$ref": "AAAAAAFdF9Jh6J1iK1E=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdF9Jh6J1jC4c=" + } + }, + { + "_type": "UMLAttributeCompartmentView", + "_id": "AAAAAAFdF9Jh6J1k2zs=", + "_parent": { + "$ref": "AAAAAAFdF9Jh5p1e1kg=" + }, + "model": { + "$ref": "AAAAAAFdF9Jh5Z1ciZA=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 88, + "top": 161, + "width": 146, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLOperationCompartmentView", + "_id": "AAAAAAFdF9Jh6Z1lcZE=", + "_parent": { + "$ref": "AAAAAAFdF9Jh5p1e1kg=" + }, + "model": { + "$ref": "AAAAAAFdF9Jh5Z1ciZA=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 88, + "top": 171, + "width": 146, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLReceptionCompartmentView", + "_id": "AAAAAAFdF9Jh6Z1mfBE=", + "_parent": { + "$ref": "AAAAAAFdF9Jh5p1e1kg=" + }, + "model": { + "$ref": "AAAAAAFdF9Jh5Z1ciZA=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -32, + "top": -32, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLTemplateParameterCompartmentView", + "_id": "AAAAAAFdF9Jh6p1n2Rs=", + "_parent": { + "$ref": "AAAAAAFdF9Jh5p1e1kg=" + }, + "model": { + "$ref": "AAAAAAFdF9Jh5Z1ciZA=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -32, + "top": -32, + "width": 10, + "height": 10, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": true, + "containerExtending": false, + "left": 88, + "top": 136, + "width": 146, + "height": 137, + "autoResize": false, + "stereotypeDisplay": "label", + "showVisibility": true, + "showNamespace": false, + "showProperty": true, + "showType": true, + "nameCompartment": { + "$ref": "AAAAAAFdF9Jh551fLcE=" + }, + "wordWrap": false, + "suppressAttributes": false, + "suppressOperations": false, + "suppressReceptions": true, + "showMultiplicity": true, + "showOperationSignature": true, + "attributeCompartment": { + "$ref": "AAAAAAFdF9Jh6J1k2zs=" + }, + "operationCompartment": { + "$ref": "AAAAAAFdF9Jh6Z1lcZE=" + }, + "receptionCompartment": { + "$ref": "AAAAAAFdF9Jh6Z1mfBE=" + }, + "templateParameterCompartment": { + "$ref": "AAAAAAFdF9Jh6p1n2Rs=" + } + }, + { + "_type": "UMLClassView", + "_id": "AAAAAAFdF9NBMZ2L3Y0=", + "_parent": { + "$ref": "AAAAAAFdF8bUG5znYro=" + }, + "model": { + "$ref": "AAAAAAFdF9NBMZ2Jv50=" + }, + "subViews": [ + { + "_type": "UMLNameCompartmentView", + "_id": "AAAAAAFdF9NBMp2MHjA=", + "_parent": { + "$ref": "AAAAAAFdF9NBMZ2L3Y0=" + }, + "model": { + "$ref": "AAAAAAFdF9NBMZ2Jv50=" + }, + "subViews": [ + { + "_type": "LabelView", + "_id": "AAAAAAFdF9NBMp2N/fY=", + "_parent": { + "$ref": "AAAAAAFdF9NBMp2MHjA=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 352, + "top": -32, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdF9NBMp2OfKA=", + "_parent": { + "$ref": "AAAAAAFdF9NBMp2MHjA=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;1", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 301, + "top": 159, + "width": 110, + "height": 13, + "autoResize": false, + "underline": false, + "text": "DiceGame", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdF9NBMp2P328=", + "_parent": { + "$ref": "AAAAAAFdF9NBMp2MHjA=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 352, + "top": -32, + "width": 65, + "height": 13, + "autoResize": false, + "underline": false, + "text": "(from UML)", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdF9NBMp2QlM4=", + "_parent": { + "$ref": "AAAAAAFdF9NBMp2MHjA=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 352, + "top": -32, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 1, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 296, + "top": 152, + "width": 120, + "height": 25, + "autoResize": false, + "stereotypeLabel": { + "$ref": "AAAAAAFdF9NBMp2N/fY=" + }, + "nameLabel": { + "$ref": "AAAAAAFdF9NBMp2OfKA=" + }, + "namespaceLabel": { + "$ref": "AAAAAAFdF9NBMp2P328=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdF9NBMp2QlM4=" + } + }, + { + "_type": "UMLAttributeCompartmentView", + "_id": "AAAAAAFdF9NBM52Rwlo=", + "_parent": { + "$ref": "AAAAAAFdF9NBMZ2L3Y0=" + }, + "model": { + "$ref": "AAAAAAFdF9NBMZ2Jv50=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 296, + "top": 177, + "width": 120, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLOperationCompartmentView", + "_id": "AAAAAAFdF9NBM52Sw5c=", + "_parent": { + "$ref": "AAAAAAFdF9NBMZ2L3Y0=" + }, + "model": { + "$ref": "AAAAAAFdF9NBMZ2Jv50=" + }, + "subViews": [ + { + "_type": "UMLOperationView", + "_id": "AAAAAAFdF9tkjZ8WQz4=", + "_parent": { + "$ref": "AAAAAAFdF9NBM52Sw5c=" + }, + "model": { + "$ref": "AAAAAAFdF9tkT58TEw0=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 301, + "top": 192, + "width": 110, + "height": 13, + "autoResize": false, + "underline": false, + "text": "+play()", + "horizontalAlignment": 0, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 296, + "top": 187, + "width": 120, + "height": 23, + "autoResize": false + }, + { + "_type": "UMLReceptionCompartmentView", + "_id": "AAAAAAFdF9NBM52TM2c=", + "_parent": { + "$ref": "AAAAAAFdF9NBMZ2L3Y0=" + }, + "model": { + "$ref": "AAAAAAFdF9NBMZ2Jv50=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 176, + "top": -16, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLTemplateParameterCompartmentView", + "_id": "AAAAAAFdF9NBM52UQZA=", + "_parent": { + "$ref": "AAAAAAFdF9NBMZ2L3Y0=" + }, + "model": { + "$ref": "AAAAAAFdF9NBMZ2Jv50=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 176, + "top": -16, + "width": 10, + "height": 10, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": true, + "containerExtending": false, + "left": 296, + "top": 152, + "width": 120, + "height": 105, + "autoResize": false, + "stereotypeDisplay": "label", + "showVisibility": true, + "showNamespace": false, + "showProperty": true, + "showType": true, + "nameCompartment": { + "$ref": "AAAAAAFdF9NBMp2MHjA=" + }, + "wordWrap": false, + "suppressAttributes": false, + "suppressOperations": false, + "suppressReceptions": true, + "showMultiplicity": true, + "showOperationSignature": true, + "attributeCompartment": { + "$ref": "AAAAAAFdF9NBM52Rwlo=" + }, + "operationCompartment": { + "$ref": "AAAAAAFdF9NBM52Sw5c=" + }, + "receptionCompartment": { + "$ref": "AAAAAAFdF9NBM52TM2c=" + }, + "templateParameterCompartment": { + "$ref": "AAAAAAFdF9NBM52UQZA=" + } + }, + { + "_type": "UMLClassView", + "_id": "AAAAAAFdF9RF6p27dz8=", + "_parent": { + "$ref": "AAAAAAFdF8bUG5znYro=" + }, + "model": { + "$ref": "AAAAAAFdF9RF6Z25s+k=" + }, + "subViews": [ + { + "_type": "UMLNameCompartmentView", + "_id": "AAAAAAFdF9RF6p285OM=", + "_parent": { + "$ref": "AAAAAAFdF9RF6p27dz8=" + }, + "model": { + "$ref": "AAAAAAFdF9RF6Z25s+k=" + }, + "subViews": [ + { + "_type": "LabelView", + "_id": "AAAAAAFdF9RF6p290EI=", + "_parent": { + "$ref": "AAAAAAFdF9RF6p285OM=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 832, + "top": -64, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdF9RF652+dtM=", + "_parent": { + "$ref": "AAAAAAFdF9RF6p285OM=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;1", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 541, + "top": 143, + "width": 95, + "height": 13, + "autoResize": false, + "underline": false, + "text": "Dice", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdF9RF652/xQQ=", + "_parent": { + "$ref": "AAAAAAFdF9RF6p285OM=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 832, + "top": -64, + "width": 65, + "height": 13, + "autoResize": false, + "underline": false, + "text": "(from UML)", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdF9RF653A46U=", + "_parent": { + "$ref": "AAAAAAFdF9RF6p285OM=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 832, + "top": -64, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 1, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 536, + "top": 136, + "width": 105, + "height": 25, + "autoResize": false, + "stereotypeLabel": { + "$ref": "AAAAAAFdF9RF6p290EI=" + }, + "nameLabel": { + "$ref": "AAAAAAFdF9RF652+dtM=" + }, + "namespaceLabel": { + "$ref": "AAAAAAFdF9RF652/xQQ=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdF9RF653A46U=" + } + }, + { + "_type": "UMLAttributeCompartmentView", + "_id": "AAAAAAFdF9RF653BO3M=", + "_parent": { + "$ref": "AAAAAAFdF9RF6p27dz8=" + }, + "model": { + "$ref": "AAAAAAFdF9RF6Z25s+k=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 536, + "top": 161, + "width": 105, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLOperationCompartmentView", + "_id": "AAAAAAFdF9RF653Cqww=", + "_parent": { + "$ref": "AAAAAAFdF9RF6p27dz8=" + }, + "model": { + "$ref": "AAAAAAFdF9RF6Z25s+k=" + }, + "subViews": [ + { + "_type": "UMLOperationView", + "_id": "AAAAAAFdF9yO5Z8ojEk=", + "_parent": { + "$ref": "AAAAAAFdF9RF653Cqww=" + }, + "model": { + "$ref": "AAAAAAFdF9yOrp8l+p4=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 541, + "top": 176, + "width": 95, + "height": 13, + "autoResize": false, + "underline": false, + "text": "+roll()", + "horizontalAlignment": 0, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 536, + "top": 171, + "width": 105, + "height": 23, + "autoResize": false + }, + { + "_type": "UMLReceptionCompartmentView", + "_id": "AAAAAAFdF9RF653DNB8=", + "_parent": { + "$ref": "AAAAAAFdF9RF6p27dz8=" + }, + "model": { + "$ref": "AAAAAAFdF9RF6Z25s+k=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 416, + "top": -32, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLTemplateParameterCompartmentView", + "_id": "AAAAAAFdF9RF653EiHA=", + "_parent": { + "$ref": "AAAAAAFdF9RF6p27dz8=" + }, + "model": { + "$ref": "AAAAAAFdF9RF6Z25s+k=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 416, + "top": -32, + "width": 10, + "height": 10, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": true, + "containerExtending": false, + "left": 536, + "top": 136, + "width": 105, + "height": 129, + "autoResize": false, + "stereotypeDisplay": "label", + "showVisibility": true, + "showNamespace": false, + "showProperty": true, + "showType": true, + "nameCompartment": { + "$ref": "AAAAAAFdF9RF6p285OM=" + }, + "wordWrap": false, + "suppressAttributes": false, + "suppressOperations": false, + "suppressReceptions": true, + "showMultiplicity": true, + "showOperationSignature": true, + "attributeCompartment": { + "$ref": "AAAAAAFdF9RF653BO3M=" + }, + "operationCompartment": { + "$ref": "AAAAAAFdF9RF653Cqww=" + }, + "receptionCompartment": { + "$ref": "AAAAAAFdF9RF653DNB8=" + }, + "templateParameterCompartment": { + "$ref": "AAAAAAFdF9RF653EiHA=" + } + }, + { + "_type": "UMLClassView", + "_id": "AAAAAAFdG6RIw5sj01s=", + "_parent": { + "$ref": "AAAAAAFdF8bUG5znYro=" + }, + "model": { + "$ref": "AAAAAAFdG6RIwpshRVw=" + }, + "subViews": [ + { + "_type": "UMLNameCompartmentView", + "_id": "AAAAAAFdG6RIw5skjDw=", + "_parent": { + "$ref": "AAAAAAFdG6RIw5sj01s=" + }, + "model": { + "$ref": "AAAAAAFdG6RIwpshRVw=" + }, + "subViews": [ + { + "_type": "LabelView", + "_id": "AAAAAAFdG6RIxJslAao=", + "_parent": { + "$ref": "AAAAAAFdG6RIw5skjDw=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 64, + "top": 0, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdG6RIxJsm7oQ=", + "_parent": { + "$ref": "AAAAAAFdG6RIw5skjDw=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;1", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 317, + "top": 343, + "width": 83, + "height": 13, + "autoResize": false, + "underline": false, + "text": "Display", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdG6RIxJsn/Ho=", + "_parent": { + "$ref": "AAAAAAFdG6RIw5skjDw=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 64, + "top": 0, + "width": 65, + "height": 13, + "autoResize": false, + "underline": false, + "text": "(from UML)", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdG6RIxJsowro=", + "_parent": { + "$ref": "AAAAAAFdG6RIw5skjDw=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 64, + "top": 0, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 1, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 312, + "top": 336, + "width": 93, + "height": 25, + "autoResize": false, + "stereotypeLabel": { + "$ref": "AAAAAAFdG6RIxJslAao=" + }, + "nameLabel": { + "$ref": "AAAAAAFdG6RIxJsm7oQ=" + }, + "namespaceLabel": { + "$ref": "AAAAAAFdG6RIxJsn/Ho=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdG6RIxJsowro=" + } + }, + { + "_type": "UMLAttributeCompartmentView", + "_id": "AAAAAAFdG6RIxJsppN8=", + "_parent": { + "$ref": "AAAAAAFdG6RIw5sj01s=" + }, + "model": { + "$ref": "AAAAAAFdG6RIwpshRVw=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 312, + "top": 361, + "width": 93, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLOperationCompartmentView", + "_id": "AAAAAAFdG6RIxJsqh8o=", + "_parent": { + "$ref": "AAAAAAFdG6RIw5sj01s=" + }, + "model": { + "$ref": "AAAAAAFdG6RIwpshRVw=" + }, + "subViews": [ + { + "_type": "UMLOperationView", + "_id": "AAAAAAFdG6UFHpx+fFk=", + "_parent": { + "$ref": "AAAAAAFdG6RIxJsqh8o=" + }, + "model": { + "$ref": "AAAAAAFdG6UEzJx4aDY=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 317, + "top": 376, + "width": 83, + "height": 13, + "autoResize": false, + "underline": false, + "text": "+showResult()", + "horizontalAlignment": 0, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 312, + "top": 371, + "width": 93, + "height": 23, + "autoResize": false + }, + { + "_type": "UMLReceptionCompartmentView", + "_id": "AAAAAAFdG6RIxZsrp4I=", + "_parent": { + "$ref": "AAAAAAFdG6RIw5sj01s=" + }, + "model": { + "$ref": "AAAAAAFdG6RIwpshRVw=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 32, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLTemplateParameterCompartmentView", + "_id": "AAAAAAFdG6RIxZssrB4=", + "_parent": { + "$ref": "AAAAAAFdG6RIw5sj01s=" + }, + "model": { + "$ref": "AAAAAAFdG6RIwpshRVw=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 32, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": true, + "containerExtending": false, + "left": 312, + "top": 336, + "width": 93, + "height": 58, + "autoResize": false, + "stereotypeDisplay": "label", + "showVisibility": true, + "showNamespace": false, + "showProperty": true, + "showType": true, + "nameCompartment": { + "$ref": "AAAAAAFdG6RIw5skjDw=" + }, + "wordWrap": false, + "suppressAttributes": false, + "suppressOperations": false, + "suppressReceptions": true, + "showMultiplicity": true, + "showOperationSignature": true, + "attributeCompartment": { + "$ref": "AAAAAAFdG6RIxJsppN8=" + }, + "operationCompartment": { + "$ref": "AAAAAAFdG6RIxJsqh8o=" + }, + "receptionCompartment": { + "$ref": "AAAAAAFdG6RIxZsrp4I=" + }, + "templateParameterCompartment": { + "$ref": "AAAAAAFdG6RIxZssrB4=" + } + }, + { + "_type": "UMLAssociationView", + "_id": "AAAAAAFdG6S2ipuwjkI=", + "_parent": { + "$ref": "AAAAAAFdF8bUG5znYro=" + }, + "model": { + "$ref": "AAAAAAFdG6S2iZusc0s=" + }, + "subViews": [ + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6S2i5uxbfQ=", + "_parent": { + "$ref": "AAAAAAFdG6S2ipuwjkI=" + }, + "model": { + "$ref": "AAAAAAFdG6S2iZusc0s=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 475, + "top": 210, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdG6S2ipuwjkI=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6S2i5uyfR4=", + "_parent": { + "$ref": "AAAAAAFdG6S2ipuwjkI=" + }, + "model": { + "$ref": "AAAAAAFdG6S2iZusc0s=" + }, + "visible": null, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 475, + "top": 225, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdG6S2ipuwjkI=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6S2i5uz2QY=", + "_parent": { + "$ref": "AAAAAAFdG6S2ipuwjkI=" + }, + "model": { + "$ref": "AAAAAAFdG6S2iZusc0s=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 474, + "top": 181, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdG6S2ipuwjkI=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6S2i5u0CCg=", + "_parent": { + "$ref": "AAAAAAFdG6S2ipuwjkI=" + }, + "model": { + "$ref": "AAAAAAFdG6S2iZutrMs=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 509, + "top": 210, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 0.5235987755982988, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdG6S2ipuwjkI=" + }, + "edgePosition": 2, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6S2i5u1a6s=", + "_parent": { + "$ref": "AAAAAAFdG6S2ipuwjkI=" + }, + "model": { + "$ref": "AAAAAAFdG6S2iZutrMs=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 507, + "top": 223, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 0.7853981633974483, + "distance": 40, + "hostEdge": { + "$ref": "AAAAAAFdG6S2ipuwjkI=" + }, + "edgePosition": 2, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6S2i5u2OxE=", + "_parent": { + "$ref": "AAAAAAFdG6S2ipuwjkI=" + }, + "model": { + "$ref": "AAAAAAFdG6S2iZutrMs=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 513, + "top": 182, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -0.5235987755982988, + "distance": 25, + "hostEdge": { + "$ref": "AAAAAAFdG6S2ipuwjkI=" + }, + "edgePosition": 2, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6S2i5u3NnY=", + "_parent": { + "$ref": "AAAAAAFdG6S2ipuwjkI=" + }, + "model": { + "$ref": "AAAAAAFdG6S2iZuu5hA=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 442, + "top": 211, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -0.5235987755982988, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdG6S2ipuwjkI=" + }, + "edgePosition": 0, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6S2i5u4bS4=", + "_parent": { + "$ref": "AAAAAAFdG6S2ipuwjkI=" + }, + "model": { + "$ref": "AAAAAAFdG6S2iZuu5hA=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 444, + "top": 224, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -0.7853981633974483, + "distance": 40, + "hostEdge": { + "$ref": "AAAAAAFdG6S2ipuwjkI=" + }, + "edgePosition": 0, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6S2i5u5L50=", + "_parent": { + "$ref": "AAAAAAFdG6S2ipuwjkI=" + }, + "model": { + "$ref": "AAAAAAFdG6S2iZuu5hA=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 437, + "top": 184, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 0.5235987755982988, + "distance": 25, + "hostEdge": { + "$ref": "AAAAAAFdG6S2ipuwjkI=" + }, + "edgePosition": 0, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "UMLQualifierCompartmentView", + "_id": "AAAAAAFdG6S2i5u6s+4=", + "_parent": { + "$ref": "AAAAAAFdG6S2ipuwjkI=" + }, + "model": { + "$ref": "AAAAAAFdG6S2iZutrMs=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLQualifierCompartmentView", + "_id": "AAAAAAFdG6S2i5u7PHQ=", + "_parent": { + "$ref": "AAAAAAFdG6S2ipuwjkI=" + }, + "model": { + "$ref": "AAAAAAFdG6S2iZuu5hA=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "head": { + "$ref": "AAAAAAFdF9NBMZ2L3Y0=" + }, + "tail": { + "$ref": "AAAAAAFdF9RF6p27dz8=" + }, + "lineStyle": 1, + "points": "535:201;416:203", + "stereotypeDisplay": "label", + "showVisibility": true, + "showProperty": true, + "nameLabel": { + "$ref": "AAAAAAFdG6S2i5uxbfQ=" + }, + "stereotypeLabel": { + "$ref": "AAAAAAFdG6S2i5uyfR4=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdG6S2i5uz2QY=" + }, + "showMultiplicity": true, + "showType": true, + "tailRoleNameLabel": { + "$ref": "AAAAAAFdG6S2i5u0CCg=" + }, + "tailPropertyLabel": { + "$ref": "AAAAAAFdG6S2i5u1a6s=" + }, + "tailMultiplicityLabel": { + "$ref": "AAAAAAFdG6S2i5u2OxE=" + }, + "headRoleNameLabel": { + "$ref": "AAAAAAFdG6S2i5u3NnY=" + }, + "headPropertyLabel": { + "$ref": "AAAAAAFdG6S2i5u4bS4=" + }, + "headMultiplicityLabel": { + "$ref": "AAAAAAFdG6S2i5u5L50=" + }, + "tailQualifiersCompartment": { + "$ref": "AAAAAAFdG6S2i5u6s+4=" + }, + "headQualifiersCompartment": { + "$ref": "AAAAAAFdG6S2i5u7PHQ=" + } + }, + { + "_type": "UMLAssociationView", + "_id": "AAAAAAFdG6TzIZwbrTI=", + "_parent": { + "$ref": "AAAAAAFdF8bUG5znYro=" + }, + "model": { + "$ref": "AAAAAAFdG6TzIJwX5cs=" + }, + "subViews": [ + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6TzIZwcpKE=", + "_parent": { + "$ref": "AAAAAAFdG6TzIZwbrTI=" + }, + "model": { + "$ref": "AAAAAAFdG6TzIJwX5cs=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 370, + "top": 289, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdG6TzIZwbrTI=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6TzIZwdOEs=", + "_parent": { + "$ref": "AAAAAAFdG6TzIZwbrTI=" + }, + "model": { + "$ref": "AAAAAAFdG6TzIJwX5cs=" + }, + "visible": null, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 385, + "top": 289, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdG6TzIZwbrTI=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6TzIZweT1I=", + "_parent": { + "$ref": "AAAAAAFdG6TzIZwbrTI=" + }, + "model": { + "$ref": "AAAAAAFdG6TzIJwX5cs=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 341, + "top": 290, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdG6TzIZwbrTI=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6TzIZwf28Q=", + "_parent": { + "$ref": "AAAAAAFdG6TzIZwbrTI=" + }, + "model": { + "$ref": "AAAAAAFdG6TzIJwYZJ8=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 371, + "top": 276, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 0.5235987755982988, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdG6TzIZwbrTI=" + }, + "edgePosition": 2, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6TzIZwgt2E=", + "_parent": { + "$ref": "AAAAAAFdG6TzIZwbrTI=" + }, + "model": { + "$ref": "AAAAAAFdG6TzIJwYZJ8=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 384, + "top": 278, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 0.7853981633974483, + "distance": 40, + "hostEdge": { + "$ref": "AAAAAAFdG6TzIZwbrTI=" + }, + "edgePosition": 2, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6TzIZwhoAc=", + "_parent": { + "$ref": "AAAAAAFdG6TzIZwbrTI=" + }, + "model": { + "$ref": "AAAAAAFdG6TzIJwYZJ8=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 343, + "top": 272, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -0.5235987755982988, + "distance": 25, + "hostEdge": { + "$ref": "AAAAAAFdG6TzIZwbrTI=" + }, + "edgePosition": 2, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6TzIZwixsg=", + "_parent": { + "$ref": "AAAAAAFdG6TzIZwbrTI=" + }, + "model": { + "$ref": "AAAAAAFdG6TzIJwZeVE=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 371, + "top": 302, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -0.5235987755982988, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdG6TzIZwbrTI=" + }, + "edgePosition": 0, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6TzIZwj9mY=", + "_parent": { + "$ref": "AAAAAAFdG6TzIZwbrTI=" + }, + "model": { + "$ref": "AAAAAAFdG6TzIJwZeVE=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 384, + "top": 300, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -0.7853981633974483, + "distance": 40, + "hostEdge": { + "$ref": "AAAAAAFdG6TzIZwbrTI=" + }, + "edgePosition": 0, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6TzIZwk3hI=", + "_parent": { + "$ref": "AAAAAAFdG6TzIZwbrTI=" + }, + "model": { + "$ref": "AAAAAAFdG6TzIJwZeVE=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 344, + "top": 307, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 0.5235987755982988, + "distance": 25, + "hostEdge": { + "$ref": "AAAAAAFdG6TzIZwbrTI=" + }, + "edgePosition": 0, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "UMLQualifierCompartmentView", + "_id": "AAAAAAFdG6TzIZwlZ4U=", + "_parent": { + "$ref": "AAAAAAFdG6TzIZwbrTI=" + }, + "model": { + "$ref": "AAAAAAFdG6TzIJwYZJ8=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLQualifierCompartmentView", + "_id": "AAAAAAFdG6TzIZwmWlA=", + "_parent": { + "$ref": "AAAAAAFdG6TzIZwbrTI=" + }, + "model": { + "$ref": "AAAAAAFdG6TzIJwZeVE=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "head": { + "$ref": "AAAAAAFdG6RIw5sj01s=" + }, + "tail": { + "$ref": "AAAAAAFdF9NBMZ2L3Y0=" + }, + "lineStyle": 1, + "points": "356:257;357:335", + "stereotypeDisplay": "label", + "showVisibility": true, + "showProperty": true, + "nameLabel": { + "$ref": "AAAAAAFdG6TzIZwcpKE=" + }, + "stereotypeLabel": { + "$ref": "AAAAAAFdG6TzIZwdOEs=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdG6TzIZweT1I=" + }, + "showMultiplicity": true, + "showType": true, + "tailRoleNameLabel": { + "$ref": "AAAAAAFdG6TzIZwf28Q=" + }, + "tailPropertyLabel": { + "$ref": "AAAAAAFdG6TzIZwgt2E=" + }, + "tailMultiplicityLabel": { + "$ref": "AAAAAAFdG6TzIZwhoAc=" + }, + "headRoleNameLabel": { + "$ref": "AAAAAAFdG6TzIZwixsg=" + }, + "headPropertyLabel": { + "$ref": "AAAAAAFdG6TzIZwj9mY=" + }, + "headMultiplicityLabel": { + "$ref": "AAAAAAFdG6TzIZwk3hI=" + }, + "tailQualifiersCompartment": { + "$ref": "AAAAAAFdG6TzIZwlZ4U=" + }, + "headQualifiersCompartment": { + "$ref": "AAAAAAFdG6TzIZwmWlA=" + } + }, + { + "_type": "UMLAssociationView", + "_id": "AAAAAAFdG6VR1p1K29k=", + "_parent": { + "$ref": "AAAAAAFdF8bUG5znYro=" + }, + "model": { + "$ref": "AAAAAAFdG6VR1p1Gsno=" + }, + "subViews": [ + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6VR151Ll90=", + "_parent": { + "$ref": "AAAAAAFdG6VR1p1K29k=" + }, + "model": { + "$ref": "AAAAAAFdG6VR1p1Gsno=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 264, + "top": 183, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdG6VR1p1K29k=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6VR151MEwk=", + "_parent": { + "$ref": "AAAAAAFdG6VR1p1K29k=" + }, + "model": { + "$ref": "AAAAAAFdG6VR1p1Gsno=" + }, + "visible": null, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 264, + "top": 168, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdG6VR1p1K29k=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6VR151N38E=", + "_parent": { + "$ref": "AAAAAAFdG6VR1p1K29k=" + }, + "model": { + "$ref": "AAAAAAFdG6VR1p1Gsno=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 264, + "top": 213, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdG6VR1p1K29k=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6VR151OVG8=", + "_parent": { + "$ref": "AAAAAAFdG6VR1p1K29k=" + }, + "model": { + "$ref": "AAAAAAFdG6VR1p1HuPE=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 259, + "top": 183, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 0.5235987755982988, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdG6VR1p1K29k=" + }, + "edgePosition": 2, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6VR151PBXI=", + "_parent": { + "$ref": "AAAAAAFdG6VR1p1K29k=" + }, + "model": { + "$ref": "AAAAAAFdG6VR1p1HuPE=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 262, + "top": 169, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 0.7853981633974483, + "distance": 40, + "hostEdge": { + "$ref": "AAAAAAFdG6VR1p1K29k=" + }, + "edgePosition": 2, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6VR151Qxb0=", + "_parent": { + "$ref": "AAAAAAFdG6VR1p1K29k=" + }, + "model": { + "$ref": "AAAAAAFdG6VR1p1HuPE=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 255, + "top": 210, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -0.5235987755982988, + "distance": 25, + "hostEdge": { + "$ref": "AAAAAAFdG6VR1p1K29k=" + }, + "edgePosition": 2, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6VR151RWSE=", + "_parent": { + "$ref": "AAAAAAFdG6VR1p1K29k=" + }, + "model": { + "$ref": "AAAAAAFdG6VR1p1IHBQ=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 269, + "top": 183, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -0.5235987755982988, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdG6VR1p1K29k=" + }, + "edgePosition": 0, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6VR151SI6M=", + "_parent": { + "$ref": "AAAAAAFdG6VR1p1K29k=" + }, + "model": { + "$ref": "AAAAAAFdG6VR1p1IHBQ=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 266, + "top": 169, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -0.7853981633974483, + "distance": 40, + "hostEdge": { + "$ref": "AAAAAAFdG6VR1p1K29k=" + }, + "edgePosition": 0, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdG6VR151Tzp0=", + "_parent": { + "$ref": "AAAAAAFdG6VR1p1K29k=" + }, + "model": { + "$ref": "AAAAAAFdG6VR1p1IHBQ=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 273, + "top": 210, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 0.5235987755982988, + "distance": 25, + "hostEdge": { + "$ref": "AAAAAAFdG6VR1p1K29k=" + }, + "edgePosition": 0, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "UMLQualifierCompartmentView", + "_id": "AAAAAAFdG6VR2J1U3mw=", + "_parent": { + "$ref": "AAAAAAFdG6VR1p1K29k=" + }, + "model": { + "$ref": "AAAAAAFdG6VR1p1HuPE=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLQualifierCompartmentView", + "_id": "AAAAAAFdG6VR2J1VdIc=", + "_parent": { + "$ref": "AAAAAAFdG6VR1p1K29k=" + }, + "model": { + "$ref": "AAAAAAFdG6VR1p1IHBQ=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "head": { + "$ref": "AAAAAAFdF9NBMZ2L3Y0=" + }, + "tail": { + "$ref": "AAAAAAFdF9Jh5p1e1kg=" + }, + "lineStyle": 1, + "points": "234:204;295:204", + "stereotypeDisplay": "label", + "showVisibility": true, + "showProperty": true, + "nameLabel": { + "$ref": "AAAAAAFdG6VR151Ll90=" + }, + "stereotypeLabel": { + "$ref": "AAAAAAFdG6VR151MEwk=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdG6VR151N38E=" + }, + "showMultiplicity": true, + "showType": true, + "tailRoleNameLabel": { + "$ref": "AAAAAAFdG6VR151OVG8=" + }, + "tailPropertyLabel": { + "$ref": "AAAAAAFdG6VR151PBXI=" + }, + "tailMultiplicityLabel": { + "$ref": "AAAAAAFdG6VR151Qxb0=" + }, + "headRoleNameLabel": { + "$ref": "AAAAAAFdG6VR151RWSE=" + }, + "headPropertyLabel": { + "$ref": "AAAAAAFdG6VR151SI6M=" + }, + "headMultiplicityLabel": { + "$ref": "AAAAAAFdG6VR151Tzp0=" + }, + "tailQualifiersCompartment": { + "$ref": "AAAAAAFdG6VR2J1U3mw=" + }, + "headQualifiersCompartment": { + "$ref": "AAAAAAFdG6VR2J1VdIc=" + } + } + ] + }, + { + "_type": "UMLUseCaseDiagram", + "_id": "AAAAAAFdF8yd/5z3Wwc=", + "_parent": { + "$ref": "AAAAAAFdF8bUGpzmKj4=" + }, + "name": "购物网站", + "visible": true, + "defaultDiagram": false, + "ownedViews": [ + { + "_type": "UMLActorView", + "_id": "AAAAAAFdGAKakqRiXVU=", + "_parent": { + "$ref": "AAAAAAFdF8yd/5z3Wwc=" + }, + "model": { + "$ref": "AAAAAAFdGAKakKRgInE=" + }, + "subViews": [ + { + "_type": "UMLNameCompartmentView", + "_id": "AAAAAAFdGAKakqRjG98=", + "_parent": { + "$ref": "AAAAAAFdGAKakqRiXVU=" + }, + "model": { + "$ref": "AAAAAAFdGAKakKRgInE=" + }, + "subViews": [ + { + "_type": "LabelView", + "_id": "AAAAAAFdGAKalKRkgoU=", + "_parent": { + "$ref": "AAAAAAFdGAKakqRjG98=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 80, + "top": 432, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdGAKalaRlXyo=", + "_parent": { + "$ref": "AAAAAAFdGAKakqRjG98=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;1", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 125, + "top": 549, + "width": 40, + "height": 13, + "autoResize": false, + "underline": false, + "text": "用户", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdGAKalqRm2U4=", + "_parent": { + "$ref": "AAAAAAFdGAKakqRjG98=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 80, + "top": 432, + "width": 65, + "height": 13, + "autoResize": false, + "underline": false, + "text": "(from UML)", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdGAKalqRnExY=", + "_parent": { + "$ref": "AAAAAAFdGAKakqRjG98=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 80, + "top": 432, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 1, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 120, + "top": 542, + "width": 50, + "height": 25, + "autoResize": false, + "stereotypeLabel": { + "$ref": "AAAAAAFdGAKalKRkgoU=" + }, + "nameLabel": { + "$ref": "AAAAAAFdGAKalaRlXyo=" + }, + "namespaceLabel": { + "$ref": "AAAAAAFdGAKalqRm2U4=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdGAKalqRnExY=" + } + }, + { + "_type": "UMLAttributeCompartmentView", + "_id": "AAAAAAFdGAKalqRoke0=", + "_parent": { + "$ref": "AAAAAAFdGAKakqRiXVU=" + }, + "model": { + "$ref": "AAAAAAFdGAKakKRgInE=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 40, + "top": 216, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLOperationCompartmentView", + "_id": "AAAAAAFdGAKalqRpCx8=", + "_parent": { + "$ref": "AAAAAAFdGAKakqRiXVU=" + }, + "model": { + "$ref": "AAAAAAFdGAKakKRgInE=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 40, + "top": 216, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLReceptionCompartmentView", + "_id": "AAAAAAFdGAKalqRq+G8=", + "_parent": { + "$ref": "AAAAAAFdGAKakqRiXVU=" + }, + "model": { + "$ref": "AAAAAAFdGAKakKRgInE=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 40, + "top": 216, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLTemplateParameterCompartmentView", + "_id": "AAAAAAFdGAKal6Rr7ig=", + "_parent": { + "$ref": "AAAAAAFdGAKakqRiXVU=" + }, + "model": { + "$ref": "AAAAAAFdGAKakKRgInE=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 40, + "top": 216, + "width": 10, + "height": 10, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": true, + "containerExtending": false, + "left": 120, + "top": 488, + "width": 50, + "height": 80, + "autoResize": false, + "stereotypeDisplay": "label", + "showVisibility": true, + "showNamespace": false, + "showProperty": true, + "showType": true, + "nameCompartment": { + "$ref": "AAAAAAFdGAKakqRjG98=" + }, + "wordWrap": false, + "suppressAttributes": true, + "suppressOperations": true, + "suppressReceptions": true, + "showMultiplicity": true, + "showOperationSignature": true, + "attributeCompartment": { + "$ref": "AAAAAAFdGAKalqRoke0=" + }, + "operationCompartment": { + "$ref": "AAAAAAFdGAKalqRpCx8=" + }, + "receptionCompartment": { + "$ref": "AAAAAAFdGAKalqRq+G8=" + }, + "templateParameterCompartment": { + "$ref": "AAAAAAFdGAKal6Rr7ig=" + } + }, + { + "_type": "UMLUseCaseView", + "_id": "AAAAAAFdGAO/iqSO/fU=", + "_parent": { + "$ref": "AAAAAAFdF8yd/5z3Wwc=" + }, + "model": { + "$ref": "AAAAAAFdGAO/iaSMYxI=" + }, + "subViews": [ + { + "_type": "UMLNameCompartmentView", + "_id": "AAAAAAFdGAO/i6SPYmM=", + "_parent": { + "$ref": "AAAAAAFdGAO/iqSO/fU=" + }, + "model": { + "$ref": "AAAAAAFdGAO/iaSMYxI=" + }, + "subViews": [ + { + "_type": "LabelView", + "_id": "AAAAAAFdGAO/i6SQA1I=", + "_parent": { + "$ref": "AAAAAAFdGAO/i6SPYmM=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 96, + "top": 0, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdGAO/jKSRG4E=", + "_parent": { + "$ref": "AAAAAAFdGAO/i6SPYmM=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;1", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 363.5, + "top": 299.5, + "width": 59, + "height": 13, + "autoResize": false, + "underline": false, + "text": "搜索产品", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdGAO/jKSSM84=", + "_parent": { + "$ref": "AAAAAAFdGAO/i6SPYmM=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 96, + "top": 0, + "width": 65, + "height": 13, + "autoResize": false, + "underline": false, + "text": "(from UML)", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdGAO/jKSTyrk=", + "_parent": { + "$ref": "AAAAAAFdGAO/i6SPYmM=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 96, + "top": 0, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 1, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 358.5, + "top": 292.5, + "width": 69, + "height": 25, + "autoResize": false, + "stereotypeLabel": { + "$ref": "AAAAAAFdGAO/i6SQA1I=" + }, + "nameLabel": { + "$ref": "AAAAAAFdGAO/jKSRG4E=" + }, + "namespaceLabel": { + "$ref": "AAAAAAFdGAO/jKSSM84=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdGAO/jKSTyrk=" + } + }, + { + "_type": "UMLAttributeCompartmentView", + "_id": "AAAAAAFdGAO/jKSULYo=", + "_parent": { + "$ref": "AAAAAAFdGAO/iqSO/fU=" + }, + "model": { + "$ref": "AAAAAAFdGAO/iaSMYxI=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 48, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLOperationCompartmentView", + "_id": "AAAAAAFdGAO/jKSVv9A=", + "_parent": { + "$ref": "AAAAAAFdGAO/iqSO/fU=" + }, + "model": { + "$ref": "AAAAAAFdGAO/iaSMYxI=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 48, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLReceptionCompartmentView", + "_id": "AAAAAAFdGAO/jaSWaoI=", + "_parent": { + "$ref": "AAAAAAFdGAO/iqSO/fU=" + }, + "model": { + "$ref": "AAAAAAFdGAO/iaSMYxI=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 48, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLTemplateParameterCompartmentView", + "_id": "AAAAAAFdGAO/jaSXnr0=", + "_parent": { + "$ref": "AAAAAAFdGAO/iqSO/fU=" + }, + "model": { + "$ref": "AAAAAAFdGAO/iaSMYxI=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 48, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLExtensionPointCompartmentView", + "_id": "AAAAAAFdGAO/jaSYrk8=", + "_parent": { + "$ref": "AAAAAAFdGAO/iqSO/fU=" + }, + "model": { + "$ref": "AAAAAAFdGAO/iaSMYxI=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 48, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": true, + "containerExtending": false, + "left": 344, + "top": 288, + "width": 98, + "height": 35, + "autoResize": false, + "stereotypeDisplay": "label", + "showVisibility": true, + "showNamespace": false, + "showProperty": true, + "showType": true, + "nameCompartment": { + "$ref": "AAAAAAFdGAO/i6SPYmM=" + }, + "wordWrap": false, + "suppressAttributes": true, + "suppressOperations": true, + "suppressReceptions": true, + "showMultiplicity": true, + "showOperationSignature": true, + "attributeCompartment": { + "$ref": "AAAAAAFdGAO/jKSULYo=" + }, + "operationCompartment": { + "$ref": "AAAAAAFdGAO/jKSVv9A=" + }, + "receptionCompartment": { + "$ref": "AAAAAAFdGAO/jaSWaoI=" + }, + "templateParameterCompartment": { + "$ref": "AAAAAAFdGAO/jaSXnr0=" + }, + "extensionPointCompartment": { + "$ref": "AAAAAAFdGAO/jaSYrk8=" + } + }, + { + "_type": "UMLUseCaseView", + "_id": "AAAAAAFdGAW4LqTsTLE=", + "_parent": { + "$ref": "AAAAAAFdF8yd/5z3Wwc=" + }, + "model": { + "$ref": "AAAAAAFdGAW4LaTq8JA=" + }, + "subViews": [ + { + "_type": "UMLNameCompartmentView", + "_id": "AAAAAAFdGAW4LqTtPZc=", + "_parent": { + "$ref": "AAAAAAFdGAW4LqTsTLE=" + }, + "model": { + "$ref": "AAAAAAFdGAW4LaTq8JA=" + }, + "subViews": [ + { + "_type": "LabelView", + "_id": "AAAAAAFdGAW4LqTuTJk=", + "_parent": { + "$ref": "AAAAAAFdGAW4LqTtPZc=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -48, + "top": 192, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdGAW4LqTvhiU=", + "_parent": { + "$ref": "AAAAAAFdGAW4LqTtPZc=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;1", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 283.5, + "top": 547.5, + "width": 59, + "height": 13, + "autoResize": false, + "underline": false, + "text": "登录", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdGAW4LqTwLGA=", + "_parent": { + "$ref": "AAAAAAFdGAW4LqTtPZc=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -48, + "top": 192, + "width": 65, + "height": 13, + "autoResize": false, + "underline": false, + "text": "(from UML)", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdGAW4LqTxlcc=", + "_parent": { + "$ref": "AAAAAAFdGAW4LqTtPZc=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -48, + "top": 192, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 1, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 278.5, + "top": 540.5, + "width": 69, + "height": 25, + "autoResize": false, + "stereotypeLabel": { + "$ref": "AAAAAAFdGAW4LqTuTJk=" + }, + "nameLabel": { + "$ref": "AAAAAAFdGAW4LqTvhiU=" + }, + "namespaceLabel": { + "$ref": "AAAAAAFdGAW4LqTwLGA=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdGAW4LqTxlcc=" + } + }, + { + "_type": "UMLAttributeCompartmentView", + "_id": "AAAAAAFdGAW4L6Ty/cY=", + "_parent": { + "$ref": "AAAAAAFdGAW4LqTsTLE=" + }, + "model": { + "$ref": "AAAAAAFdGAW4LaTq8JA=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -24, + "top": 96, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLOperationCompartmentView", + "_id": "AAAAAAFdGAW4L6TzO8g=", + "_parent": { + "$ref": "AAAAAAFdGAW4LqTsTLE=" + }, + "model": { + "$ref": "AAAAAAFdGAW4LaTq8JA=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -24, + "top": 96, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLReceptionCompartmentView", + "_id": "AAAAAAFdGAW4L6T0ZYo=", + "_parent": { + "$ref": "AAAAAAFdGAW4LqTsTLE=" + }, + "model": { + "$ref": "AAAAAAFdGAW4LaTq8JA=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -24, + "top": 96, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLTemplateParameterCompartmentView", + "_id": "AAAAAAFdGAW4L6T1z/U=", + "_parent": { + "$ref": "AAAAAAFdGAW4LqTsTLE=" + }, + "model": { + "$ref": "AAAAAAFdGAW4LaTq8JA=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -24, + "top": 96, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLExtensionPointCompartmentView", + "_id": "AAAAAAFdGAW4L6T22yQ=", + "_parent": { + "$ref": "AAAAAAFdGAW4LqTsTLE=" + }, + "model": { + "$ref": "AAAAAAFdGAW4LaTq8JA=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -24, + "top": 96, + "width": 10, + "height": 10, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": true, + "containerExtending": false, + "left": 264, + "top": 536, + "width": 98, + "height": 35, + "autoResize": false, + "stereotypeDisplay": "label", + "showVisibility": true, + "showNamespace": false, + "showProperty": true, + "showType": true, + "nameCompartment": { + "$ref": "AAAAAAFdGAW4LqTtPZc=" + }, + "wordWrap": false, + "suppressAttributes": true, + "suppressOperations": true, + "suppressReceptions": true, + "showMultiplicity": true, + "showOperationSignature": true, + "attributeCompartment": { + "$ref": "AAAAAAFdGAW4L6Ty/cY=" + }, + "operationCompartment": { + "$ref": "AAAAAAFdGAW4L6TzO8g=" + }, + "receptionCompartment": { + "$ref": "AAAAAAFdGAW4L6T0ZYo=" + }, + "templateParameterCompartment": { + "$ref": "AAAAAAFdGAW4L6T1z/U=" + }, + "extensionPointCompartment": { + "$ref": "AAAAAAFdGAW4L6T22yQ=" + } + }, + { + "_type": "UMLUseCaseView", + "_id": "AAAAAAFdGAXoA6UbzVQ=", + "_parent": { + "$ref": "AAAAAAFdF8yd/5z3Wwc=" + }, + "model": { + "$ref": "AAAAAAFdGAXoAqUZa/0=" + }, + "subViews": [ + { + "_type": "UMLNameCompartmentView", + "_id": "AAAAAAFdGAXoA6UcL8A=", + "_parent": { + "$ref": "AAAAAAFdGAXoA6UbzVQ=" + }, + "model": { + "$ref": "AAAAAAFdGAXoAqUZa/0=" + }, + "subViews": [ + { + "_type": "LabelView", + "_id": "AAAAAAFdGAXoA6UdkQA=", + "_parent": { + "$ref": "AAAAAAFdGAXoA6UcL8A=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 512, + "top": -256, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdGAXoBKUe/lA=", + "_parent": { + "$ref": "AAAAAAFdGAXoA6UcL8A=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;1", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 557, + "top": 379.5, + "width": 64, + "height": 13, + "autoResize": false, + "underline": false, + "text": "加入购物车", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdGAXoBKUftL0=", + "_parent": { + "$ref": "AAAAAAFdGAXoA6UcL8A=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 512, + "top": -256, + "width": 65, + "height": 13, + "autoResize": false, + "underline": false, + "text": "(from UML)", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdGAXoBKUgLYU=", + "_parent": { + "$ref": "AAAAAAFdGAXoA6UcL8A=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 512, + "top": -256, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 1, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 552, + "top": 372.5, + "width": 75, + "height": 25, + "autoResize": false, + "stereotypeLabel": { + "$ref": "AAAAAAFdGAXoA6UdkQA=" + }, + "nameLabel": { + "$ref": "AAAAAAFdGAXoBKUe/lA=" + }, + "namespaceLabel": { + "$ref": "AAAAAAFdGAXoBKUftL0=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdGAXoBKUgLYU=" + } + }, + { + "_type": "UMLAttributeCompartmentView", + "_id": "AAAAAAFdGAXoBKUhVMo=", + "_parent": { + "$ref": "AAAAAAFdGAXoA6UbzVQ=" + }, + "model": { + "$ref": "AAAAAAFdGAXoAqUZa/0=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 256, + "top": -128, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLOperationCompartmentView", + "_id": "AAAAAAFdGAXoBKUiMzs=", + "_parent": { + "$ref": "AAAAAAFdGAXoA6UbzVQ=" + }, + "model": { + "$ref": "AAAAAAFdGAXoAqUZa/0=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 256, + "top": -128, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLReceptionCompartmentView", + "_id": "AAAAAAFdGAXoBKUj3f8=", + "_parent": { + "$ref": "AAAAAAFdGAXoA6UbzVQ=" + }, + "model": { + "$ref": "AAAAAAFdGAXoAqUZa/0=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 256, + "top": -128, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLTemplateParameterCompartmentView", + "_id": "AAAAAAFdGAXoBKUk5Oc=", + "_parent": { + "$ref": "AAAAAAFdGAXoA6UbzVQ=" + }, + "model": { + "$ref": "AAAAAAFdGAXoAqUZa/0=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 256, + "top": -128, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLExtensionPointCompartmentView", + "_id": "AAAAAAFdGAXoBKUlCmw=", + "_parent": { + "$ref": "AAAAAAFdGAXoA6UbzVQ=" + }, + "model": { + "$ref": "AAAAAAFdGAXoAqUZa/0=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 256, + "top": -128, + "width": 10, + "height": 10, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": true, + "containerExtending": false, + "left": 536, + "top": 368, + "width": 106, + "height": 35, + "autoResize": false, + "stereotypeDisplay": "label", + "showVisibility": true, + "showNamespace": false, + "showProperty": true, + "showType": true, + "nameCompartment": { + "$ref": "AAAAAAFdGAXoA6UcL8A=" + }, + "wordWrap": false, + "suppressAttributes": true, + "suppressOperations": true, + "suppressReceptions": true, + "showMultiplicity": true, + "showOperationSignature": true, + "attributeCompartment": { + "$ref": "AAAAAAFdGAXoBKUhVMo=" + }, + "operationCompartment": { + "$ref": "AAAAAAFdGAXoBKUiMzs=" + }, + "receptionCompartment": { + "$ref": "AAAAAAFdGAXoBKUj3f8=" + }, + "templateParameterCompartment": { + "$ref": "AAAAAAFdGAXoBKUk5Oc=" + }, + "extensionPointCompartment": { + "$ref": "AAAAAAFdGAXoBKUlCmw=" + } + }, + { + "_type": "UMLUseCaseView", + "_id": "AAAAAAFdGAY0uaVJfPE=", + "_parent": { + "$ref": "AAAAAAFdF8yd/5z3Wwc=" + }, + "model": { + "$ref": "AAAAAAFdGAY0uKVHc28=" + }, + "subViews": [ + { + "_type": "UMLNameCompartmentView", + "_id": "AAAAAAFdGAY0uqVKVek=", + "_parent": { + "$ref": "AAAAAAFdGAY0uaVJfPE=" + }, + "model": { + "$ref": "AAAAAAFdGAY0uKVHc28=" + }, + "subViews": [ + { + "_type": "LabelView", + "_id": "AAAAAAFdGAY0uqVLTx8=", + "_parent": { + "$ref": "AAAAAAFdGAY0uqVKVek=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 384, + "top": -224, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdGAY0uqVMq7M=", + "_parent": { + "$ref": "AAAAAAFdGAY0uqVKVek=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;1", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 491.5, + "top": 459.5, + "width": 59, + "height": 13, + "autoResize": false, + "underline": false, + "text": "下订单", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdGAY0uqVNyeI=", + "_parent": { + "$ref": "AAAAAAFdGAY0uqVKVek=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 384, + "top": -224, + "width": 65, + "height": 13, + "autoResize": false, + "underline": false, + "text": "(from UML)", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdGAY0uqVOXIE=", + "_parent": { + "$ref": "AAAAAAFdGAY0uqVKVek=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 384, + "top": -224, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 1, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 486.5, + "top": 452.5, + "width": 69, + "height": 25, + "autoResize": false, + "stereotypeLabel": { + "$ref": "AAAAAAFdGAY0uqVLTx8=" + }, + "nameLabel": { + "$ref": "AAAAAAFdGAY0uqVMq7M=" + }, + "namespaceLabel": { + "$ref": "AAAAAAFdGAY0uqVNyeI=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdGAY0uqVOXIE=" + } + }, + { + "_type": "UMLAttributeCompartmentView", + "_id": "AAAAAAFdGAY0u6VPDCs=", + "_parent": { + "$ref": "AAAAAAFdGAY0uaVJfPE=" + }, + "model": { + "$ref": "AAAAAAFdGAY0uKVHc28=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 192, + "top": -112, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLOperationCompartmentView", + "_id": "AAAAAAFdGAY0u6VQoxY=", + "_parent": { + "$ref": "AAAAAAFdGAY0uaVJfPE=" + }, + "model": { + "$ref": "AAAAAAFdGAY0uKVHc28=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 192, + "top": -112, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLReceptionCompartmentView", + "_id": "AAAAAAFdGAY0vKVR6Lo=", + "_parent": { + "$ref": "AAAAAAFdGAY0uaVJfPE=" + }, + "model": { + "$ref": "AAAAAAFdGAY0uKVHc28=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 192, + "top": -112, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLTemplateParameterCompartmentView", + "_id": "AAAAAAFdGAY0vKVS8fI=", + "_parent": { + "$ref": "AAAAAAFdGAY0uaVJfPE=" + }, + "model": { + "$ref": "AAAAAAFdGAY0uKVHc28=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 192, + "top": -112, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLExtensionPointCompartmentView", + "_id": "AAAAAAFdGAY0vKVTC5U=", + "_parent": { + "$ref": "AAAAAAFdGAY0uaVJfPE=" + }, + "model": { + "$ref": "AAAAAAFdGAY0uKVHc28=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 192, + "top": -112, + "width": 10, + "height": 10, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": true, + "containerExtending": false, + "left": 472, + "top": 448, + "width": 98, + "height": 35, + "autoResize": false, + "stereotypeDisplay": "label", + "showVisibility": true, + "showNamespace": false, + "showProperty": true, + "showType": true, + "nameCompartment": { + "$ref": "AAAAAAFdGAY0uqVKVek=" + }, + "wordWrap": false, + "suppressAttributes": true, + "suppressOperations": true, + "suppressReceptions": true, + "showMultiplicity": true, + "showOperationSignature": true, + "attributeCompartment": { + "$ref": "AAAAAAFdGAY0u6VPDCs=" + }, + "operationCompartment": { + "$ref": "AAAAAAFdGAY0u6VQoxY=" + }, + "receptionCompartment": { + "$ref": "AAAAAAFdGAY0vKVR6Lo=" + }, + "templateParameterCompartment": { + "$ref": "AAAAAAFdGAY0vKVS8fI=" + }, + "extensionPointCompartment": { + "$ref": "AAAAAAFdGAY0vKVTC5U=" + } + }, + { + "_type": "UMLAssociationView", + "_id": "AAAAAAFdGBgGqqbtA6o=", + "_parent": { + "$ref": "AAAAAAFdF8yd/5z3Wwc=" + }, + "model": { + "$ref": "AAAAAAFdGBgGqabpFws=" + }, + "subViews": [ + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdGBgGqqbulzY=", + "_parent": { + "$ref": "AAAAAAFdGBgGqqbtA6o=" + }, + "model": { + "$ref": "AAAAAAFdGBgGqabpFws=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 261, + "top": 395, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdGBgGqqbtA6o=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdGBgGqqbvRns=", + "_parent": { + "$ref": "AAAAAAFdGBgGqqbtA6o=" + }, + "model": { + "$ref": "AAAAAAFdGBgGqabpFws=" + }, + "visible": null, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 251, + "top": 384, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdGBgGqqbtA6o=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdGBgGqqbw+8Q=", + "_parent": { + "$ref": "AAAAAAFdGBgGqqbtA6o=" + }, + "model": { + "$ref": "AAAAAAFdGBgGqabpFws=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 280, + "top": 418, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdGBgGqqbtA6o=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdGBgGqqbx1Oo=", + "_parent": { + "$ref": "AAAAAAFdGBgGqqbtA6o=" + }, + "model": { + "$ref": "AAAAAAFdGBgGqabqC0k=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 179, + "top": 469, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 0.5235987755982988, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdGBgGqqbtA6o=" + }, + "edgePosition": 2, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdGBgGqqby2Nw=", + "_parent": { + "$ref": "AAAAAAFdGBgGqqbtA6o=" + }, + "model": { + "$ref": "AAAAAAFdGBgGqabqC0k=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 172, + "top": 458, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 0.7853981633974483, + "distance": 40, + "hostEdge": { + "$ref": "AAAAAAFdGBgGqqbtA6o=" + }, + "edgePosition": 2, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdGBgGq6bzark=", + "_parent": { + "$ref": "AAAAAAFdGBgGqqbtA6o=" + }, + "model": { + "$ref": "AAAAAAFdGBgGqabqC0k=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 194, + "top": 492, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -0.5235987755982988, + "distance": 25, + "hostEdge": { + "$ref": "AAAAAAFdGBgGqqbtA6o=" + }, + "edgePosition": 2, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdGBgGq6b0+5A=", + "_parent": { + "$ref": "AAAAAAFdGBgGqqbtA6o=" + }, + "model": { + "$ref": "AAAAAAFdGBgGqabrjBY=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 342, + "top": 323, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -0.5235987755982988, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdGBgGqqbtA6o=" + }, + "edgePosition": 0, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdGBgGq6b1X1E=", + "_parent": { + "$ref": "AAAAAAFdGBgGqqbtA6o=" + }, + "model": { + "$ref": "AAAAAAFdGBgGqabrjBY=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 332, + "top": 314, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -0.7853981633974483, + "distance": 40, + "hostEdge": { + "$ref": "AAAAAAFdGBgGqqbtA6o=" + }, + "edgePosition": 0, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdGBgGq6b22tU=", + "_parent": { + "$ref": "AAAAAAFdGBgGqqbtA6o=" + }, + "model": { + "$ref": "AAAAAAFdGBgGqabrjBY=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 364, + "top": 340, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 0.5235987755982988, + "distance": 25, + "hostEdge": { + "$ref": "AAAAAAFdGBgGqqbtA6o=" + }, + "edgePosition": 0, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "UMLQualifierCompartmentView", + "_id": "AAAAAAFdGBgGq6b3GEg=", + "_parent": { + "$ref": "AAAAAAFdGBgGqqbtA6o=" + }, + "model": { + "$ref": "AAAAAAFdGBgGqabqC0k=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLQualifierCompartmentView", + "_id": "AAAAAAFdGBgGq6b4aEw=", + "_parent": { + "$ref": "AAAAAAFdGBgGqqbtA6o=" + }, + "model": { + "$ref": "AAAAAAFdGBgGqabrjBY=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "head": { + "$ref": "AAAAAAFdGAO/iqSO/fU=" + }, + "tail": { + "$ref": "AAAAAAFdGAKakqRiXVU=" + }, + "lineStyle": 1, + "points": "170:504;372:323", + "stereotypeDisplay": "label", + "showVisibility": true, + "showProperty": true, + "nameLabel": { + "$ref": "AAAAAAFdGBgGqqbulzY=" + }, + "stereotypeLabel": { + "$ref": "AAAAAAFdGBgGqqbvRns=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdGBgGqqbw+8Q=" + }, + "showMultiplicity": true, + "showType": true, + "tailRoleNameLabel": { + "$ref": "AAAAAAFdGBgGqqbx1Oo=" + }, + "tailPropertyLabel": { + "$ref": "AAAAAAFdGBgGqqby2Nw=" + }, + "tailMultiplicityLabel": { + "$ref": "AAAAAAFdGBgGq6bzark=" + }, + "headRoleNameLabel": { + "$ref": "AAAAAAFdGBgGq6b0+5A=" + }, + "headPropertyLabel": { + "$ref": "AAAAAAFdGBgGq6b1X1E=" + }, + "headMultiplicityLabel": { + "$ref": "AAAAAAFdGBgGq6b22tU=" + }, + "tailQualifiersCompartment": { + "$ref": "AAAAAAFdGBgGq6b3GEg=" + }, + "headQualifiersCompartment": { + "$ref": "AAAAAAFdGBgGq6b4aEw=" + } + }, + { + "_type": "UMLUseCaseView", + "_id": "AAAAAAFdHQ4fLp+/lbg=", + "_parent": { + "$ref": "AAAAAAFdF8yd/5z3Wwc=" + }, + "model": { + "$ref": "AAAAAAFdHQ4fLZ+9HuM=" + }, + "subViews": [ + { + "_type": "UMLNameCompartmentView", + "_id": "AAAAAAFdHQ4fL5/A/FM=", + "_parent": { + "$ref": "AAAAAAFdHQ4fLp+/lbg=" + }, + "model": { + "$ref": "AAAAAAFdHQ4fLZ+9HuM=" + }, + "subViews": [ + { + "_type": "LabelView", + "_id": "AAAAAAFdHQ4fL5/ByjE=", + "_parent": { + "$ref": "AAAAAAFdHQ4fL5/A/FM=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdHQ4fL5/Cees=", + "_parent": { + "$ref": "AAAAAAFdHQ4fL5/A/FM=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;1", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 567.5, + "top": 283.5, + "width": 77, + "height": 13, + "autoResize": false, + "underline": false, + "text": "查看产品详情", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdHQ4fL5/Dl2s=", + "_parent": { + "$ref": "AAAAAAFdHQ4fL5/A/FM=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 65, + "height": 13, + "autoResize": false, + "underline": false, + "text": "(from UML)", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdHQ4fL5/ELok=", + "_parent": { + "$ref": "AAAAAAFdHQ4fL5/A/FM=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 1, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 562.5, + "top": 276.5, + "width": 88, + "height": 25, + "autoResize": false, + "stereotypeLabel": { + "$ref": "AAAAAAFdHQ4fL5/ByjE=" + }, + "nameLabel": { + "$ref": "AAAAAAFdHQ4fL5/Cees=" + }, + "namespaceLabel": { + "$ref": "AAAAAAFdHQ4fL5/Dl2s=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdHQ4fL5/ELok=" + } + }, + { + "_type": "UMLAttributeCompartmentView", + "_id": "AAAAAAFdHQ4fL5/FyyE=", + "_parent": { + "$ref": "AAAAAAFdHQ4fLp+/lbg=" + }, + "model": { + "$ref": "AAAAAAFdHQ4fLZ+9HuM=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLOperationCompartmentView", + "_id": "AAAAAAFdHQ4fMJ/GK3o=", + "_parent": { + "$ref": "AAAAAAFdHQ4fLp+/lbg=" + }, + "model": { + "$ref": "AAAAAAFdHQ4fLZ+9HuM=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLReceptionCompartmentView", + "_id": "AAAAAAFdHQ4fMJ/Hh90=", + "_parent": { + "$ref": "AAAAAAFdHQ4fLp+/lbg=" + }, + "model": { + "$ref": "AAAAAAFdHQ4fLZ+9HuM=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLTemplateParameterCompartmentView", + "_id": "AAAAAAFdHQ4fMJ/I0dw=", + "_parent": { + "$ref": "AAAAAAFdHQ4fLp+/lbg=" + }, + "model": { + "$ref": "AAAAAAFdHQ4fLZ+9HuM=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLExtensionPointCompartmentView", + "_id": "AAAAAAFdHQ4fMJ/Jrj0=", + "_parent": { + "$ref": "AAAAAAFdHQ4fLp+/lbg=" + }, + "model": { + "$ref": "AAAAAAFdHQ4fLZ+9HuM=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": true, + "containerExtending": false, + "left": 544, + "top": 272, + "width": 124, + "height": 35, + "autoResize": false, + "stereotypeDisplay": "label", + "showVisibility": true, + "showNamespace": false, + "showProperty": true, + "showType": true, + "nameCompartment": { + "$ref": "AAAAAAFdHQ4fL5/A/FM=" + }, + "wordWrap": false, + "suppressAttributes": true, + "suppressOperations": true, + "suppressReceptions": true, + "showMultiplicity": true, + "showOperationSignature": true, + "attributeCompartment": { + "$ref": "AAAAAAFdHQ4fL5/FyyE=" + }, + "operationCompartment": { + "$ref": "AAAAAAFdHQ4fMJ/GK3o=" + }, + "receptionCompartment": { + "$ref": "AAAAAAFdHQ4fMJ/Hh90=" + }, + "templateParameterCompartment": { + "$ref": "AAAAAAFdHQ4fMJ/I0dw=" + }, + "extensionPointCompartment": { + "$ref": "AAAAAAFdHQ4fMJ/Jrj0=" + } + }, + { + "_type": "UMLExtendView", + "_id": "AAAAAAFdHQ57DaAqNs0=", + "_parent": { + "$ref": "AAAAAAFdF8yd/5z3Wwc=" + }, + "model": { + "$ref": "AAAAAAFdHQ57DaAopRI=" + }, + "subViews": [ + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ57DqAr1sM=", + "_parent": { + "$ref": "AAAAAAFdHQ57DaAqNs0=" + }, + "model": { + "$ref": "AAAAAAFdHQ57DaAopRI=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 493, + "top": 305, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdHQ57DaAqNs0=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ57DqAshCo=", + "_parent": { + "$ref": "AAAAAAFdHQ57DaAqNs0=" + }, + "model": { + "$ref": "AAAAAAFdHQ57DaAopRI=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 464, + "top": 279, + "width": 53, + "height": 13, + "autoResize": false, + "alpha": -1.4707737086130512, + "distance": 11.180339887498949, + "hostEdge": { + "$ref": "AAAAAAFdHQ57DaAqNs0=" + }, + "edgePosition": 1, + "underline": false, + "text": "«extend»", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ57DqAt9cs=", + "_parent": { + "$ref": "AAAAAAFdHQ57DaAqNs0=" + }, + "model": { + "$ref": "AAAAAAFdHQ57DaAopRI=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 490, + "top": 276, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdHQ57DaAqNs0=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "head": { + "$ref": "AAAAAAFdGAO/iqSO/fU=" + }, + "tail": { + "$ref": "AAAAAAFdHQ4fLp+/lbg=" + }, + "lineStyle": 1, + "points": "543:294;442:301", + "stereotypeDisplay": "label", + "showVisibility": true, + "showProperty": true, + "nameLabel": { + "$ref": "AAAAAAFdHQ57DqAr1sM=" + }, + "stereotypeLabel": { + "$ref": "AAAAAAFdHQ57DqAshCo=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdHQ57DqAt9cs=" + } + }, + { + "_type": "UMLExtendView", + "_id": "AAAAAAFdHQ7gj6GpG4g=", + "_parent": { + "$ref": "AAAAAAFdF8yd/5z3Wwc=" + }, + "model": { + "$ref": "AAAAAAFdHQ7gj6Gn9wA=" + }, + "subViews": [ + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ7gj6GqUSs=", + "_parent": { + "$ref": "AAAAAAFdHQ7gj6GpG4g=" + }, + "model": { + "$ref": "AAAAAAFdHQ7gj6Gn9wA=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 484, + "top": 352, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdHQ7gj6GpG4g=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ7gj6Grtfg=", + "_parent": { + "$ref": "AAAAAAFdHQ7gj6GpG4g=" + }, + "model": { + "$ref": "AAAAAAFdHQ7gj6Gn9wA=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 440, + "top": 344, + "width": 53, + "height": 13, + "autoResize": false, + "alpha": 0.5922712548213971, + "distance": 24.515301344262525, + "hostEdge": { + "$ref": "AAAAAAFdHQ7gj6GpG4g=" + }, + "edgePosition": 1, + "underline": false, + "text": "«extend»", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ7gj6Gs0Zk=", + "_parent": { + "$ref": "AAAAAAFdHQ7gj6GpG4g=" + }, + "model": { + "$ref": "AAAAAAFdHQ7gj6Gn9wA=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 495, + "top": 325, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdHQ7gj6GpG4g=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "head": { + "$ref": "AAAAAAFdGAO/iqSO/fU=" + }, + "tail": { + "$ref": "AAAAAAFdGAXoA6UbzVQ=" + }, + "lineStyle": 1, + "points": "544:367;436:323", + "stereotypeDisplay": "label", + "showVisibility": true, + "showProperty": true, + "nameLabel": { + "$ref": "AAAAAAFdHQ7gj6GqUSs=" + }, + "stereotypeLabel": { + "$ref": "AAAAAAFdHQ7gj6Grtfg=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdHQ7gj6Gs0Zk=" + } + }, + { + "_type": "UMLExtendView", + "_id": "AAAAAAFdHQ8AdqIMIpQ=", + "_parent": { + "$ref": "AAAAAAFdF8yd/5z3Wwc=" + }, + "model": { + "$ref": "AAAAAAFdHQ8AdqIKyBQ=" + }, + "subViews": [ + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ8AdqINQDI=", + "_parent": { + "$ref": "AAAAAAFdHQ8AdqIMIpQ=" + }, + "model": { + "$ref": "AAAAAAFdHQ8AdqIKyBQ=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 581, + "top": 328, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdHQ8AdqIMIpQ=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ8AdqIOOpY=", + "_parent": { + "$ref": "AAAAAAFdHQ8AdqIMIpQ=" + }, + "model": { + "$ref": "AAAAAAFdHQ8AdqIKyBQ=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 540, + "top": 325, + "width": 53, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdHQ8AdqIMIpQ=" + }, + "edgePosition": 1, + "underline": false, + "text": "«extend»", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ8AdqIP3rw=", + "_parent": { + "$ref": "AAAAAAFdHQ8AdqIMIpQ=" + }, + "model": { + "$ref": "AAAAAAFdHQ8AdqIKyBQ=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 610, + "top": 333, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdHQ8AdqIMIpQ=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "head": { + "$ref": "AAAAAAFdHQ4fLp+/lbg=" + }, + "tail": { + "$ref": "AAAAAAFdGAXoA6UbzVQ=" + }, + "lineStyle": 1, + "points": "591:367;602:307", + "stereotypeDisplay": "label", + "showVisibility": true, + "showProperty": true, + "nameLabel": { + "$ref": "AAAAAAFdHQ8AdqINQDI=" + }, + "stereotypeLabel": { + "$ref": "AAAAAAFdHQ8AdqIOOpY=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdHQ8AdqIP3rw=" + } + }, + { + "_type": "UMLUseCaseView", + "_id": "AAAAAAFdHQ882aKZU8U=", + "_parent": { + "$ref": "AAAAAAFdF8yd/5z3Wwc=" + }, + "model": { + "$ref": "AAAAAAFdHQ882KKXixg=" + }, + "subViews": [ + { + "_type": "UMLNameCompartmentView", + "_id": "AAAAAAFdHQ882aKagds=", + "_parent": { + "$ref": "AAAAAAFdHQ882aKZU8U=" + }, + "model": { + "$ref": "AAAAAAFdHQ882KKXixg=" + }, + "subViews": [ + { + "_type": "LabelView", + "_id": "AAAAAAFdHQ882aKbCFY=", + "_parent": { + "$ref": "AAAAAAFdHQ882aKagds=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -144, + "top": 0, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdHQ882aKcJss=", + "_parent": { + "$ref": "AAAAAAFdHQ882aKagds=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;1", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 333, + "top": 419.5, + "width": 64, + "height": 13, + "autoResize": false, + "underline": false, + "text": "显示购物车", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdHQ882aKdAj4=", + "_parent": { + "$ref": "AAAAAAFdHQ882aKagds=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -144, + "top": 0, + "width": 65, + "height": 13, + "autoResize": false, + "underline": false, + "text": "(from UML)", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdHQ882aKeFk8=", + "_parent": { + "$ref": "AAAAAAFdHQ882aKagds=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -144, + "top": 0, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 1, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 328, + "top": 412.5, + "width": 75, + "height": 25, + "autoResize": false, + "stereotypeLabel": { + "$ref": "AAAAAAFdHQ882aKbCFY=" + }, + "nameLabel": { + "$ref": "AAAAAAFdHQ882aKcJss=" + }, + "namespaceLabel": { + "$ref": "AAAAAAFdHQ882aKdAj4=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdHQ882aKeFk8=" + } + }, + { + "_type": "UMLAttributeCompartmentView", + "_id": "AAAAAAFdHQ882aKfXY8=", + "_parent": { + "$ref": "AAAAAAFdHQ882aKZU8U=" + }, + "model": { + "$ref": "AAAAAAFdHQ882KKXixg=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -72, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLOperationCompartmentView", + "_id": "AAAAAAFdHQ882qKgImc=", + "_parent": { + "$ref": "AAAAAAFdHQ882aKZU8U=" + }, + "model": { + "$ref": "AAAAAAFdHQ882KKXixg=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -72, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLReceptionCompartmentView", + "_id": "AAAAAAFdHQ882qKhtB0=", + "_parent": { + "$ref": "AAAAAAFdHQ882aKZU8U=" + }, + "model": { + "$ref": "AAAAAAFdHQ882KKXixg=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -72, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLTemplateParameterCompartmentView", + "_id": "AAAAAAFdHQ882qKiU5Q=", + "_parent": { + "$ref": "AAAAAAFdHQ882aKZU8U=" + }, + "model": { + "$ref": "AAAAAAFdHQ882KKXixg=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -72, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLExtensionPointCompartmentView", + "_id": "AAAAAAFdHQ882qKj6Uw=", + "_parent": { + "$ref": "AAAAAAFdHQ882aKZU8U=" + }, + "model": { + "$ref": "AAAAAAFdHQ882KKXixg=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -72, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": true, + "containerExtending": false, + "left": 312, + "top": 408, + "width": 106, + "height": 35, + "autoResize": false, + "stereotypeDisplay": "label", + "showVisibility": true, + "showNamespace": false, + "showProperty": true, + "showType": true, + "nameCompartment": { + "$ref": "AAAAAAFdHQ882aKagds=" + }, + "wordWrap": false, + "suppressAttributes": true, + "suppressOperations": true, + "suppressReceptions": true, + "showMultiplicity": true, + "showOperationSignature": true, + "attributeCompartment": { + "$ref": "AAAAAAFdHQ882aKfXY8=" + }, + "operationCompartment": { + "$ref": "AAAAAAFdHQ882qKgImc=" + }, + "receptionCompartment": { + "$ref": "AAAAAAFdHQ882qKhtB0=" + }, + "templateParameterCompartment": { + "$ref": "AAAAAAFdHQ882qKiU5Q=" + }, + "extensionPointCompartment": { + "$ref": "AAAAAAFdHQ882qKj6Uw=" + } + }, + { + "_type": "UMLAssociationView", + "_id": "AAAAAAFdHQ9cP6L6Aeo=", + "_parent": { + "$ref": "AAAAAAFdF8yd/5z3Wwc=" + }, + "model": { + "$ref": "AAAAAAFdHQ9cPqL2MKE=" + }, + "subViews": [ + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ9cP6L7zvs=", + "_parent": { + "$ref": "AAAAAAFdHQ9cP6L6Aeo=" + }, + "model": { + "$ref": "AAAAAAFdHQ9cPqL2MKE=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 240, + "top": 459, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdHQ9cP6L6Aeo=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ9cQaL8CqM=", + "_parent": { + "$ref": "AAAAAAFdHQ9cP6L6Aeo=" + }, + "model": { + "$ref": "AAAAAAFdHQ9cPqL2MKE=" + }, + "visible": null, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 234, + "top": 445, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdHQ9cP6L6Aeo=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ9cQqL9dnk=", + "_parent": { + "$ref": "AAAAAAFdHQ9cP6L6Aeo=" + }, + "model": { + "$ref": "AAAAAAFdHQ9cPqL2MKE=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 253, + "top": 486, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdHQ9cP6L6Aeo=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ9cQqL+ddA=", + "_parent": { + "$ref": "AAAAAAFdHQ9cP6L6Aeo=" + }, + "model": { + "$ref": "AAAAAAFdHQ9cPqL3JSg=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 187, + "top": 484, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 0.5235987755982988, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdHQ9cP6L6Aeo=" + }, + "edgePosition": 2, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ9cQqL/dNg=", + "_parent": { + "$ref": "AAAAAAFdHQ9cP6L6Aeo=" + }, + "model": { + "$ref": "AAAAAAFdHQ9cPqL3JSg=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 183, + "top": 471, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 0.7853981633974483, + "distance": 40, + "hostEdge": { + "$ref": "AAAAAAFdHQ9cP6L6Aeo=" + }, + "edgePosition": 2, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ9cQqMATrE=", + "_parent": { + "$ref": "AAAAAAFdHQ9cP6L6Aeo=" + }, + "model": { + "$ref": "AAAAAAFdHQ9cPqL3JSg=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 194, + "top": 511, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -0.5235987755982988, + "distance": 25, + "hostEdge": { + "$ref": "AAAAAAFdHQ9cP6L6Aeo=" + }, + "edgePosition": 2, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ9cQqMBCKU=", + "_parent": { + "$ref": "AAAAAAFdHQ9cP6L6Aeo=" + }, + "model": { + "$ref": "AAAAAAFdHQ9cPqL4Obc=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 295, + "top": 434, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -0.5235987755982988, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdHQ9cP6L6Aeo=" + }, + "edgePosition": 0, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ9cQqMCH3Y=", + "_parent": { + "$ref": "AAAAAAFdHQ9cP6L6Aeo=" + }, + "model": { + "$ref": "AAAAAAFdHQ9cPqL4Obc=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 287, + "top": 423, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -0.7853981633974483, + "distance": 40, + "hostEdge": { + "$ref": "AAAAAAFdHQ9cP6L6Aeo=" + }, + "edgePosition": 0, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ9cQqMDqB8=", + "_parent": { + "$ref": "AAAAAAFdHQ9cP6L6Aeo=" + }, + "model": { + "$ref": "AAAAAAFdHQ9cPqL4Obc=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 310, + "top": 457, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 0.5235987755982988, + "distance": 25, + "hostEdge": { + "$ref": "AAAAAAFdHQ9cP6L6Aeo=" + }, + "edgePosition": 0, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "UMLQualifierCompartmentView", + "_id": "AAAAAAFdHQ9cQqMEVYQ=", + "_parent": { + "$ref": "AAAAAAFdHQ9cP6L6Aeo=" + }, + "model": { + "$ref": "AAAAAAFdHQ9cPqL3JSg=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLQualifierCompartmentView", + "_id": "AAAAAAFdHQ9cQ6MFMeQ=", + "_parent": { + "$ref": "AAAAAAFdHQ9cP6L6Aeo=" + }, + "model": { + "$ref": "AAAAAAFdHQ9cPqL4Obc=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "head": { + "$ref": "AAAAAAFdHQ882aKZU8U=" + }, + "tail": { + "$ref": "AAAAAAFdGAKakqRiXVU=" + }, + "lineStyle": 1, + "points": "170:515;325:443", + "stereotypeDisplay": "label", + "showVisibility": true, + "showProperty": true, + "nameLabel": { + "$ref": "AAAAAAFdHQ9cP6L7zvs=" + }, + "stereotypeLabel": { + "$ref": "AAAAAAFdHQ9cQaL8CqM=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdHQ9cQqL9dnk=" + }, + "showMultiplicity": true, + "showType": true, + "tailRoleNameLabel": { + "$ref": "AAAAAAFdHQ9cQqL+ddA=" + }, + "tailPropertyLabel": { + "$ref": "AAAAAAFdHQ9cQqL/dNg=" + }, + "tailMultiplicityLabel": { + "$ref": "AAAAAAFdHQ9cQqMATrE=" + }, + "headRoleNameLabel": { + "$ref": "AAAAAAFdHQ9cQqMBCKU=" + }, + "headPropertyLabel": { + "$ref": "AAAAAAFdHQ9cQqMCH3Y=" + }, + "headMultiplicityLabel": { + "$ref": "AAAAAAFdHQ9cQqMDqB8=" + }, + "tailQualifiersCompartment": { + "$ref": "AAAAAAFdHQ9cQqMEVYQ=" + }, + "headQualifiersCompartment": { + "$ref": "AAAAAAFdHQ9cQ6MFMeQ=" + } + }, + { + "_type": "UMLExtendView", + "_id": "AAAAAAFdHQ+6bqQX4zM=", + "_parent": { + "$ref": "AAAAAAFdF8yd/5z3Wwc=" + }, + "model": { + "$ref": "AAAAAAFdHQ+6bqQVrTI=" + }, + "subViews": [ + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ+6b6QYXyk=", + "_parent": { + "$ref": "AAAAAAFdHQ+6bqQX4zM=" + }, + "model": { + "$ref": "AAAAAAFdHQ+6bqQVrTI=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 440, + "top": 453, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdHQ+6bqQX4zM=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ+6b6QZrOI=", + "_parent": { + "$ref": "AAAAAAFdHQ+6bqQX4zM=" + }, + "model": { + "$ref": "AAAAAAFdHQ+6bqQVrTI=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 408, + "top": 448, + "width": 53, + "height": 13, + "autoResize": false, + "alpha": 0.9596145313479303, + "distance": 13.45362404707371, + "hostEdge": { + "$ref": "AAAAAAFdHQ+6bqQX4zM=" + }, + "edgePosition": 1, + "underline": false, + "text": "«extend»", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ+6b6QaSio=", + "_parent": { + "$ref": "AAAAAAFdHQ+6bqQX4zM=" + }, + "model": { + "$ref": "AAAAAAFdHQ+6bqQVrTI=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 447, + "top": 424, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdHQ+6bqQX4zM=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "head": { + "$ref": "AAAAAAFdHQ882aKZU8U=" + }, + "tail": { + "$ref": "AAAAAAFdGAY0uaVJfPE=" + }, + "lineStyle": 1, + "points": "471:452;418:439", + "stereotypeDisplay": "label", + "showVisibility": true, + "showProperty": true, + "nameLabel": { + "$ref": "AAAAAAFdHQ+6b6QYXyk=" + }, + "stereotypeLabel": { + "$ref": "AAAAAAFdHQ+6b6QZrOI=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdHQ+6b6QaSio=" + } + }, + { + "_type": "UMLAssociationView", + "_id": "AAAAAAFdHQ/nDaSMkME=", + "_parent": { + "$ref": "AAAAAAFdF8yd/5z3Wwc=" + }, + "model": { + "$ref": "AAAAAAFdHQ/nC6SIpV8=" + }, + "subViews": [ + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ/nDaSNdP4=", + "_parent": { + "$ref": "AAAAAAFdHQ/nDaSMkME=" + }, + "model": { + "$ref": "AAAAAAFdHQ/nC6SIpV8=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 218, + "top": 517, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdHQ/nDaSMkME=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ/nDaSO7po=", + "_parent": { + "$ref": "AAAAAAFdHQ/nDaSMkME=" + }, + "model": { + "$ref": "AAAAAAFdHQ/nC6SIpV8=" + }, + "visible": null, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 220, + "top": 502, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdHQ/nDaSMkME=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ/nDqSPPvg=", + "_parent": { + "$ref": "AAAAAAFdHQ/nDaSMkME=" + }, + "model": { + "$ref": "AAAAAAFdHQ/nC6SIpV8=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 213, + "top": 546, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdHQ/nDaSMkME=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ/nDqSQ5n8=", + "_parent": { + "$ref": "AAAAAAFdHQ/nDaSMkME=" + }, + "model": { + "$ref": "AAAAAAFdHQ/nC6SJEfc=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 197, + "top": 514, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 0.5235987755982988, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdHQ/nDaSMkME=" + }, + "edgePosition": 2, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ/nDqSRoK0=", + "_parent": { + "$ref": "AAAAAAFdHQ/nDaSMkME=" + }, + "model": { + "$ref": "AAAAAAFdHQ/nC6SJEfc=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 202, + "top": 501, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 0.7853981633974483, + "distance": 40, + "hostEdge": { + "$ref": "AAAAAAFdHQ/nDaSMkME=" + }, + "edgePosition": 2, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ/nDqSSHNE=", + "_parent": { + "$ref": "AAAAAAFdHQ/nDaSMkME=" + }, + "model": { + "$ref": "AAAAAAFdHQ/nC6SJEfc=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 189, + "top": 540, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -0.5235987755982988, + "distance": 25, + "hostEdge": { + "$ref": "AAAAAAFdHQ/nDaSMkME=" + }, + "edgePosition": 2, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ/nDqSTDv4=", + "_parent": { + "$ref": "AAAAAAFdHQ/nDaSMkME=" + }, + "model": { + "$ref": "AAAAAAFdHQ/nC6SKfbM=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 239, + "top": 520, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -0.5235987755982988, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdHQ/nDaSMkME=" + }, + "edgePosition": 0, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ/nDqSUKEc=", + "_parent": { + "$ref": "AAAAAAFdHQ/nDaSMkME=" + }, + "model": { + "$ref": "AAAAAAFdHQ/nC6SKfbM=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 239, + "top": 506, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -0.7853981633974483, + "distance": 40, + "hostEdge": { + "$ref": "AAAAAAFdHQ/nDaSMkME=" + }, + "edgePosition": 0, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQ/nDqSV+BU=", + "_parent": { + "$ref": "AAAAAAFdHQ/nDaSMkME=" + }, + "model": { + "$ref": "AAAAAAFdHQ/nC6SKfbM=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 239, + "top": 548, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 0.5235987755982988, + "distance": 25, + "hostEdge": { + "$ref": "AAAAAAFdHQ/nDaSMkME=" + }, + "edgePosition": 0, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "UMLQualifierCompartmentView", + "_id": "AAAAAAFdHQ/nDqSW3i8=", + "_parent": { + "$ref": "AAAAAAFdHQ/nDaSMkME=" + }, + "model": { + "$ref": "AAAAAAFdHQ/nC6SJEfc=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLQualifierCompartmentView", + "_id": "AAAAAAFdHQ/nDqSXffo=", + "_parent": { + "$ref": "AAAAAAFdHQ/nDaSMkME=" + }, + "model": { + "$ref": "AAAAAAFdHQ/nC6SKfbM=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "head": { + "$ref": "AAAAAAFdGAW4LqTsTLE=" + }, + "tail": { + "$ref": "AAAAAAFdGAKakqRiXVU=" + }, + "lineStyle": 1, + "points": "170:531;263:545", + "stereotypeDisplay": "label", + "showVisibility": true, + "showProperty": true, + "nameLabel": { + "$ref": "AAAAAAFdHQ/nDaSNdP4=" + }, + "stereotypeLabel": { + "$ref": "AAAAAAFdHQ/nDaSO7po=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdHQ/nDqSPPvg=" + }, + "showMultiplicity": true, + "showType": true, + "tailRoleNameLabel": { + "$ref": "AAAAAAFdHQ/nDqSQ5n8=" + }, + "tailPropertyLabel": { + "$ref": "AAAAAAFdHQ/nDqSRoK0=" + }, + "tailMultiplicityLabel": { + "$ref": "AAAAAAFdHQ/nDqSSHNE=" + }, + "headRoleNameLabel": { + "$ref": "AAAAAAFdHQ/nDqSTDv4=" + }, + "headPropertyLabel": { + "$ref": "AAAAAAFdHQ/nDqSUKEc=" + }, + "headMultiplicityLabel": { + "$ref": "AAAAAAFdHQ/nDqSV+BU=" + }, + "tailQualifiersCompartment": { + "$ref": "AAAAAAFdHQ/nDqSW3i8=" + }, + "headQualifiersCompartment": { + "$ref": "AAAAAAFdHQ/nDqSXffo=" + } + }, + { + "_type": "UMLUseCaseView", + "_id": "AAAAAAFdHQ/+ZqTrAgU=", + "_parent": { + "$ref": "AAAAAAFdF8yd/5z3Wwc=" + }, + "model": { + "$ref": "AAAAAAFdHQ/+ZqTpmg8=" + }, + "subViews": [ + { + "_type": "UMLNameCompartmentView", + "_id": "AAAAAAFdHQ/+ZqTsUt0=", + "_parent": { + "$ref": "AAAAAAFdHQ/+ZqTrAgU=" + }, + "model": { + "$ref": "AAAAAAFdHQ/+ZqTpmg8=" + }, + "subViews": [ + { + "_type": "LabelView", + "_id": "AAAAAAFdHQ/+Z6TtsU0=", + "_parent": { + "$ref": "AAAAAAFdHQ/+ZqTsUt0=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -32, + "top": -16, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdHQ/+Z6TuoEc=", + "_parent": { + "$ref": "AAAAAAFdHQ/+ZqTsUt0=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;1", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 283.5, + "top": 619.5, + "width": 59, + "height": 13, + "autoResize": false, + "underline": false, + "text": "注册", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdHQ/+Z6TvnVY=", + "_parent": { + "$ref": "AAAAAAFdHQ/+ZqTsUt0=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -32, + "top": -16, + "width": 65, + "height": 13, + "autoResize": false, + "underline": false, + "text": "(from UML)", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdHQ/+Z6TwpEY=", + "_parent": { + "$ref": "AAAAAAFdHQ/+ZqTsUt0=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -32, + "top": -16, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 1, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 278.5, + "top": 612.5, + "width": 69, + "height": 25, + "autoResize": false, + "stereotypeLabel": { + "$ref": "AAAAAAFdHQ/+Z6TtsU0=" + }, + "nameLabel": { + "$ref": "AAAAAAFdHQ/+Z6TuoEc=" + }, + "namespaceLabel": { + "$ref": "AAAAAAFdHQ/+Z6TvnVY=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdHQ/+Z6TwpEY=" + } + }, + { + "_type": "UMLAttributeCompartmentView", + "_id": "AAAAAAFdHQ/+Z6Tx1GQ=", + "_parent": { + "$ref": "AAAAAAFdHQ/+ZqTrAgU=" + }, + "model": { + "$ref": "AAAAAAFdHQ/+ZqTpmg8=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -16, + "top": -8, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLOperationCompartmentView", + "_id": "AAAAAAFdHQ/+aKTyY7E=", + "_parent": { + "$ref": "AAAAAAFdHQ/+ZqTrAgU=" + }, + "model": { + "$ref": "AAAAAAFdHQ/+ZqTpmg8=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -16, + "top": -8, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLReceptionCompartmentView", + "_id": "AAAAAAFdHQ/+aKTzGEk=", + "_parent": { + "$ref": "AAAAAAFdHQ/+ZqTrAgU=" + }, + "model": { + "$ref": "AAAAAAFdHQ/+ZqTpmg8=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -16, + "top": -8, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLTemplateParameterCompartmentView", + "_id": "AAAAAAFdHQ/+aKT0jnU=", + "_parent": { + "$ref": "AAAAAAFdHQ/+ZqTrAgU=" + }, + "model": { + "$ref": "AAAAAAFdHQ/+ZqTpmg8=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -16, + "top": -8, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLExtensionPointCompartmentView", + "_id": "AAAAAAFdHQ/+aKT1dBo=", + "_parent": { + "$ref": "AAAAAAFdHQ/+ZqTrAgU=" + }, + "model": { + "$ref": "AAAAAAFdHQ/+ZqTpmg8=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -16, + "top": -8, + "width": 10, + "height": 10, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": true, + "containerExtending": false, + "left": 264, + "top": 608, + "width": 98, + "height": 35, + "autoResize": false, + "stereotypeDisplay": "label", + "showVisibility": true, + "showNamespace": false, + "showProperty": true, + "showType": true, + "nameCompartment": { + "$ref": "AAAAAAFdHQ/+ZqTsUt0=" + }, + "wordWrap": false, + "suppressAttributes": true, + "suppressOperations": true, + "suppressReceptions": true, + "showMultiplicity": true, + "showOperationSignature": true, + "attributeCompartment": { + "$ref": "AAAAAAFdHQ/+Z6Tx1GQ=" + }, + "operationCompartment": { + "$ref": "AAAAAAFdHQ/+aKTyY7E=" + }, + "receptionCompartment": { + "$ref": "AAAAAAFdHQ/+aKTzGEk=" + }, + "templateParameterCompartment": { + "$ref": "AAAAAAFdHQ/+aKT0jnU=" + }, + "extensionPointCompartment": { + "$ref": "AAAAAAFdHQ/+aKT1dBo=" + } + }, + { + "_type": "UMLExtendView", + "_id": "AAAAAAFdHRAkKaVi4M8=", + "_parent": { + "$ref": "AAAAAAFdF8yd/5z3Wwc=" + }, + "model": { + "$ref": "AAAAAAFdHRAkKaVg3zE=" + }, + "subViews": [ + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHRAkKaVjtmc=", + "_parent": { + "$ref": "AAAAAAFdHRAkKaVi4M8=" + }, + "model": { + "$ref": "AAAAAAFdHRAkKaVg3zE=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 297, + "top": 582, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdHRAkKaVi4M8=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHRAkKqVk7LU=", + "_parent": { + "$ref": "AAAAAAFdHRAkKaVi4M8=" + }, + "model": { + "$ref": "AAAAAAFdHRAkKaVg3zE=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 256, + "top": 582, + "width": 53, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdHRAkKaVi4M8=" + }, + "edgePosition": 1, + "underline": false, + "text": "«extend»", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHRAkKqVlFnA=", + "_parent": { + "$ref": "AAAAAAFdHRAkKaVi4M8=" + }, + "model": { + "$ref": "AAAAAAFdHRAkKaVg3zE=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 326, + "top": 583, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdHRAkKaVi4M8=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "head": { + "$ref": "AAAAAAFdGAW4LqTsTLE=" + }, + "tail": { + "$ref": "AAAAAAFdHQ/+ZqTrAgU=" + }, + "lineStyle": 1, + "points": "312:607;312:571", + "stereotypeDisplay": "label", + "showVisibility": true, + "showProperty": true, + "nameLabel": { + "$ref": "AAAAAAFdHRAkKaVjtmc=" + }, + "stereotypeLabel": { + "$ref": "AAAAAAFdHRAkKqVk7LU=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdHRAkKqVlFnA=" + } + }, + { + "_type": "UMLAssociationView", + "_id": "AAAAAAFdHRA1LqWixAs=", + "_parent": { + "$ref": "AAAAAAFdF8yd/5z3Wwc=" + }, + "model": { + "$ref": "AAAAAAFdHRA1LqWeYgw=" + }, + "subViews": [ + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHRA1L6WjkHo=", + "_parent": { + "$ref": "AAAAAAFdHRA1LqWixAs=" + }, + "model": { + "$ref": "AAAAAAFdHRA1LqWeYgw=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 232, + "top": 555, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdHRA1LqWixAs=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHRA1L6WkyuM=", + "_parent": { + "$ref": "AAAAAAFdHRA1LqWixAs=" + }, + "model": { + "$ref": "AAAAAAFdHRA1LqWeYgw=" + }, + "visible": null, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 240, + "top": 542, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdHRA1LqWixAs=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHRA1L6Wl/Us=", + "_parent": { + "$ref": "AAAAAAFdHRA1LqWixAs=" + }, + "model": { + "$ref": "AAAAAAFdHRA1LqWeYgw=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 217, + "top": 580, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdHRA1LqWixAs=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHRA1L6Wm/vw=", + "_parent": { + "$ref": "AAAAAAFdHRA1LqWixAs=" + }, + "model": { + "$ref": "AAAAAAFdHRA1LqWfgCc=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 199, + "top": 536, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 0.5235987755982988, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdHRA1LqWixAs=" + }, + "edgePosition": 2, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHRA1L6WnyBs=", + "_parent": { + "$ref": "AAAAAAFdHRA1LqWixAs=" + }, + "model": { + "$ref": "AAAAAAFdHRA1LqWfgCc=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 208, + "top": 525, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 0.7853981633974483, + "distance": 40, + "hostEdge": { + "$ref": "AAAAAAFdHRA1LqWixAs=" + }, + "edgePosition": 2, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHRA1L6WollM=", + "_parent": { + "$ref": "AAAAAAFdHRA1LqWixAs=" + }, + "model": { + "$ref": "AAAAAAFdHRA1LqWfgCc=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 182, + "top": 557, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -0.5235987755982988, + "distance": 25, + "hostEdge": { + "$ref": "AAAAAAFdHRA1LqWixAs=" + }, + "edgePosition": 2, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHRA1L6WpMj4=", + "_parent": { + "$ref": "AAAAAAFdHRA1LqWixAs=" + }, + "model": { + "$ref": "AAAAAAFdHRA1LqWgex0=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 266, + "top": 574, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -0.5235987755982988, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdHRA1LqWixAs=" + }, + "edgePosition": 0, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHRA1L6WqZWg=", + "_parent": { + "$ref": "AAAAAAFdHRA1LqWixAs=" + }, + "model": { + "$ref": "AAAAAAFdHRA1LqWgex0=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 270, + "top": 562, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -0.7853981633974483, + "distance": 40, + "hostEdge": { + "$ref": "AAAAAAFdHRA1LqWixAs=" + }, + "edgePosition": 0, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHRA1L6WrUmo=", + "_parent": { + "$ref": "AAAAAAFdHRA1LqWixAs=" + }, + "model": { + "$ref": "AAAAAAFdHRA1LqWgex0=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 256, + "top": 600, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 0.5235987755982988, + "distance": 25, + "hostEdge": { + "$ref": "AAAAAAFdHRA1LqWixAs=" + }, + "edgePosition": 0, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "UMLQualifierCompartmentView", + "_id": "AAAAAAFdHRA1L6WsvHA=", + "_parent": { + "$ref": "AAAAAAFdHRA1LqWixAs=" + }, + "model": { + "$ref": "AAAAAAFdHRA1LqWfgCc=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + }, + { + "_type": "UMLQualifierCompartmentView", + "_id": "AAAAAAFdHRA1L6WtjWo=", + "_parent": { + "$ref": "AAAAAAFdHRA1LqWixAs=" + }, + "model": { + "$ref": "AAAAAAFdHRA1LqWgex0=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 0, + "top": 0, + "width": 10, + "height": 10, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "head": { + "$ref": "AAAAAAFdHQ/+ZqTrAgU=" + }, + "tail": { + "$ref": "AAAAAAFdGAKakqRiXVU=" + }, + "lineStyle": 1, + "points": "170:542;281:607", + "stereotypeDisplay": "label", + "showVisibility": true, + "showProperty": true, + "nameLabel": { + "$ref": "AAAAAAFdHRA1L6WjkHo=" + }, + "stereotypeLabel": { + "$ref": "AAAAAAFdHRA1L6WkyuM=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdHRA1L6Wl/Us=" + }, + "showMultiplicity": true, + "showType": true, + "tailRoleNameLabel": { + "$ref": "AAAAAAFdHRA1L6Wm/vw=" + }, + "tailPropertyLabel": { + "$ref": "AAAAAAFdHRA1L6WnyBs=" + }, + "tailMultiplicityLabel": { + "$ref": "AAAAAAFdHRA1L6WollM=" + }, + "headRoleNameLabel": { + "$ref": "AAAAAAFdHRA1L6WpMj4=" + }, + "headPropertyLabel": { + "$ref": "AAAAAAFdHRA1L6WqZWg=" + }, + "headMultiplicityLabel": { + "$ref": "AAAAAAFdHRA1L6WrUmo=" + }, + "tailQualifiersCompartment": { + "$ref": "AAAAAAFdHRA1L6WsvHA=" + }, + "headQualifiersCompartment": { + "$ref": "AAAAAAFdHRA1L6WtjWo=" + } + }, + { + "_type": "UMLIncludeView", + "_id": "AAAAAAFdHRBbZKYcUQM=", + "_parent": { + "$ref": "AAAAAAFdF8yd/5z3Wwc=" + }, + "model": { + "$ref": "AAAAAAFdHRBbZKYaDv0=" + }, + "subViews": [ + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHRBbZaYdj30=", + "_parent": { + "$ref": "AAAAAAFdHRBbZKYcUQM=" + }, + "model": { + "$ref": "AAAAAAFdHRBbZKYaDv0=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 421, + "top": 516, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdHRBbZKYcUQM=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHRBbZaYeH/M=", + "_parent": { + "$ref": "AAAAAAFdHRBbZKYcUQM=" + }, + "model": { + "$ref": "AAAAAAFdHRBbZKYaDv0=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 400, + "top": 530, + "width": 55, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 30, + "hostEdge": { + "$ref": "AAAAAAFdHRBbZKYcUQM=" + }, + "edgePosition": 1, + "underline": false, + "text": "«include»", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHRBbZaYfqBU=", + "_parent": { + "$ref": "AAAAAAFdHRBbZKYcUQM=" + }, + "model": { + "$ref": "AAAAAAFdHRBbZKYaDv0=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 410, + "top": 489, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -1.5707963267948966, + "distance": 15, + "hostEdge": { + "$ref": "AAAAAAFdHRBbZKYcUQM=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "head": { + "$ref": "AAAAAAFdGAW4LqTsTLE=" + }, + "tail": { + "$ref": "AAAAAAFdGAY0uaVJfPE=" + }, + "lineStyle": 1, + "points": "477:483;355:535", + "stereotypeDisplay": "label", + "showVisibility": true, + "showProperty": true, + "nameLabel": { + "$ref": "AAAAAAFdHRBbZaYdj30=" + }, + "stereotypeLabel": { + "$ref": "AAAAAAFdHRBbZaYeH/M=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdHRBbZaYfqBU=" + } + } + ] + }, + { + "_type": "UMLClass", + "_id": "AAAAAAFdF9Jh5Z1ciZA=", + "_parent": { + "$ref": "AAAAAAFdF8bUGpzmKj4=" + }, + "name": "Player", + "ownedElements": [ + { + "_type": "UMLAssociation", + "_id": "AAAAAAFdF9dc2J3pDD0=", + "_parent": { + "$ref": "AAAAAAFdF9Jh5Z1ciZA=" + }, + "end1": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdF9dc2J3qoKU=", + "_parent": { + "$ref": "AAAAAAFdF9dc2J3pDD0=" + }, + "reference": { + "$ref": "AAAAAAFdF9Jh5Z1ciZA=" + }, + "visibility": "public", + "navigable": false, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "end2": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdF9dc2Z3rpO4=", + "_parent": { + "$ref": "AAAAAAFdF9dc2J3pDD0=" + }, + "reference": { + "$ref": "AAAAAAFdF9NBMZ2Jv50=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "visibility": "public", + "isDerived": false + }, + { + "_type": "UMLAssociation", + "_id": "AAAAAAFdG6VR1p1Gsno=", + "_parent": { + "$ref": "AAAAAAFdF9Jh5Z1ciZA=" + }, + "end1": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdG6VR1p1HuPE=", + "_parent": { + "$ref": "AAAAAAFdG6VR1p1Gsno=" + }, + "reference": { + "$ref": "AAAAAAFdF9Jh5Z1ciZA=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "end2": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdG6VR1p1IHBQ=", + "_parent": { + "$ref": "AAAAAAFdG6VR1p1Gsno=" + }, + "reference": { + "$ref": "AAAAAAFdF9NBMZ2Jv50=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "visibility": "public", + "isDerived": false + } + ], + "visibility": "public", + "isAbstract": false, + "isFinalSpecialization": false, + "isLeaf": false, + "isActive": false + }, + { + "_type": "UMLClass", + "_id": "AAAAAAFdF9NBMZ2Jv50=", + "_parent": { + "$ref": "AAAAAAFdF8bUGpzmKj4=" + }, + "name": "DiceGame", + "ownedElements": [ + { + "_type": "UMLAssociation", + "_id": "AAAAAAFdF99KOaCQNwo=", + "_parent": { + "$ref": "AAAAAAFdF9NBMZ2Jv50=" + }, + "end1": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdF99KOaCRrPU=", + "_parent": { + "$ref": "AAAAAAFdF99KOaCQNwo=" + }, + "reference": { + "$ref": "AAAAAAFdF9NBMZ2Jv50=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "end2": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdF99KOaCSiy0=", + "_parent": { + "$ref": "AAAAAAFdF99KOaCQNwo=" + }, + "reference": { + "$ref": "AAAAAAFdF9RF6Z25s+k=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "composite", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "visibility": "public", + "isDerived": false + }, + { + "_type": "UMLAssociation", + "_id": "AAAAAAFdG6MH7Zmtypw=", + "_parent": { + "$ref": "AAAAAAFdF9NBMZ2Jv50=" + }, + "end1": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdG6MH7ZmuDN4=", + "_parent": { + "$ref": "AAAAAAFdG6MH7Zmtypw=" + }, + "reference": { + "$ref": "AAAAAAFdF9NBMZ2Jv50=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "end2": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdG6MH7Zmvqpw=", + "_parent": { + "$ref": "AAAAAAFdG6MH7Zmtypw=" + }, + "reference": { + "$ref": "AAAAAAFdF9RF6Z25s+k=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "composite", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "visibility": "public", + "isDerived": false + }, + { + "_type": "UMLAssociation", + "_id": "AAAAAAFdG6TzIJwX5cs=", + "_parent": { + "$ref": "AAAAAAFdF9NBMZ2Jv50=" + }, + "end1": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdG6TzIJwYZJ8=", + "_parent": { + "$ref": "AAAAAAFdG6TzIJwX5cs=" + }, + "reference": { + "$ref": "AAAAAAFdF9NBMZ2Jv50=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "end2": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdG6TzIJwZeVE=", + "_parent": { + "$ref": "AAAAAAFdG6TzIJwX5cs=" + }, + "reference": { + "$ref": "AAAAAAFdG6RIwpshRVw=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "visibility": "public", + "isDerived": false + } + ], + "visibility": "public", + "operations": [ + { + "_type": "UMLOperation", + "_id": "AAAAAAFdF9tkT58TEw0=", + "_parent": { + "$ref": "AAAAAAFdF9NBMZ2Jv50=" + }, + "name": "play", + "visibility": "public", + "isStatic": false, + "isLeaf": false, + "concurrency": "sequential", + "isQuery": false, + "isAbstract": false + } + ], + "isAbstract": false, + "isFinalSpecialization": false, + "isLeaf": false, + "isActive": false + }, + { + "_type": "UMLClass", + "_id": "AAAAAAFdF9RF6Z25s+k=", + "_parent": { + "$ref": "AAAAAAFdF8bUGpzmKj4=" + }, + "name": "Dice", + "ownedElements": [ + { + "_type": "UMLAssociation", + "_id": "AAAAAAFdG6Mw9ZoppUM=", + "_parent": { + "$ref": "AAAAAAFdF9RF6Z25s+k=" + }, + "end1": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdG6Mw9ZoqSLc=", + "_parent": { + "$ref": "AAAAAAFdG6Mw9ZoppUM=" + }, + "reference": { + "$ref": "AAAAAAFdF9RF6Z25s+k=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "end2": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdG6Mw9porfGs=", + "_parent": { + "$ref": "AAAAAAFdG6Mw9ZoppUM=" + }, + "reference": { + "$ref": "AAAAAAFdF9NBMZ2Jv50=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "composite", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "visibility": "public", + "isDerived": false + }, + { + "_type": "UMLAssociation", + "_id": "AAAAAAFdG6S2iZusc0s=", + "_parent": { + "$ref": "AAAAAAFdF9RF6Z25s+k=" + }, + "end1": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdG6S2iZutrMs=", + "_parent": { + "$ref": "AAAAAAFdG6S2iZusc0s=" + }, + "reference": { + "$ref": "AAAAAAFdF9RF6Z25s+k=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "end2": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdG6S2iZuu5hA=", + "_parent": { + "$ref": "AAAAAAFdG6S2iZusc0s=" + }, + "reference": { + "$ref": "AAAAAAFdF9NBMZ2Jv50=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "shared", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "visibility": "public", + "isDerived": false + } + ], + "visibility": "public", + "operations": [ + { + "_type": "UMLOperation", + "_id": "AAAAAAFdF9yOrp8l+p4=", + "_parent": { + "$ref": "AAAAAAFdF9RF6Z25s+k=" + }, + "name": "roll", + "visibility": "public", + "isStatic": false, + "isLeaf": false, + "concurrency": "sequential", + "isQuery": false, + "isAbstract": false + } + ], + "isAbstract": false, + "isFinalSpecialization": false, + "isLeaf": false, + "isActive": false + }, + { + "_type": "UMLActor", + "_id": "AAAAAAFdGAKakKRgInE=", + "_parent": { + "$ref": "AAAAAAFdF8bUGpzmKj4=" + }, + "name": "用户", + "ownedElements": [ + { + "_type": "UMLAssociation", + "_id": "AAAAAAFdGBfGHaYFPwU=", + "_parent": { + "$ref": "AAAAAAFdGAKakKRgInE=" + }, + "end1": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdGBfGHaYGRkw=", + "_parent": { + "$ref": "AAAAAAFdGBfGHaYFPwU=" + }, + "reference": { + "$ref": "AAAAAAFdGAKakKRgInE=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "end2": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdGBfGHaYHyF4=", + "_parent": { + "$ref": "AAAAAAFdGBfGHaYFPwU=" + }, + "reference": { + "$ref": "AAAAAAFdGAXoAqUZa/0=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "visibility": "public", + "isDerived": false + }, + { + "_type": "UMLAssociation", + "_id": "AAAAAAFdGBfedKZIprQ=", + "_parent": { + "$ref": "AAAAAAFdGAKakKRgInE=" + }, + "end1": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdGBfedaZJO7I=", + "_parent": { + "$ref": "AAAAAAFdGBfedKZIprQ=" + }, + "reference": { + "$ref": "AAAAAAFdGAKakKRgInE=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "end2": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdGBfedaZKKu0=", + "_parent": { + "$ref": "AAAAAAFdGBfedKZIprQ=" + }, + "reference": { + "$ref": "AAAAAAFdGAY0uKVHc28=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "visibility": "public", + "isDerived": false + }, + { + "_type": "UMLAssociation", + "_id": "AAAAAAFdGBf23qaao/Y=", + "_parent": { + "$ref": "AAAAAAFdGAKakKRgInE=" + }, + "end1": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdGBf23qabaUY=", + "_parent": { + "$ref": "AAAAAAFdGBf23qaao/Y=" + }, + "reference": { + "$ref": "AAAAAAFdGAKakKRgInE=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "end2": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdGBf23qacez0=", + "_parent": { + "$ref": "AAAAAAFdGBf23qaao/Y=" + }, + "reference": { + "$ref": "AAAAAAFdGAVH16S6bA0=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "visibility": "public", + "isDerived": false + }, + { + "_type": "UMLAssociation", + "_id": "AAAAAAFdGBgGqabpFws=", + "_parent": { + "$ref": "AAAAAAFdGAKakKRgInE=" + }, + "end1": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdGBgGqabqC0k=", + "_parent": { + "$ref": "AAAAAAFdGBgGqabpFws=" + }, + "reference": { + "$ref": "AAAAAAFdGAKakKRgInE=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "end2": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdGBgGqabrjBY=", + "_parent": { + "$ref": "AAAAAAFdGBgGqabpFws=" + }, + "reference": { + "$ref": "AAAAAAFdGAO/iaSMYxI=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "visibility": "public", + "isDerived": false + }, + { + "_type": "UMLAssociation", + "_id": "AAAAAAFdHQ9cPqL2MKE=", + "_parent": { + "$ref": "AAAAAAFdGAKakKRgInE=" + }, + "end1": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdHQ9cPqL3JSg=", + "_parent": { + "$ref": "AAAAAAFdHQ9cPqL2MKE=" + }, + "reference": { + "$ref": "AAAAAAFdGAKakKRgInE=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "end2": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdHQ9cPqL4Obc=", + "_parent": { + "$ref": "AAAAAAFdHQ9cPqL2MKE=" + }, + "reference": { + "$ref": "AAAAAAFdHQ882KKXixg=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "visibility": "public", + "isDerived": false + }, + { + "_type": "UMLAssociation", + "_id": "AAAAAAFdHQ/nC6SIpV8=", + "_parent": { + "$ref": "AAAAAAFdGAKakKRgInE=" + }, + "end1": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdHQ/nC6SJEfc=", + "_parent": { + "$ref": "AAAAAAFdHQ/nC6SIpV8=" + }, + "reference": { + "$ref": "AAAAAAFdGAKakKRgInE=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "end2": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdHQ/nC6SKfbM=", + "_parent": { + "$ref": "AAAAAAFdHQ/nC6SIpV8=" + }, + "reference": { + "$ref": "AAAAAAFdGAW4LaTq8JA=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "visibility": "public", + "isDerived": false + }, + { + "_type": "UMLAssociation", + "_id": "AAAAAAFdHRA1LqWeYgw=", + "_parent": { + "$ref": "AAAAAAFdGAKakKRgInE=" + }, + "end1": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdHRA1LqWfgCc=", + "_parent": { + "$ref": "AAAAAAFdHRA1LqWeYgw=" + }, + "reference": { + "$ref": "AAAAAAFdGAKakKRgInE=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "end2": { + "_type": "UMLAssociationEnd", + "_id": "AAAAAAFdHRA1LqWgex0=", + "_parent": { + "$ref": "AAAAAAFdHRA1LqWeYgw=" + }, + "reference": { + "$ref": "AAAAAAFdHQ/+ZqTpmg8=" + }, + "visibility": "public", + "navigable": true, + "aggregation": "none", + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "isID": false + }, + "visibility": "public", + "isDerived": false + } + ], + "visibility": "public", + "isAbstract": false, + "isFinalSpecialization": false, + "isLeaf": false + }, + { + "_type": "UMLUseCase", + "_id": "AAAAAAFdGAO/iaSMYxI=", + "_parent": { + "$ref": "AAAAAAFdF8bUGpzmKj4=" + }, + "name": "搜索产品", + "visibility": "public", + "isAbstract": false, + "isFinalSpecialization": false, + "isLeaf": false + }, + { + "_type": "UMLUseCase", + "_id": "AAAAAAFdGAVH16S6bA0=", + "_parent": { + "$ref": "AAAAAAFdF8bUGpzmKj4=" + }, + "name": "查看产品细节", + "visibility": "public", + "isAbstract": false, + "isFinalSpecialization": false, + "isLeaf": false + }, + { + "_type": "UMLUseCase", + "_id": "AAAAAAFdGAW4LaTq8JA=", + "_parent": { + "$ref": "AAAAAAFdF8bUGpzmKj4=" + }, + "name": "登录", + "visibility": "public", + "isAbstract": false, + "isFinalSpecialization": false, + "isLeaf": false + }, + { + "_type": "UMLUseCase", + "_id": "AAAAAAFdGAXoAqUZa/0=", + "_parent": { + "$ref": "AAAAAAFdF8bUGpzmKj4=" + }, + "name": "加入购物车", + "ownedElements": [ + { + "_type": "UMLExtend", + "_id": "AAAAAAFdHQ7gj6Gn9wA=", + "_parent": { + "$ref": "AAAAAAFdGAXoAqUZa/0=" + }, + "source": { + "$ref": "AAAAAAFdGAXoAqUZa/0=" + }, + "target": { + "$ref": "AAAAAAFdGAO/iaSMYxI=" + }, + "visibility": "public" + }, + { + "_type": "UMLExtend", + "_id": "AAAAAAFdHQ8AdqIKyBQ=", + "_parent": { + "$ref": "AAAAAAFdGAXoAqUZa/0=" + }, + "source": { + "$ref": "AAAAAAFdGAXoAqUZa/0=" + }, + "target": { + "$ref": "AAAAAAFdHQ4fLZ+9HuM=" + }, + "visibility": "public" + } + ], + "visibility": "public", + "isAbstract": false, + "isFinalSpecialization": false, + "isLeaf": false + }, + { + "_type": "UMLUseCase", + "_id": "AAAAAAFdGAY0uKVHc28=", + "_parent": { + "$ref": "AAAAAAFdF8bUGpzmKj4=" + }, + "name": "下订单", + "ownedElements": [ + { + "_type": "UMLInclude", + "_id": "AAAAAAFdGBT5vaXucnQ=", + "_parent": { + "$ref": "AAAAAAFdGAY0uKVHc28=" + }, + "source": { + "$ref": "AAAAAAFdGAY0uKVHc28=" + }, + "target": { + "$ref": "AAAAAAFdGAW4LaTq8JA=" + }, + "visibility": "public" + }, + { + "_type": "UMLExtend", + "_id": "AAAAAAFdHQ+6bqQVrTI=", + "_parent": { + "$ref": "AAAAAAFdGAY0uKVHc28=" + }, + "source": { + "$ref": "AAAAAAFdGAY0uKVHc28=" + }, + "target": { + "$ref": "AAAAAAFdHQ882KKXixg=" + }, + "visibility": "public" + }, + { + "_type": "UMLInclude", + "_id": "AAAAAAFdHRBbZKYaDv0=", + "_parent": { + "$ref": "AAAAAAFdGAY0uKVHc28=" + }, + "source": { + "$ref": "AAAAAAFdGAY0uKVHc28=" + }, + "target": { + "$ref": "AAAAAAFdGAW4LaTq8JA=" + }, + "visibility": "public" + } + ], + "visibility": "public", + "isAbstract": false, + "isFinalSpecialization": false, + "isLeaf": false + }, + { + "_type": "UMLUseCase", + "_id": "AAAAAAFdGAfYTKV2bvY=", + "_parent": { + "$ref": "AAAAAAFdF8bUGpzmKj4=" + }, + "name": "产品", + "visibility": "public", + "isAbstract": false, + "isFinalSpecialization": false, + "isLeaf": false + }, + { + "_type": "UMLUseCaseSubject", + "_id": "AAAAAAFdGBPCQaWkzJE=", + "_parent": { + "$ref": "AAAAAAFdF8bUGpzmKj4=" + }, + "name": "UseCaseSubject1", + "visibility": "public" + }, + { + "_type": "UMLClass", + "_id": "AAAAAAFdG6RIwpshRVw=", + "_parent": { + "$ref": "AAAAAAFdF8bUGpzmKj4=" + }, + "name": "Display", + "visibility": "public", + "operations": [ + { + "_type": "UMLOperation", + "_id": "AAAAAAFdG6UEzJx4aDY=", + "_parent": { + "$ref": "AAAAAAFdG6RIwpshRVw=" + }, + "name": "showResult", + "visibility": "public", + "isStatic": false, + "isLeaf": false, + "concurrency": "sequential", + "isQuery": false, + "isAbstract": false + } + ], + "isAbstract": false, + "isFinalSpecialization": false, + "isLeaf": false, + "isActive": false + }, + { + "_type": "UMLUseCase", + "_id": "AAAAAAFdHQ4fLZ+9HuM=", + "_parent": { + "$ref": "AAAAAAFdF8bUGpzmKj4=" + }, + "name": "查看产品详情", + "ownedElements": [ + { + "_type": "UMLExtend", + "_id": "AAAAAAFdHQ57DaAopRI=", + "_parent": { + "$ref": "AAAAAAFdHQ4fLZ+9HuM=" + }, + "source": { + "$ref": "AAAAAAFdHQ4fLZ+9HuM=" + }, + "target": { + "$ref": "AAAAAAFdGAO/iaSMYxI=" + }, + "visibility": "public" + } + ], + "visibility": "public", + "isAbstract": false, + "isFinalSpecialization": false, + "isLeaf": false + }, + { + "_type": "UMLUseCase", + "_id": "AAAAAAFdHQ882KKXixg=", + "_parent": { + "$ref": "AAAAAAFdF8bUGpzmKj4=" + }, + "name": "显示购物车", + "visibility": "public", + "isAbstract": false, + "isFinalSpecialization": false, + "isLeaf": false + }, + { + "_type": "UMLUseCase", + "_id": "AAAAAAFdHQ/+ZqTpmg8=", + "_parent": { + "$ref": "AAAAAAFdF8bUGpzmKj4=" + }, + "name": "注册", + "ownedElements": [ + { + "_type": "UMLExtend", + "_id": "AAAAAAFdHRAkKaVg3zE=", + "_parent": { + "$ref": "AAAAAAFdHQ/+ZqTpmg8=" + }, + "source": { + "$ref": "AAAAAAFdHQ/+ZqTpmg8=" + }, + "target": { + "$ref": "AAAAAAFdGAW4LaTq8JA=" + }, + "visibility": "public" + } + ], + "visibility": "public", + "isAbstract": false, + "isFinalSpecialization": false, + "isLeaf": false + } + ], + "visibility": "public" + }, + { + "_type": "UMLCollaboration", + "_id": "AAAAAAFdF9ENuJ1Khbw=", + "_parent": { + "$ref": "AAAAAAFF+h6SjaM2Hec=" + }, + "name": "Collaboration", + "ownedElements": [ + { + "_type": "UMLInteraction", + "_id": "AAAAAAFdF9ENuJ1LFdg=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1Khbw=" + }, + "name": "Interaction", + "ownedElements": [ + { + "_type": "UMLSequenceDiagram", + "_id": "AAAAAAFdF9ENuJ1MVCI=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1LFdg=" + }, + "name": "掷骰子顺序图", + "visible": true, + "defaultDiagram": false, + "ownedViews": [ + { + "_type": "UMLFrameView", + "_id": "AAAAAAFdF9ENuJ1NVPk=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1MVCI=" + }, + "model": { + "$ref": "AAAAAAFdF9ENuJ1MVCI=" + }, + "subViews": [ + { + "_type": "LabelView", + "_id": "AAAAAAFdF9ENuZ1OWM4=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1NVPk=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 76, + "top": 10, + "width": 79, + "height": 13, + "autoResize": false, + "underline": false, + "text": "掷骰子顺序图", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdF9ENuZ1P378=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1NVPk=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;1", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 10, + "top": 10, + "width": 61, + "height": 13, + "autoResize": false, + "underline": false, + "text": "interaction", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 5, + "top": 5, + "width": 695, + "height": 595, + "autoResize": false, + "nameLabel": { + "$ref": "AAAAAAFdF9ENuZ1OWM4=" + }, + "frameTypeLabel": { + "$ref": "AAAAAAFdF9ENuZ1P378=" + } + }, + { + "_type": "UMLSeqLifelineView", + "_id": "AAAAAAFdF+OdeqGXCpA=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1MVCI=" + }, + "model": { + "$ref": "AAAAAAFdF+OdeqGWcbc=" + }, + "subViews": [ + { + "_type": "UMLNameCompartmentView", + "_id": "AAAAAAFdF+OdeqGYEEU=", + "_parent": { + "$ref": "AAAAAAFdF+OdeqGXCpA=" + }, + "model": { + "$ref": "AAAAAAFdF+OdeqGWcbc=" + }, + "subViews": [ + { + "_type": "LabelView", + "_id": "AAAAAAFdF+Ode6GZUBc=", + "_parent": { + "$ref": "AAAAAAFdF+OdeqGYEEU=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -160, + "top": 0, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdF+Ode6GavkA=", + "_parent": { + "$ref": "AAAAAAFdF+OdeqGYEEU=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;1", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 85, + "top": 47, + "width": 95, + "height": 13, + "autoResize": false, + "underline": false, + "text": "player: Player", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdF+Ode6Gb7JQ=", + "_parent": { + "$ref": "AAAAAAFdF+OdeqGYEEU=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -160, + "top": 0, + "width": 99, + "height": 13, + "autoResize": false, + "underline": false, + "text": "(from Interaction)", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdF+OdfKGc5R8=", + "_parent": { + "$ref": "AAAAAAFdF+OdeqGYEEU=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -160, + "top": 0, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 1, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 80, + "top": 40, + "width": 105, + "height": 40, + "autoResize": false, + "stereotypeLabel": { + "$ref": "AAAAAAFdF+Ode6GZUBc=" + }, + "nameLabel": { + "$ref": "AAAAAAFdF+Ode6GavkA=" + }, + "namespaceLabel": { + "$ref": "AAAAAAFdF+Ode6Gb7JQ=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdF+OdfKGc5R8=" + } + }, + { + "_type": "UMLLinePartView", + "_id": "AAAAAAFdF+OdfKGdq7U=", + "_parent": { + "$ref": "AAAAAAFdF+OdeqGXCpA=" + }, + "model": { + "$ref": "AAAAAAFdF+OdeqGWcbc=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 133, + "top": 80, + "width": 1, + "height": 271, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 80, + "top": 40, + "width": 105, + "height": 311, + "autoResize": false, + "stereotypeDisplay": "label", + "showVisibility": true, + "showNamespace": false, + "showProperty": true, + "showType": true, + "nameCompartment": { + "$ref": "AAAAAAFdF+OdeqGYEEU=" + }, + "wordWrap": false, + "linePart": { + "$ref": "AAAAAAFdF+OdfKGdq7U=" + } + }, + { + "_type": "UMLSeqLifelineView", + "_id": "AAAAAAFdF+RP86G5S4s=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1MVCI=" + }, + "model": { + "$ref": "AAAAAAFdF+RP86G4mVc=" + }, + "subViews": [ + { + "_type": "UMLNameCompartmentView", + "_id": "AAAAAAFdF+RP86G6V2w=", + "_parent": { + "$ref": "AAAAAAFdF+RP86G5S4s=" + }, + "model": { + "$ref": "AAAAAAFdF+RP86G4mVc=" + }, + "subViews": [ + { + "_type": "LabelView", + "_id": "AAAAAAFdF+RP86G7KPw=", + "_parent": { + "$ref": "AAAAAAFdF+RP86G6V2w=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -80, + "top": 0, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdF+RP9KG8g9w=", + "_parent": { + "$ref": "AAAAAAFdF+RP86G6V2w=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;1", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 205, + "top": 47, + "width": 143, + "height": 13, + "autoResize": false, + "underline": false, + "text": "diceGame: DiceGame", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdF+RP9KG9Bck=", + "_parent": { + "$ref": "AAAAAAFdF+RP86G6V2w=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -80, + "top": 0, + "width": 99, + "height": 13, + "autoResize": false, + "underline": false, + "text": "(from Interaction)", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdF+RP9KG+FO0=", + "_parent": { + "$ref": "AAAAAAFdF+RP86G6V2w=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -80, + "top": 0, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 1, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 200, + "top": 40, + "width": 153, + "height": 40, + "autoResize": false, + "stereotypeLabel": { + "$ref": "AAAAAAFdF+RP86G7KPw=" + }, + "nameLabel": { + "$ref": "AAAAAAFdF+RP9KG8g9w=" + }, + "namespaceLabel": { + "$ref": "AAAAAAFdF+RP9KG9Bck=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdF+RP9KG+FO0=" + } + }, + { + "_type": "UMLLinePartView", + "_id": "AAAAAAFdF+RP9KG/qmo=", + "_parent": { + "$ref": "AAAAAAFdF+RP86G5S4s=" + }, + "model": { + "$ref": "AAAAAAFdF+RP86G4mVc=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 277, + "top": 80, + "width": 1, + "height": 283, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 200, + "top": 40, + "width": 153, + "height": 323, + "autoResize": false, + "stereotypeDisplay": "label", + "showVisibility": true, + "showNamespace": false, + "showProperty": true, + "showType": true, + "nameCompartment": { + "$ref": "AAAAAAFdF+RP86G6V2w=" + }, + "wordWrap": false, + "linePart": { + "$ref": "AAAAAAFdF+RP9KG/qmo=" + } + }, + { + "_type": "UMLSeqLifelineView", + "_id": "AAAAAAFdF+UgqKHvECc=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1MVCI=" + }, + "model": { + "$ref": "AAAAAAFdF+Ugp6Huy74=" + }, + "subViews": [ + { + "_type": "UMLNameCompartmentView", + "_id": "AAAAAAFdF+UgqKHwKJY=", + "_parent": { + "$ref": "AAAAAAFdF+UgqKHvECc=" + }, + "model": { + "$ref": "AAAAAAFdF+Ugp6Huy74=" + }, + "subViews": [ + { + "_type": "LabelView", + "_id": "AAAAAAFdF+UgqaHx/1c=", + "_parent": { + "$ref": "AAAAAAFdF+UgqKHwKJY=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -96, + "top": 0, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdF+UgqaHy7Ec=", + "_parent": { + "$ref": "AAAAAAFdF+UgqKHwKJY=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;1", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 373, + "top": 47, + "width": 78, + "height": 13, + "autoResize": false, + "underline": false, + "text": "dice1: Dice", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdF+UgqaHzfxg=", + "_parent": { + "$ref": "AAAAAAFdF+UgqKHwKJY=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -96, + "top": 0, + "width": 99, + "height": 13, + "autoResize": false, + "underline": false, + "text": "(from Interaction)", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdF+UgqaH0Efk=", + "_parent": { + "$ref": "AAAAAAFdF+UgqKHwKJY=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -96, + "top": 0, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 1, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 368, + "top": 40, + "width": 88, + "height": 40, + "autoResize": false, + "stereotypeLabel": { + "$ref": "AAAAAAFdF+UgqaHx/1c=" + }, + "nameLabel": { + "$ref": "AAAAAAFdF+UgqaHy7Ec=" + }, + "namespaceLabel": { + "$ref": "AAAAAAFdF+UgqaHzfxg=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdF+UgqaH0Efk=" + } + }, + { + "_type": "UMLLinePartView", + "_id": "AAAAAAFdF+UgqaH1Ack=", + "_parent": { + "$ref": "AAAAAAFdF+UgqKHvECc=" + }, + "model": { + "$ref": "AAAAAAFdF+Ugp6Huy74=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 412, + "top": 80, + "width": 1, + "height": 209, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 368, + "top": 40, + "width": 88, + "height": 249, + "autoResize": false, + "stereotypeDisplay": "label", + "showVisibility": true, + "showNamespace": false, + "showProperty": true, + "showType": true, + "nameCompartment": { + "$ref": "AAAAAAFdF+UgqKHwKJY=" + }, + "wordWrap": false, + "linePart": { + "$ref": "AAAAAAFdF+UgqaH1Ack=" + } + }, + { + "_type": "UMLSeqMessageView", + "_id": "AAAAAAFdF+TkA6HYtTw=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1MVCI=" + }, + "model": { + "$ref": "AAAAAAFdF+TkA6HXVqw=" + }, + "subViews": [ + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdF+TkBKHZZ+Y=", + "_parent": { + "$ref": "AAAAAAFdF+TkA6HYtTw=" + }, + "model": { + "$ref": "AAAAAAFdF+TkA6HXVqw=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 162, + "top": 167, + "width": 79, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 10, + "hostEdge": { + "$ref": "AAAAAAFdF+TkA6HYtTw=" + }, + "edgePosition": 1, + "underline": false, + "text": "1 : play", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdF+TkBKHaWq4=", + "_parent": { + "$ref": "AAAAAAFdF+TkA6HYtTw=" + }, + "model": { + "$ref": "AAAAAAFdF+TkA6HXVqw=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 201, + "top": 152, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 25, + "hostEdge": { + "$ref": "AAAAAAFdF+TkA6HYtTw=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdF+TkBKHbuuY=", + "_parent": { + "$ref": "AAAAAAFdF+TkA6HYtTw=" + }, + "model": { + "$ref": "AAAAAAFdF+TkA6HXVqw=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 201, + "top": 187, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -1.5707963267948966, + "distance": 10, + "hostEdge": { + "$ref": "AAAAAAFdF+TkA6HYtTw=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "UMLActivationView", + "_id": "AAAAAAFdF+TkBKHctG4=", + "_parent": { + "$ref": "AAAAAAFdF+TkA6HYtTw=" + }, + "model": { + "$ref": "AAAAAAFdF+TkA6HXVqw=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 270, + "top": 183, + "width": 14, + "height": 154, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "head": { + "$ref": "AAAAAAFdF+RP9KG/qmo=" + }, + "tail": { + "$ref": "AAAAAAFdF+OdfKGdq7U=" + }, + "lineStyle": 0, + "points": "133:183;270:183", + "nameLabel": { + "$ref": "AAAAAAFdF+TkBKHZZ+Y=" + }, + "stereotypeLabel": { + "$ref": "AAAAAAFdF+TkBKHaWq4=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdF+TkBKHbuuY=" + }, + "activation": { + "$ref": "AAAAAAFdF+TkBKHctG4=" + }, + "showProperty": true, + "showType": true + }, + { + "_type": "UMLSeqMessageView", + "_id": "AAAAAAFdF/sfZqPnl+I=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1MVCI=" + }, + "model": { + "$ref": "AAAAAAFdF/sfZaPm+zc=" + }, + "subViews": [ + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdF/sfZqPogK0=", + "_parent": { + "$ref": "AAAAAAFdF/sfZqPnl+I=" + }, + "model": { + "$ref": "AAAAAAFdF/sfZaPm+zc=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 305, + "top": 178, + "width": 79, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 10, + "hostEdge": { + "$ref": "AAAAAAFdF/sfZqPnl+I=" + }, + "edgePosition": 1, + "underline": false, + "text": "2 : roll", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdF/sfZqPp5uY=", + "_parent": { + "$ref": "AAAAAAFdF/sfZqPnl+I=" + }, + "model": { + "$ref": "AAAAAAFdF/sfZaPm+zc=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 344, + "top": 163, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 25, + "hostEdge": { + "$ref": "AAAAAAFdF/sfZqPnl+I=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdF/sfZqPqawY=", + "_parent": { + "$ref": "AAAAAAFdF/sfZqPnl+I=" + }, + "model": { + "$ref": "AAAAAAFdF/sfZaPm+zc=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 344, + "top": 198, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -1.5707963267948966, + "distance": 10, + "hostEdge": { + "$ref": "AAAAAAFdF/sfZqPnl+I=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "UMLActivationView", + "_id": "AAAAAAFdF/sfZqPrd6c=", + "_parent": { + "$ref": "AAAAAAFdF/sfZqPnl+I=" + }, + "model": { + "$ref": "AAAAAAFdF/sfZaPm+zc=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 405, + "top": 194, + "width": 14, + "height": 29, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "head": { + "$ref": "AAAAAAFdF+UgqaH1Ack=" + }, + "tail": { + "$ref": "AAAAAAFdF+RP9KG/qmo=" + }, + "lineStyle": 0, + "points": "283:194;405:194", + "nameLabel": { + "$ref": "AAAAAAFdF/sfZqPogK0=" + }, + "stereotypeLabel": { + "$ref": "AAAAAAFdF/sfZqPp5uY=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdF/sfZqPqawY=" + }, + "activation": { + "$ref": "AAAAAAFdF/sfZqPrd6c=" + }, + "showProperty": true, + "showType": true + }, + { + "_type": "UMLSeqMessageView", + "_id": "AAAAAAFdHQp4LZ8Q7dM=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1MVCI=" + }, + "model": { + "$ref": "AAAAAAFdHQp4LZ8P0ZU=" + }, + "subViews": [ + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQp4LZ8R3GI=", + "_parent": { + "$ref": "AAAAAAFdHQp4LZ8Q7dM=" + }, + "model": { + "$ref": "AAAAAAFdHQp4LZ8P0ZU=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 357, + "top": 232, + "width": 79, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 10, + "hostEdge": { + "$ref": "AAAAAAFdHQp4LZ8Q7dM=" + }, + "edgePosition": 1, + "underline": false, + "text": "3 : roll", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQp4LZ8S8XE=", + "_parent": { + "$ref": "AAAAAAFdHQp4LZ8Q7dM=" + }, + "model": { + "$ref": "AAAAAAFdHQp4LZ8P0ZU=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 396, + "top": 217, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 25, + "hostEdge": { + "$ref": "AAAAAAFdHQp4LZ8Q7dM=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQp4LZ8TEEM=", + "_parent": { + "$ref": "AAAAAAFdHQp4LZ8Q7dM=" + }, + "model": { + "$ref": "AAAAAAFdHQp4LZ8P0ZU=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 396, + "top": 252, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -1.5707963267948966, + "distance": 10, + "hostEdge": { + "$ref": "AAAAAAFdHQp4LZ8Q7dM=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "UMLActivationView", + "_id": "AAAAAAFdHQp4LZ8UAbU=", + "_parent": { + "$ref": "AAAAAAFdHQp4LZ8Q7dM=" + }, + "model": { + "$ref": "AAAAAAFdHQp4LZ8P0ZU=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 509, + "top": 248, + "width": 14, + "height": 29, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "head": { + "$ref": "AAAAAAFdHQn7x57ralA=" + }, + "tail": { + "$ref": "AAAAAAFdF+RP9KG/qmo=" + }, + "lineStyle": 0, + "points": "283:248;509:248", + "nameLabel": { + "$ref": "AAAAAAFdHQp4LZ8R3GI=" + }, + "stereotypeLabel": { + "$ref": "AAAAAAFdHQp4LZ8S8XE=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdHQp4LZ8TEEM=" + }, + "activation": { + "$ref": "AAAAAAFdHQp4LZ8UAbU=" + }, + "showProperty": true, + "showType": true + }, + { + "_type": "UMLSeqLifelineView", + "_id": "AAAAAAFdHQn7xp7lBR4=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1MVCI=" + }, + "model": { + "$ref": "AAAAAAFdHQn7xp7kRhc=" + }, + "subViews": [ + { + "_type": "UMLNameCompartmentView", + "_id": "AAAAAAFdHQn7x57mVek=", + "_parent": { + "$ref": "AAAAAAFdHQn7xp7lBR4=" + }, + "model": { + "$ref": "AAAAAAFdHQn7xp7kRhc=" + }, + "subViews": [ + { + "_type": "LabelView", + "_id": "AAAAAAFdHQn7x57nLbY=", + "_parent": { + "$ref": "AAAAAAFdHQn7x57mVek=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -176, + "top": 0, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdHQn7x57o4+o=", + "_parent": { + "$ref": "AAAAAAFdHQn7x57mVek=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;1", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 477, + "top": 47, + "width": 78, + "height": 13, + "autoResize": false, + "underline": false, + "text": "dice2: Dice", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdHQn7x57pTmg=", + "_parent": { + "$ref": "AAAAAAFdHQn7x57mVek=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -176, + "top": 0, + "width": 99, + "height": 13, + "autoResize": false, + "underline": false, + "text": "(from Interaction)", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdHQn7x57qzPQ=", + "_parent": { + "$ref": "AAAAAAFdHQn7x57mVek=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -176, + "top": 0, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 1, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 472, + "top": 40, + "width": 88, + "height": 40, + "autoResize": false, + "stereotypeLabel": { + "$ref": "AAAAAAFdHQn7x57nLbY=" + }, + "nameLabel": { + "$ref": "AAAAAAFdHQn7x57o4+o=" + }, + "namespaceLabel": { + "$ref": "AAAAAAFdHQn7x57pTmg=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdHQn7x57qzPQ=" + } + }, + { + "_type": "UMLLinePartView", + "_id": "AAAAAAFdHQn7x57ralA=", + "_parent": { + "$ref": "AAAAAAFdHQn7xp7lBR4=" + }, + "model": { + "$ref": "AAAAAAFdHQn7xp7kRhc=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 516, + "top": 80, + "width": 1, + "height": 233, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 472, + "top": 40, + "width": 88, + "height": 273, + "autoResize": false, + "stereotypeDisplay": "label", + "showVisibility": true, + "showNamespace": false, + "showProperty": true, + "showType": true, + "nameCompartment": { + "$ref": "AAAAAAFdHQn7x57mVek=" + }, + "wordWrap": false, + "linePart": { + "$ref": "AAAAAAFdHQn7x57ralA=" + } + }, + { + "_type": "UMLSeqMessageView", + "_id": "AAAAAAFdHQrka58ztv8=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1MVCI=" + }, + "model": { + "$ref": "AAAAAAFdHQrkap8ywZE=" + }, + "subViews": [ + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQrka580RZc=", + "_parent": { + "$ref": "AAAAAAFdHQrka58ztv8=" + }, + "model": { + "$ref": "AAAAAAFdHQrkap8ywZE=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 280, + "top": 259, + "width": 84, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 10, + "hostEdge": { + "$ref": "AAAAAAFdHQrka58ztv8=" + }, + "edgePosition": 1, + "underline": false, + "text": "4 : checkIfWin", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQrka581cj0=", + "_parent": { + "$ref": "AAAAAAFdHQrka58ztv8=" + }, + "model": { + "$ref": "AAAAAAFdHQrkap8ywZE=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 337, + "top": 259, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 25, + "hostEdge": { + "$ref": "AAAAAAFdHQrka58ztv8=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQrka582R4Q=", + "_parent": { + "$ref": "AAAAAAFdHQrka58ztv8=" + }, + "model": { + "$ref": "AAAAAAFdHQrkap8ywZE=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 303, + "top": 260, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -1.5707963267948966, + "distance": 10, + "hostEdge": { + "$ref": "AAAAAAFdHQrka58ztv8=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "UMLActivationView", + "_id": "AAAAAAFdHQrka5831N4=", + "_parent": { + "$ref": "AAAAAAFdHQrka58ztv8=" + }, + "model": { + "$ref": "AAAAAAFdHQrkap8ywZE=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 277, + "top": 276, + "width": 14, + "height": 29, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "head": { + "$ref": "AAAAAAFdF+RP9KG/qmo=" + }, + "tail": { + "$ref": "AAAAAAFdF+RP9KG/qmo=" + }, + "lineStyle": 0, + "points": "283:256;313:256;313:276;290:276", + "nameLabel": { + "$ref": "AAAAAAFdHQrka580RZc=" + }, + "stereotypeLabel": { + "$ref": "AAAAAAFdHQrka581cj0=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdHQrka582R4Q=" + }, + "activation": { + "$ref": "AAAAAAFdHQrka5831N4=" + }, + "showProperty": true, + "showType": true + }, + { + "_type": "UMLSeqMessageView", + "_id": "AAAAAAFdHQtT8J9UAqo=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1MVCI=" + }, + "model": { + "$ref": "AAAAAAFdHQtT8J9TQQw=" + }, + "subViews": [ + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQtT8J9VOo0=", + "_parent": { + "$ref": "AAAAAAFdHQtT8J9UAqo=" + }, + "model": { + "$ref": "AAAAAAFdHQtT8J9TQQw=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 191, + "top": 276, + "width": 19, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 10, + "hostEdge": { + "$ref": "AAAAAAFdHQtT8J9UAqo=" + }, + "edgePosition": 1, + "underline": false, + "text": "5 : ", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQtT8J9WSys=", + "_parent": { + "$ref": "AAAAAAFdHQtT8J9UAqo=" + }, + "model": { + "$ref": "AAAAAAFdHQtT8J9TQQw=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 200, + "top": 291, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 25, + "hostEdge": { + "$ref": "AAAAAAFdHQtT8J9UAqo=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQtT8Z9XeJ4=", + "_parent": { + "$ref": "AAAAAAFdHQtT8J9UAqo=" + }, + "model": { + "$ref": "AAAAAAFdHQtT8J9TQQw=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 201, + "top": 256, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -1.5707963267948966, + "distance": 10, + "hostEdge": { + "$ref": "AAAAAAFdHQtT8J9UAqo=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "UMLActivationView", + "_id": "AAAAAAFdHQtT8Z9YmtM=", + "_parent": { + "$ref": "AAAAAAFdHQtT8J9UAqo=" + }, + "model": { + "$ref": "AAAAAAFdHQtT8J9TQQw=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 133, + "top": 272, + "width": 14, + "height": 25, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "head": { + "$ref": "AAAAAAFdF+OdfKGdq7U=" + }, + "tail": { + "$ref": "AAAAAAFdF+RP9KG/qmo=" + }, + "lineStyle": 0, + "points": "270:272;133:272", + "nameLabel": { + "$ref": "AAAAAAFdHQtT8J9VOo0=" + }, + "stereotypeLabel": { + "$ref": "AAAAAAFdHQtT8J9WSys=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdHQtT8Z9XeJ4=" + }, + "activation": { + "$ref": "AAAAAAFdHQtT8Z9YmtM=" + }, + "showProperty": true, + "showType": true + }, + { + "_type": "UMLSeqLifelineView", + "_id": "AAAAAAFdHQt8mJ9qCGY=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1MVCI=" + }, + "model": { + "$ref": "AAAAAAFdHQt8mJ9p6E8=" + }, + "subViews": [ + { + "_type": "UMLNameCompartmentView", + "_id": "AAAAAAFdHQt8mJ9ruWw=", + "_parent": { + "$ref": "AAAAAAFdHQt8mJ9qCGY=" + }, + "model": { + "$ref": "AAAAAAFdHQt8mJ9p6E8=" + }, + "subViews": [ + { + "_type": "LabelView", + "_id": "AAAAAAFdHQt8mZ9sOEM=", + "_parent": { + "$ref": "AAAAAAFdHQt8mJ9ruWw=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -192, + "top": 0, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdHQt8mZ9tGhY=", + "_parent": { + "$ref": "AAAAAAFdHQt8mJ9ruWw=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;1", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 573, + "top": 47, + "width": 109, + "height": 13, + "autoResize": false, + "underline": false, + "text": "display: Display", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdHQt8mZ9uDAY=", + "_parent": { + "$ref": "AAAAAAFdHQt8mJ9ruWw=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -192, + "top": 0, + "width": 99, + "height": 13, + "autoResize": false, + "underline": false, + "text": "(from Interaction)", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "LabelView", + "_id": "AAAAAAFdHQt8mZ9vP4w=", + "_parent": { + "$ref": "AAAAAAFdHQt8mJ9ruWw=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": -192, + "top": 0, + "width": 0, + "height": 13, + "autoResize": false, + "underline": false, + "horizontalAlignment": 1, + "verticalAlignment": 5, + "wordWrap": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 568, + "top": 40, + "width": 119, + "height": 40, + "autoResize": false, + "stereotypeLabel": { + "$ref": "AAAAAAFdHQt8mZ9sOEM=" + }, + "nameLabel": { + "$ref": "AAAAAAFdHQt8mZ9tGhY=" + }, + "namespaceLabel": { + "$ref": "AAAAAAFdHQt8mZ9uDAY=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdHQt8mZ9vP4w=" + } + }, + { + "_type": "UMLLinePartView", + "_id": "AAAAAAFdHQt8mZ9w62Y=", + "_parent": { + "$ref": "AAAAAAFdHQt8mJ9qCGY=" + }, + "model": { + "$ref": "AAAAAAFdHQt8mJ9p6E8=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 628, + "top": 80, + "width": 1, + "height": 283, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 568, + "top": 40, + "width": 119, + "height": 323, + "autoResize": false, + "stereotypeDisplay": "label", + "showVisibility": true, + "showNamespace": false, + "showProperty": true, + "showType": true, + "nameCompartment": { + "$ref": "AAAAAAFdHQt8mJ9ruWw=" + }, + "wordWrap": false, + "linePart": { + "$ref": "AAAAAAFdHQt8mZ9w62Y=" + } + }, + { + "_type": "UMLSeqMessageView", + "_id": "AAAAAAFdHQxJ4p+Q4MA=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1MVCI=" + }, + "model": { + "$ref": "AAAAAAFdHQxJ4p+P7MY=" + }, + "subViews": [ + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQxJ45+RqsQ=", + "_parent": { + "$ref": "AAAAAAFdHQxJ4p+Q4MA=" + }, + "model": { + "$ref": "AAAAAAFdHQxJ4p+P7MY=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 409, + "top": 304, + "width": 86, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 10, + "hostEdge": { + "$ref": "AAAAAAFdHQxJ4p+Q4MA=" + }, + "edgePosition": 1, + "underline": false, + "text": "6 : showResult", + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQxJ45+STu4=", + "_parent": { + "$ref": "AAAAAAFdHQxJ4p+Q4MA=" + }, + "model": { + "$ref": "AAAAAAFdHQxJ4p+P7MY=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 452, + "top": 289, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": 1.5707963267948966, + "distance": 25, + "hostEdge": { + "$ref": "AAAAAAFdHQxJ4p+Q4MA=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "EdgeLabelView", + "_id": "AAAAAAFdHQxJ45+TGcs=", + "_parent": { + "$ref": "AAAAAAFdHQxJ4p+Q4MA=" + }, + "model": { + "$ref": "AAAAAAFdHQxJ4p+P7MY=" + }, + "visible": false, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 452, + "top": 324, + "width": 0, + "height": 13, + "autoResize": false, + "alpha": -1.5707963267948966, + "distance": 10, + "hostEdge": { + "$ref": "AAAAAAFdHQxJ4p+Q4MA=" + }, + "edgePosition": 1, + "underline": false, + "horizontalAlignment": 2, + "verticalAlignment": 5, + "wordWrap": false + }, + { + "_type": "UMLActivationView", + "_id": "AAAAAAFdHQxJ45+UKO0=", + "_parent": { + "$ref": "AAAAAAFdHQxJ4p+Q4MA=" + }, + "model": { + "$ref": "AAAAAAFdHQxJ4p+P7MY=" + }, + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "left": 621, + "top": 320, + "width": 14, + "height": 29, + "autoResize": false + } + ], + "visible": true, + "enabled": true, + "lineColor": "#000000", + "fillColor": "#ffffff", + "fontColor": "#000000", + "font": "Arial;13;0", + "showShadow": true, + "containerChangeable": false, + "containerExtending": false, + "head": { + "$ref": "AAAAAAFdHQt8mZ9w62Y=" + }, + "tail": { + "$ref": "AAAAAAFdF+RP9KG/qmo=" + }, + "lineStyle": 0, + "points": "283:320;621:320", + "nameLabel": { + "$ref": "AAAAAAFdHQxJ45+RqsQ=" + }, + "stereotypeLabel": { + "$ref": "AAAAAAFdHQxJ45+STu4=" + }, + "propertyLabel": { + "$ref": "AAAAAAFdHQxJ45+TGcs=" + }, + "activation": { + "$ref": "AAAAAAFdHQxJ45+UKO0=" + }, + "showProperty": true, + "showType": true + } + ], + "showSequenceNumber": true, + "showSignature": true, + "showActivation": true + } + ], + "visibility": "public", + "isReentrant": true, + "messages": [ + { + "_type": "UMLMessage", + "_id": "AAAAAAFdF+TkA6HXVqw=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1LFdg=" + }, + "name": "play", + "source": { + "$ref": "AAAAAAFdF+OdeqGWcbc=" + }, + "target": { + "$ref": "AAAAAAFdF+RP86G4mVc=" + }, + "visibility": "public", + "messageSort": "synchCall", + "isConcurrentIteration": false + }, + { + "_type": "UMLMessage", + "_id": "AAAAAAFdF/sfZaPm+zc=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1LFdg=" + }, + "name": "roll", + "source": { + "$ref": "AAAAAAFdF+RP86G4mVc=" + }, + "target": { + "$ref": "AAAAAAFdF+Ugp6Huy74=" + }, + "visibility": "public", + "messageSort": "synchCall", + "isConcurrentIteration": false + }, + { + "_type": "UMLMessage", + "_id": "AAAAAAFdHQp4LZ8P0ZU=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1LFdg=" + }, + "name": "roll", + "source": { + "$ref": "AAAAAAFdF+RP86G4mVc=" + }, + "target": { + "$ref": "AAAAAAFdHQn7xp7kRhc=" + }, + "visibility": "public", + "messageSort": "synchCall", + "isConcurrentIteration": false + }, + { + "_type": "UMLMessage", + "_id": "AAAAAAFdHQrkap8ywZE=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1LFdg=" + }, + "name": "checkIfWin", + "source": { + "$ref": "AAAAAAFdF+RP86G4mVc=" + }, + "target": { + "$ref": "AAAAAAFdF+RP86G4mVc=" + }, + "visibility": "public", + "messageSort": "synchCall", + "isConcurrentIteration": false + }, + { + "_type": "UMLMessage", + "_id": "AAAAAAFdHQtT8J9TQQw=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1LFdg=" + }, + "source": { + "$ref": "AAAAAAFdF+RP86G4mVc=" + }, + "target": { + "$ref": "AAAAAAFdF+OdeqGWcbc=" + }, + "visibility": "public", + "messageSort": "reply", + "isConcurrentIteration": false + }, + { + "_type": "UMLMessage", + "_id": "AAAAAAFdHQxJ4p+P7MY=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1LFdg=" + }, + "name": "showResult", + "source": { + "$ref": "AAAAAAFdF+RP86G4mVc=" + }, + "target": { + "$ref": "AAAAAAFdHQt8mJ9p6E8=" + }, + "visibility": "public", + "messageSort": "synchCall", + "isConcurrentIteration": false + } + ], + "participants": [ + { + "_type": "UMLLifeline", + "_id": "AAAAAAFdF+OdeqGWcbc=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1LFdg=" + }, + "name": "player", + "visibility": "public", + "represent": { + "$ref": "AAAAAAFdF+OdeaGVt7c=" + }, + "isMultiInstance": false + }, + { + "_type": "UMLLifeline", + "_id": "AAAAAAFdF+RP86G4mVc=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1LFdg=" + }, + "name": "diceGame", + "visibility": "public", + "represent": { + "$ref": "AAAAAAFdF+RP8qG3O3c=" + }, + "isMultiInstance": false + }, + { + "_type": "UMLLifeline", + "_id": "AAAAAAFdF+Ugp6Huy74=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1LFdg=" + }, + "name": "dice1", + "visibility": "public", + "represent": { + "$ref": "AAAAAAFdF+Ugp6Htms4=" + }, + "isMultiInstance": false + }, + { + "_type": "UMLLifeline", + "_id": "AAAAAAFdHQn7xp7kRhc=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1LFdg=" + }, + "name": "dice2", + "visibility": "public", + "represent": { + "$ref": "AAAAAAFdHQn7xZ7jTMM=" + }, + "isMultiInstance": false + }, + { + "_type": "UMLLifeline", + "_id": "AAAAAAFdHQt8mJ9p6E8=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1LFdg=" + }, + "name": "display", + "visibility": "public", + "represent": { + "$ref": "AAAAAAFdHQt8mJ9oW1c=" + }, + "isMultiInstance": false + } + ] + } + ], + "visibility": "public", + "attributes": [ + { + "_type": "UMLAttribute", + "_id": "AAAAAAFdF+OdeaGVt7c=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1Khbw=" + }, + "name": "Role1", + "visibility": "public", + "isStatic": false, + "isLeaf": false, + "type": { + "$ref": "AAAAAAFdF9Jh5Z1ciZA=" + }, + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "aggregation": "none", + "isID": false + }, + { + "_type": "UMLAttribute", + "_id": "AAAAAAFdF+RP8qG3O3c=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1Khbw=" + }, + "name": "Role2", + "visibility": "public", + "isStatic": false, + "isLeaf": false, + "type": { + "$ref": "AAAAAAFdF9NBMZ2Jv50=" + }, + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "aggregation": "none", + "isID": false + }, + { + "_type": "UMLAttribute", + "_id": "AAAAAAFdF+Ugp6Htms4=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1Khbw=" + }, + "name": "Role3", + "visibility": "public", + "isStatic": false, + "isLeaf": false, + "type": { + "$ref": "AAAAAAFdF9RF6Z25s+k=" + }, + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "aggregation": "none", + "isID": false + }, + { + "_type": "UMLAttribute", + "_id": "AAAAAAFdHQn7xZ7jTMM=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1Khbw=" + }, + "name": "Role4", + "visibility": "public", + "isStatic": false, + "isLeaf": false, + "type": { + "$ref": "AAAAAAFdF9RF6Z25s+k=" + }, + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "aggregation": "none", + "isID": false + }, + { + "_type": "UMLAttribute", + "_id": "AAAAAAFdHQt8mJ9oW1c=", + "_parent": { + "$ref": "AAAAAAFdF9ENuJ1Khbw=" + }, + "name": "Role5", + "visibility": "public", + "isStatic": false, + "isLeaf": false, + "type": { + "$ref": "AAAAAAFdG6RIwpshRVw=" + }, + "isReadOnly": false, + "isOrdered": false, + "isUnique": false, + "isDerived": false, + "aggregation": "none", + "isID": false + } + ], + "isAbstract": false, + "isFinalSpecialization": false, + "isLeaf": false + } + ] +} \ No newline at end of file diff --git a/students/281918307/.gitignore b/students/281918307/.gitignore new file mode 100644 index 0000000000..15a7d78fcb --- /dev/null +++ b/students/281918307/.gitignore @@ -0,0 +1,153 @@ +/target/ +/.idea +/*.iml +/**/*.iml +/.setting +/*.project +.DS_Store +thrid-chongwu/.DS_Store +thrid-chongwu/src/.DS_Store +thrid-chongwu/src/main/.DS_Store +thrid-chongwu/src/main/assembly/.DS_Store +thrid-chongwu/src/main/resources/.DS_Store +thrid-chongwu/src/main/resources/templates/.DS_Store +thrid-chongwu/src/main/webapp/ +thrid-chongwu/src/test/ +thrid-chongwu/target/ +### Java template +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/dictionaries + +# Sensitive or high-churn files: +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.xml +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml + +# Gradle: +.idea/**/gradle.xml +.idea/**/libraries + +# Mongo Explorer plugin: +.idea/**/mongoSettings.xml + +## File-based project format: +*.iws + +## Plugin-specific files: + +# IntelliJ +/out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties +### macOS template +*.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk +### Windows template +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk +### Archives template +# It's better to unpack these files and commit the raw source because +# git has its own built in compression methods. +*.7z +*.gz +*.bzip +*.bz2 +*.xz +*.lzma + +#packing-only formats +*.iso +*.tar + +#package management formats +*.dmg +*.xpi +*.gem +*.egg +*.deb +*.rpm +### SVN template +.svn/ diff --git a/students/281918307/ood-ocp/pom.xml b/students/281918307/ood-ocp/pom.xml new file mode 100644 index 0000000000..60ad55a370 --- /dev/null +++ b/students/281918307/ood-ocp/pom.xml @@ -0,0 +1,83 @@ + + + 4.0.0 + + + com.ood + ood-application + 1.0.0-SNAPSHOT + ../pom.xml + + + ood-ocp + jar + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + + + + org.springframework.boot + spring-boot-starter-freemarker + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + + org.springframework.boot + spring-boot-devtools + provided + true + + + org.apache.tomcat.embed + tomcat-embed-core + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.dajia.customization.Application + -Dfile.encoding=${project.build.sourceEncoding} + + true + + + + + repackage + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + \ No newline at end of file diff --git a/students/281918307/ood-ocp/src/main/java/com/ood/ocp/Application.java b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/Application.java new file mode 100644 index 0000000000..5fc79ba891 --- /dev/null +++ b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/Application.java @@ -0,0 +1,14 @@ +package com.ood.ocp; + +import org.apache.log4j.Logger; + +/** + * Created by ajaxfeng on 2017/6/20. + */ +public class Application { + static final Logger logger = Logger.getLogger(Application.class); + + public static void main(String[] args) { + logger.error("Application running ..."); + } +} diff --git a/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/config/LoggerConfig.java b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/config/LoggerConfig.java new file mode 100644 index 0000000000..fac6f09e8c --- /dev/null +++ b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/config/LoggerConfig.java @@ -0,0 +1,31 @@ +package com.ood.ocp.logs.config; + +import com.ood.ocp.logs.content.ContentService; + +import java.util.List; + +/** + * Created by ajaxfeng on 2017/6/24. + */ +public interface LoggerConfig { + + public final int RAW_LOG = 1; + public final int RAW_LOG_WITH_DATE = 2; + public final int EMAIL_LOG = 1; + public final int SMS_LOG = 2; + public final int PRINT_LOG = 3; + + /** + * + * @return + */ + public ContentService getContentService(); + + /** + * 设置类型 + * + * @param sendTypeList + */ + public void setSendTypeList(List sendTypeList); + +} diff --git a/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/config/LoggerConfigImpl.java b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/config/LoggerConfigImpl.java new file mode 100644 index 0000000000..f8ef1661cd --- /dev/null +++ b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/config/LoggerConfigImpl.java @@ -0,0 +1,78 @@ +package com.ood.ocp.logs.config; + +import com.ood.ocp.logs.content.ContentService; +import com.ood.ocp.logs.sender.LoggerSender; +import com.ood.ocp.logs.sender.LoggerSenderWacher; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * Created by ajaxfeng on 2017/6/24. + */ +@Service +public class LoggerConfigImpl implements LoggerConfig { + @Autowired + private LoggerSenderWacher loggerSenderWacher; + + private int contentType; + + private List sendTypeList; + @Autowired + private LoggerSender mailLoggerSender; + @Autowired + private LoggerSender smsLoggerSender; + @Autowired + private LoggerSender consoleLoggerSender; + @Autowired + private ContentService contentService; + @Autowired + private ContentService dateContentService; + + + @Override + public ContentService getContentService() { + if (RAW_LOG == contentType) { + return contentService; + } + if (RAW_LOG_WITH_DATE == contentType) { + return dateContentService; + } + + return contentService; + } + + private void initLoggerWacher(){ + if(sendTypeList.contains(EMAIL_LOG)){ + loggerSenderWacher.addLoggerSender(mailLoggerSender); + } + if(sendTypeList.contains(SMS_LOG)){ + loggerSenderWacher.addLoggerSender(smsLoggerSender); + } + if(sendTypeList.contains(PRINT_LOG)){ + loggerSenderWacher.addLoggerSender(consoleLoggerSender); + } + } + + public int getContentType() { + return contentType; + } + + public void setContentType(int contentType) { + this.contentType = contentType; + } + + public List getSendTypeList() { + return sendTypeList; + } + + /** + * 设置类型 + * @param sendTypeList + */ + public void setSendTypeList(List sendTypeList) { + this.sendTypeList = sendTypeList; + initLoggerWacher(); + } +} diff --git a/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/content/ContentService.java b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/content/ContentService.java new file mode 100644 index 0000000000..b10fedb33a --- /dev/null +++ b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/content/ContentService.java @@ -0,0 +1,9 @@ +package com.ood.ocp.logs.content; + +/** + * Created by ajaxfeng on 2017/6/24. + */ +public interface ContentService { + + public String getConteng(String logMsg); +} diff --git a/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/content/DateContentServiceImpl.java b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/content/DateContentServiceImpl.java new file mode 100644 index 0000000000..a088d537a0 --- /dev/null +++ b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/content/DateContentServiceImpl.java @@ -0,0 +1,17 @@ +package com.ood.ocp.logs.content; + +import com.ood.ocp.util.DateUtil; +import org.springframework.stereotype.Service; + +/** + * 日期+log + * Created by ajaxfeng on 2017/6/24. + */ +@Service("dateContentService") +public class DateContentServiceImpl implements ContentService { + + @Override + public String getConteng(String logMsg) { + return DateUtil.getCurrentDateAsString() + ":" + logMsg; + } +} diff --git a/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/content/DefaultContentServiceImpl.java b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/content/DefaultContentServiceImpl.java new file mode 100644 index 0000000000..2fee453d79 --- /dev/null +++ b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/content/DefaultContentServiceImpl.java @@ -0,0 +1,14 @@ +package com.ood.ocp.logs.content; + +import org.springframework.stereotype.Service; + +/** + * Created by ajaxfeng on 2017/6/24. + */ +@Service("contentService") +public class DefaultContentServiceImpl implements ContentService { + @Override + public String getConteng(String logMsg) { + return logMsg; + } +} diff --git a/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/logger/LoggerService.java b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/logger/LoggerService.java new file mode 100644 index 0000000000..07cda40042 --- /dev/null +++ b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/logger/LoggerService.java @@ -0,0 +1,10 @@ +package com.ood.ocp.logs.logger; + +/** + * 发送日志 + * Created by ajaxfeng on 2017/6/24. + */ +public interface LoggerService { + + public String logger(String logMsg); +} diff --git a/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/logger/LoggerServiceImpl.java b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/logger/LoggerServiceImpl.java new file mode 100644 index 0000000000..b1d370e4c6 --- /dev/null +++ b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/logger/LoggerServiceImpl.java @@ -0,0 +1,43 @@ +package com.ood.ocp.logs.logger; + +import com.ood.ocp.logs.config.LoggerConfig; +import com.ood.ocp.logs.content.ContentService; +import com.ood.ocp.logs.sender.LoggerSender; +import com.ood.ocp.logs.sender.LoggerSenderWacher; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by ajaxfeng on 2017/6/24. + */ +@Service +public class LoggerServiceImpl implements LoggerService { + + @Autowired + LoggerConfig loggerConfig; + @Autowired + LoggerSenderWacher loggerSenderWacher; + + + @Override + public String logger(String logMsg) { + + List typeList=new ArrayList(); + typeList.add(1); + typeList.add(2); + typeList.add(3); + + loggerConfig.setSendTypeList(typeList); + + //构造内容 + ContentService contentService = loggerConfig.getContentService(); + String content = contentService.getConteng(logMsg); + + //推送消息 + loggerSenderWacher.watch(content); + return "success"; + } +} diff --git a/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/sender/ConsoleLoggerSender.java b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/sender/ConsoleLoggerSender.java new file mode 100644 index 0000000000..ec20cb1229 --- /dev/null +++ b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/sender/ConsoleLoggerSender.java @@ -0,0 +1,15 @@ +package com.ood.ocp.logs.sender; + +import org.springframework.stereotype.Service; + +/** + * Created by ajaxfeng on 2017/6/25. + */ +@Service("consoleLoggerSender") +public class ConsoleLoggerSender implements LoggerSender { + @Override + public String sendLog(String logMsg) { + System.out.println(logMsg); + return null; + } +} diff --git a/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/sender/LoggerSender.java b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/sender/LoggerSender.java new file mode 100644 index 0000000000..1aee4b6ae1 --- /dev/null +++ b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/sender/LoggerSender.java @@ -0,0 +1,11 @@ +package com.ood.ocp.logs.sender; + +/** + * 日志发送 + * Created by ajaxfeng on 2017/6/24. + */ +public interface LoggerSender { + + public String sendLog(String logMsg); + +} diff --git a/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/sender/LoggerSenderWacher.java b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/sender/LoggerSenderWacher.java new file mode 100644 index 0000000000..72f5c8013a --- /dev/null +++ b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/sender/LoggerSenderWacher.java @@ -0,0 +1,39 @@ +package com.ood.ocp.logs.sender; + +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * 日志观察者 + * Created by ajaxfeng on 2017/6/26. + */ +@Service +public class LoggerSenderWacher { + private List loggerSenders; + + public List getLoggerSenders() { + return loggerSenders; + } + + public void addLoggerSender(LoggerSender loggerSender){ + if(!loggerSenders.contains(loggerSender)){ + loggerSenders.add(loggerSender); + } + } + + public void setLoggerSenders(List loggerSenders) { + this.loggerSenders = loggerSenders; + } + + /** + * 调用观察者发送消息 + * @param content + */ + public void watch(String content){ + for(LoggerSender loggerSender:loggerSenders){ + loggerSender.sendLog(content); + } + } + +} diff --git a/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/sender/MailLoggerSender.java b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/sender/MailLoggerSender.java new file mode 100644 index 0000000000..513f352ff1 --- /dev/null +++ b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/sender/MailLoggerSender.java @@ -0,0 +1,17 @@ +package com.ood.ocp.logs.sender; + +import com.ood.ocp.util.MailUtil; +import org.springframework.stereotype.Service; + +/** + * 邮件实现类 + * Created by ajaxfeng on 2017/6/24. + */ +@Service("mailLoggerSender") +public class MailLoggerSender implements LoggerSender { + @Override + public String sendLog(String logMsg) { + MailUtil.send(logMsg); + return "success"; + } +} diff --git a/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/sender/SMSLoggerSender.java b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/sender/SMSLoggerSender.java new file mode 100644 index 0000000000..3d6f8f3ea9 --- /dev/null +++ b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/logs/sender/SMSLoggerSender.java @@ -0,0 +1,17 @@ +package com.ood.ocp.logs.sender; + +import com.ood.ocp.util.SMSUtil; +import org.springframework.stereotype.Service; + +/** + * 短信 + * Created by ajaxfeng on 2017/6/24. + */ +@Service("smsLoggerSender") +public class SMSLoggerSender implements LoggerSender { + @Override + public String sendLog(String logMsg) { + SMSUtil.send(logMsg); + return null; + } +} diff --git a/students/281918307/ood-ocp/src/main/java/com/ood/ocp/util/DateUtil.java b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/util/DateUtil.java new file mode 100644 index 0000000000..927250a6c5 --- /dev/null +++ b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/util/DateUtil.java @@ -0,0 +1,10 @@ +package com.ood.ocp.util; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return null; + } + +} diff --git a/students/281918307/ood-ocp/src/main/java/com/ood/ocp/util/MailUtil.java b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/util/MailUtil.java new file mode 100644 index 0000000000..d2be222460 --- /dev/null +++ b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/util/MailUtil.java @@ -0,0 +1,10 @@ +package com.ood.ocp.util; + +public class MailUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/281918307/ood-ocp/src/main/java/com/ood/ocp/util/SMSUtil.java b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/util/SMSUtil.java new file mode 100644 index 0000000000..30851cbb40 --- /dev/null +++ b/students/281918307/ood-ocp/src/main/java/com/ood/ocp/util/SMSUtil.java @@ -0,0 +1,10 @@ +package com.ood.ocp.util; + +public class SMSUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/281918307/ood-ocp/src/main/resources/log4j.properties b/students/281918307/ood-ocp/src/main/resources/log4j.properties new file mode 100644 index 0000000000..e70566ce70 --- /dev/null +++ b/students/281918307/ood-ocp/src/main/resources/log4j.properties @@ -0,0 +1,6 @@ +log4j.rootLogger=debug, stdout +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %l - %m%n +# Third party loggers +log4j.logger.com.ood=debug diff --git a/students/281918307/ood-srp/pom.xml b/students/281918307/ood-srp/pom.xml new file mode 100644 index 0000000000..e2c51f2ab2 --- /dev/null +++ b/students/281918307/ood-srp/pom.xml @@ -0,0 +1,83 @@ + + + 4.0.0 + + + com.ood + ood-application + 1.0.0-SNAPSHOT + ../pom.xml + + + ood-srp + jar + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + + + + org.springframework.boot + spring-boot-starter-freemarker + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + + org.springframework.boot + spring-boot-devtools + provided + true + + + org.apache.tomcat.embed + tomcat-embed-core + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.dajia.customization.Application + -Dfile.encoding=${project.build.sourceEncoding} + + true + + + + + repackage + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + \ No newline at end of file diff --git a/students/281918307/ood-srp/src/main/java/com/ood/srp/Application.java b/students/281918307/ood-srp/src/main/java/com/ood/srp/Application.java new file mode 100644 index 0000000000..bc76120dd9 --- /dev/null +++ b/students/281918307/ood-srp/src/main/java/com/ood/srp/Application.java @@ -0,0 +1,18 @@ +package com.ood.srp; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.ComponentScan; + +/** + * Created by ajaxfeng on 2017/4/28. + */ +@SpringBootApplication +@EnableConfigurationProperties +@ComponentScan("com.ood.srp") +public class Application { + public static void main(String[] args) throws Exception { + SpringApplication.run(Application.class, args); + } +} \ No newline at end of file diff --git a/students/281918307/ood-srp/src/main/java/com/ood/srp/file/FileService.java b/students/281918307/ood-srp/src/main/java/com/ood/srp/file/FileService.java new file mode 100644 index 0000000000..17da5e5add --- /dev/null +++ b/students/281918307/ood-srp/src/main/java/com/ood/srp/file/FileService.java @@ -0,0 +1,18 @@ +package com.ood.srp.file; + +import java.util.List; + +/** + * 读取文件内容 + * Created by ajaxfeng on 2017/6/20. + */ +public interface FileService { + + /** + * 读取文件内容,放到List内 + * + * @param filePath + * @return + */ + List readFile(String filePath) throws Exception; +} diff --git a/students/281918307/ood-srp/src/main/java/com/ood/srp/file/impl/FileServiceImpl.java b/students/281918307/ood-srp/src/main/java/com/ood/srp/file/impl/FileServiceImpl.java new file mode 100644 index 0000000000..71385b81ad --- /dev/null +++ b/students/281918307/ood-srp/src/main/java/com/ood/srp/file/impl/FileServiceImpl.java @@ -0,0 +1,35 @@ +package com.ood.srp.file.impl; + +import com.ood.srp.file.FileService; +import com.ood.srp.util.FileUtil; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +/** + * 文件处理类 + * Created by yuxia on 2017/6/21. + */ +@Service +public class FileServiceImpl implements FileService { + + + /** + * 获取信息 + * + * @param filePath + * @return + * @throws Exception + */ + public List readFile(String filePath) throws Exception { + List lineList = new ArrayList<>(); + FileUtil fileUtil = new FileUtil(filePath); + while (fileUtil.hasNext()) { + String s = fileUtil.readLine(); + lineList.add(s); + } + fileUtil.close(); + return lineList; + } +} diff --git a/students/281918307/ood-srp/src/main/java/com/ood/srp/mail/Configuration.java b/students/281918307/ood-srp/src/main/java/com/ood/srp/mail/Configuration.java new file mode 100644 index 0000000000..88eb7af347 --- /dev/null +++ b/students/281918307/ood-srp/src/main/java/com/ood/srp/mail/Configuration.java @@ -0,0 +1,27 @@ +package com.ood.srp.mail; + +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + + static { + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/281918307/ood-srp/src/main/java/com/ood/srp/mail/ConfigurationKeys.java b/students/281918307/ood-srp/src/main/java/com/ood/srp/mail/ConfigurationKeys.java new file mode 100644 index 0000000000..8199bf780d --- /dev/null +++ b/students/281918307/ood-srp/src/main/java/com/ood/srp/mail/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.ood.srp.mail; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/281918307/ood-srp/src/main/java/com/ood/srp/mail/MailService.java b/students/281918307/ood-srp/src/main/java/com/ood/srp/mail/MailService.java new file mode 100644 index 0000000000..c85740e19e --- /dev/null +++ b/students/281918307/ood-srp/src/main/java/com/ood/srp/mail/MailService.java @@ -0,0 +1,29 @@ +package com.ood.srp.mail; + +import com.ood.srp.user.UserInfo; + +import java.util.List; + +/** + * Created by ajaxfeng on 2017/6/20. + */ +public interface MailService { + + /** + * 主SMTP服务器地址 + */ + public static final String SMTP_SERVER = "smtp.163.com"; + + /** + * 备用SMTP服务器地址 + */ + public static final String ALT_SMTP_SERVER = "smtp1.163.com"; + + /** + * 以哪个邮箱地址发送给用户 + */ + public static final String EMAIL_ADMIN = "admin@company.com"; + + + public String sendEmail(List userInfoList); +} diff --git a/students/281918307/ood-srp/src/main/java/com/ood/srp/mail/impl/MailServiceImpl.java b/students/281918307/ood-srp/src/main/java/com/ood/srp/mail/impl/MailServiceImpl.java new file mode 100644 index 0000000000..e633f94a55 --- /dev/null +++ b/students/281918307/ood-srp/src/main/java/com/ood/srp/mail/impl/MailServiceImpl.java @@ -0,0 +1,62 @@ +package com.ood.srp.mail.impl; + +import com.ood.srp.mail.MailService; +import com.ood.srp.user.UserInfo; +import com.ood.srp.util.MailUtil; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * Created by yuxia on 2017/6/21. + */ +@Service +public class MailServiceImpl implements MailService { + + /** + * 发送邮件 + * + * @param userInfoList + * @return + */ + @Override + public String sendEmail(List userInfoList) { + if (userInfoList == null) { + System.out.println("没有邮件发送"); + return "none"; + } + + for (UserInfo info : userInfoList) { + if (!info.getEmail().isEmpty()) { + String emailInfo = generatePromotionEmail(info); + try { + MailUtil.sendPromotionEmail(emailInfo); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + } + } + return "success"; + } + + /** + * 根据用户信息生成促销邮件内容。 + * + * @param userInfo 用户信息。 + * @return 返回生成的邮件。 + */ + private static String generatePromotionEmail(UserInfo userInfo) { + StringBuilder buffer = new StringBuilder(); + + buffer.append("From:").append(EMAIL_ADMIN).append("\n"); + buffer.append("To:").append(userInfo.getEmail()).append("\n"); + buffer.append("Subject:").append("您关注的产品降价了").append("\n"); + buffer.append("Content:").append("尊敬的").append(userInfo.getName()); + buffer.append(", 您关注的产品 ").append(userInfo.getProductDesc()); + buffer.append(" 降价了,欢迎购买!").append("\n"); + + System.out.println(buffer.toString()); + + return buffer.toString(); + } +} diff --git a/students/281918307/ood-srp/src/main/java/com/ood/srp/product/ProductDetail.java b/students/281918307/ood-srp/src/main/java/com/ood/srp/product/ProductDetail.java new file mode 100644 index 0000000000..71bfc3e52c --- /dev/null +++ b/students/281918307/ood-srp/src/main/java/com/ood/srp/product/ProductDetail.java @@ -0,0 +1,27 @@ +package com.ood.srp.product; + +/** + * 产品信息数据类。 + * + * @since 06.18.2017 + */ +public class ProductDetail { + private String id; + private String description; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } +} diff --git a/students/281918307/ood-srp/src/main/java/com/ood/srp/product/ProductDetailService.java b/students/281918307/ood-srp/src/main/java/com/ood/srp/product/ProductDetailService.java new file mode 100644 index 0000000000..0ed1920a18 --- /dev/null +++ b/students/281918307/ood-srp/src/main/java/com/ood/srp/product/ProductDetailService.java @@ -0,0 +1,17 @@ +package com.ood.srp.product; + +import java.util.List; + +/** + * 产品信息 + * Created by ajaxfeng on 2017/6/20. + */ +public interface ProductDetailService { + /** + * 获取产品详情 + * + * @param lineList + * @return + */ + public List getProductDetailList(List lineList); +} diff --git a/students/281918307/ood-srp/src/main/java/com/ood/srp/product/impl/ProductDetailServiceImpl.java b/students/281918307/ood-srp/src/main/java/com/ood/srp/product/impl/ProductDetailServiceImpl.java new file mode 100644 index 0000000000..9e5f4434a1 --- /dev/null +++ b/students/281918307/ood-srp/src/main/java/com/ood/srp/product/impl/ProductDetailServiceImpl.java @@ -0,0 +1,43 @@ +package com.ood.srp.product.impl; + +import com.ood.srp.product.ProductDetail; +import com.ood.srp.product.ProductDetailService; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +/** + * 商品信息逻辑 + * Created by yuxia on 2017/6/21. + */ +@Service +public class ProductDetailServiceImpl implements ProductDetailService { + + /** + * 获取商品信息 + * + * @param lineList + * @return + */ + public List getProductDetailList(List lineList) { + List productDetailList = new ArrayList<>(); + lineList.forEach(line -> { + String[] splitInfo = line.split(" "); + if (splitInfo.length >= 2) { + String id = splitInfo[0]; + String description = splitInfo[1]; + ProductDetail productDetail = getProductDetail(id, description); + productDetailList.add(productDetail); + } + }); + return productDetailList; + } + + private ProductDetail getProductDetail(String id, String description) { + ProductDetail productDetail = new ProductDetail(); + productDetail.setId(id); + productDetail.setDescription(description); + return productDetail; + } +} diff --git a/students/281918307/ood-srp/src/main/java/com/ood/srp/promotion/PromotionService.java b/students/281918307/ood-srp/src/main/java/com/ood/srp/promotion/PromotionService.java new file mode 100644 index 0000000000..1653a981c6 --- /dev/null +++ b/students/281918307/ood-srp/src/main/java/com/ood/srp/promotion/PromotionService.java @@ -0,0 +1,16 @@ +package com.ood.srp.promotion; + +/** + * 促销处理类 + * Created by ajaxfeng on 2017/6/20. + */ +public interface PromotionService { + + /** + * 发布促销信息 + * + * @return + */ + String promotion() throws Exception; + +} diff --git a/students/281918307/ood-srp/src/main/java/com/ood/srp/promotion/impl/PromotionServiceImpl.java b/students/281918307/ood-srp/src/main/java/com/ood/srp/promotion/impl/PromotionServiceImpl.java new file mode 100644 index 0000000000..c7e104dde5 --- /dev/null +++ b/students/281918307/ood-srp/src/main/java/com/ood/srp/promotion/impl/PromotionServiceImpl.java @@ -0,0 +1,63 @@ +package com.ood.srp.promotion.impl; + +import com.ood.srp.file.FileService; +import com.ood.srp.mail.MailService; +import com.ood.srp.product.ProductDetail; +import com.ood.srp.product.ProductDetailService; +import com.ood.srp.promotion.PromotionService; +import com.ood.srp.user.UserInfo; +import com.ood.srp.user.UserInfoService; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.ArrayList; +import java.util.List; + +/** + * 发布促销信息 + * Created by yuxia on 2017/6/21. + */ +public class PromotionServiceImpl implements PromotionService { + + private static final String FILE_PATH = "pro.text"; + + @Autowired + FileService fileService; + @Autowired + ProductDetailService productDetailService; + @Autowired + UserInfoService userInfoService; + @Autowired + MailService mailService; + + /** + *

促销


+ * 1. 获取文件内容
+ * 2. 根据文件内容,获取商品信息
+ * 3. 根据商品信息,获得用户信息
+ * 4. 针对用户信息,进行邮件发送
+ * 可扩展行: + * 1. 发送促销信息,可抽象一个接口:具体可以通过邮件、短信等手段发送 + * @return + * @throws Exception + */ + @Override + public String promotion() throws Exception { + List strings = fileService.readFile(FILE_PATH); + List productDetailList = + productDetailService.getProductDetailList(strings); + List idList = productDetailList2IDList(productDetailList); + List userInfoList = userInfoService.listUserInfo(idList); + String s = mailService.sendEmail(userInfoList); + System.out.println(s); + return s; + } + + List productDetailList2IDList(List productDetails) { + List idList = new ArrayList<>(); + for (ProductDetail productDetail : productDetails) { + idList.add(productDetail.getId()); + } + return idList; + } + +} diff --git a/students/281918307/ood-srp/src/main/java/com/ood/srp/user/UserInfo.java b/students/281918307/ood-srp/src/main/java/com/ood/srp/user/UserInfo.java new file mode 100644 index 0000000000..14c363fa43 --- /dev/null +++ b/students/281918307/ood-srp/src/main/java/com/ood/srp/user/UserInfo.java @@ -0,0 +1,30 @@ +package com.ood.srp.user; + +/** + * 用户数据类。 + * + * @since 06.18.2017 + */ +public class UserInfo { + private String name; + private String email; + private String productDesc; + + public UserInfo(String name, String email, String productDesc) { + this.name = name; + this.email = email; + this.productDesc = productDesc; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + public String getProductDesc() { + return productDesc; + } +} diff --git a/students/281918307/ood-srp/src/main/java/com/ood/srp/user/UserInfoService.java b/students/281918307/ood-srp/src/main/java/com/ood/srp/user/UserInfoService.java new file mode 100644 index 0000000000..da206c4a5a --- /dev/null +++ b/students/281918307/ood-srp/src/main/java/com/ood/srp/user/UserInfoService.java @@ -0,0 +1,25 @@ +package com.ood.srp.user; + +import java.util.List; + +/** + * 用户逻辑 + * Created by ajaxfeng on 2017/6/20. + */ +public interface UserInfoService { + /** + * 获取用户信息 + * + * @param productID + * @return + */ + public List listUserInfo(String productID); + + /** + * 获取用户信息 + * + * @param productID + * @return + */ + public List listUserInfo(List productID); +} diff --git a/students/281918307/ood-srp/src/main/java/com/ood/srp/user/impl/UserInfoServiceImpl.java b/students/281918307/ood-srp/src/main/java/com/ood/srp/user/impl/UserInfoServiceImpl.java new file mode 100644 index 0000000000..5ddd5f6a45 --- /dev/null +++ b/students/281918307/ood-srp/src/main/java/com/ood/srp/user/impl/UserInfoServiceImpl.java @@ -0,0 +1,31 @@ +package com.ood.srp.user.impl; + +import com.ood.srp.user.UserInfo; +import com.ood.srp.user.UserInfoService; +import com.ood.srp.util.DBUtil; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by yuxia on 2017/6/21. + */ +@Service +public class UserInfoServiceImpl implements UserInfoService { + @Override + public List listUserInfo(String productID) { + List userInfoList = DBUtil.query(productID); + return userInfoList; + } + + @Override + public List listUserInfo(List productIDList) { + List userInfoAll = new ArrayList<>(); + for (String id : productIDList) { + List userInfoList = listUserInfo(id); + userInfoAll.addAll(userInfoList); + } + return userInfoAll; + } +} diff --git a/students/281918307/ood-srp/src/main/java/com/ood/srp/util/DBUtil.java b/students/281918307/ood-srp/src/main/java/com/ood/srp/util/DBUtil.java new file mode 100644 index 0000000000..dc9affd22f --- /dev/null +++ b/students/281918307/ood-srp/src/main/java/com/ood/srp/util/DBUtil.java @@ -0,0 +1,42 @@ +package com.ood.srp.util; + + +import com.ood.srp.user.UserInfo; + +import java.util.ArrayList; +import java.util.List; + +/** + * 数据库操作类。 + * 管理数据库连接,查询等操作。 + * + * @since 06.19.2017 + */ +public class DBUtil { + + //TODO 此处添加数据库连接信息 + + + /** + * 应该从数据库读, 但是简化为直接生成。 + * 给一个产品详情,返回一个Array List记载所有订阅该产品的用户信息(名字,邮箱,订阅的产品名称)。 + * + * @param productID 传产品详情。产品id用来查询数据库。产品名称用于和用户信息绑定 + * @return 返回数据库中所有的查询到的结果。 + */ + public static List query(String productID) { + if (productID == null) + return new ArrayList<>(); + + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID + "' " + + "and send_mail=1 "; + //假装用sendMilQuery查了数据库,生成了userList作为查询结果 + List userList = new ArrayList<>(); + for (int i = 1; i <= 3; i++) { + UserInfo newInfo = new UserInfo("User" + i, "aa@bb.com", ""); + userList.add(newInfo); + } + return userList; + } +} diff --git a/students/281918307/ood-srp/src/main/java/com/ood/srp/util/FileUtil.java b/students/281918307/ood-srp/src/main/java/com/ood/srp/util/FileUtil.java new file mode 100644 index 0000000000..05aa9d9c5b --- /dev/null +++ b/students/281918307/ood-srp/src/main/java/com/ood/srp/util/FileUtil.java @@ -0,0 +1,37 @@ +package com.ood.srp.util; + + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.Scanner; + +/** + * 文件操作类。 + * 负责文件句柄的维护。 + * 此类会打开促销文件,促销文件默认按照: + * "id" 空格 "产品名称" + * 进行存储,每行一条促销信息。 + * + * @since 06.19.2017 + */ +public class FileUtil { + private Scanner scanner; + + + public FileUtil(String filePath) throws FileNotFoundException { + scanner = new Scanner(new File(filePath)); + } + + public String readLine() { + String wholeInfo = scanner.nextLine(); + return wholeInfo; + } + + public boolean hasNext() { + return scanner.hasNextLine(); + } + + public void close() { + scanner.close(); + } +} diff --git a/students/281918307/ood-srp/src/main/java/com/ood/srp/util/MailUtil.java b/students/281918307/ood-srp/src/main/java/com/ood/srp/util/MailUtil.java new file mode 100644 index 0000000000..a6953d5306 --- /dev/null +++ b/students/281918307/ood-srp/src/main/java/com/ood/srp/util/MailUtil.java @@ -0,0 +1,37 @@ +package com.ood.srp.util; + + +/** + * 邮件发送类。 + * 管理邮箱连接,发送等操作。 + * + * @since 06.19.2017 + */ +public class MailUtil { + + /** + * SMTP连接失败异常。 + * 可用getMessage()获得异常内容。 + */ + public static class SMTPConnectionFailedException extends Throwable { + public SMTPConnectionFailedException(String message) { + super(message); + } + } + + + /** + * 假装在发邮件。默认使用主SMTP发送,若发送失败则使用备用SMTP发送。 + * 仍然失败,则抛出SMTPConnectFailException异常。 + * + * @param emailInfo 要发送的邮件内容 + * @throws SMTPConnectionFailedException 若主副SMTP服务器均连接失败,抛出异常。异常中包含完整的发送失败的邮件内容。可通过getMessage()方法获得邮件内容。 + */ + public static void sendPromotionEmail(String emailInfo) throws Exception { + //默认以SMTP_SERVER 发送 + //如果发送失败以ALT_SMTP_SERVER 重新发送 + //如果还失败,throw new SMTPConnectionFailedException(emailInfo). + } + + +} diff --git a/students/281918307/ood-srp/src/main/resources/application.properties b/students/281918307/ood-srp/src/main/resources/application.properties new file mode 100644 index 0000000000..a7e97d369d --- /dev/null +++ b/students/281918307/ood-srp/src/main/resources/application.properties @@ -0,0 +1,2 @@ +server.port=8080 +spring.application.name=ood-srp diff --git a/students/281918307/ood-srp/src/main/resources/log4j.properties b/students/281918307/ood-srp/src/main/resources/log4j.properties new file mode 100644 index 0000000000..e70566ce70 --- /dev/null +++ b/students/281918307/ood-srp/src/main/resources/log4j.properties @@ -0,0 +1,6 @@ +log4j.rootLogger=debug, stdout +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %l - %m%n +# Third party loggers +log4j.logger.com.ood=debug diff --git a/students/281918307/pom.xml b/students/281918307/pom.xml new file mode 100644 index 0000000000..61717fdeb7 --- /dev/null +++ b/students/281918307/pom.xml @@ -0,0 +1,80 @@ + + + 4.0.0 + + com.ood + ood-application + pom + 1.0.0-SNAPSHOT + + + ood-ocp + ood-srp + + + + + + aliyun maven + http://maven.aliyun.com/nexus/content/groups/public + + + maven.nuxeo.org + http://maven.nuxeo.org/nexus/content/groups/public/ + + + + + + + UTF-8 + + 1.8 + UTF-8 + 1.5.3.RELEASE + + + + + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring.boot.version} + pom + import + + + + junit + junit + 4.12 + test + + + + log4j + log4j + 1.2.16 + + + org.slf4j + slf4j-api + 1.6.1 + + + org.slf4j + slf4j-log4j12 + 1.6.1 + + + + + + + \ No newline at end of file diff --git a/students/281918307/readme.md b/students/281918307/readme.md new file mode 100644 index 0000000000..fdf99a9b89 --- /dev/null +++ b/students/281918307/readme.md @@ -0,0 +1,2 @@ +ood application + diff --git a/students/282692248/ood/ood-assignment/pom.xml b/students/282692248/ood/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/282692248/ood/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java new file mode 100644 index 0000000000..b6cf28c096 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return null; + } + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java new file mode 100644 index 0000000000..0357c4d912 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java @@ -0,0 +1,38 @@ +package com.coderising.ood.ocp; + +public class Logger { + + public final int RAW_LOG = 1; + public final int RAW_LOG_WITH_DATE = 2; + public final int EMAIL_LOG = 1; + public final int SMS_LOG = 2; + public final int PRINT_LOG = 3; + + int type = 0; + int method = 0; + + public Logger(int logType, int logMethod){ + this.type = logType; + this.method = logMethod; + } + public void log(String msg){ + + String logMsg = msg; + + if(this.type == RAW_LOG){ + logMsg = msg; + } else if(this.type == RAW_LOG_WITH_DATE){ + String txtDate = DateUtil.getCurrentDateAsString(); + logMsg = txtDate + ": " + msg; + } + + if(this.method == EMAIL_LOG){ + MailUtil.send(logMsg); + } else if(this.method == SMS_LOG){ + SMSUtil.send(logMsg); + } else if(this.method == PRINT_LOG){ + System.out.println(logMsg); + } + } +} + diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java new file mode 100644 index 0000000000..ec54b839c5 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class MailUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java new file mode 100644 index 0000000000..13cf802418 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class SMSUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/DateUtil.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/DateUtil.java new file mode 100644 index 0000000000..7d0b475c45 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/DateUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp.chasing; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return null; + } + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/Logger.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/Logger.java new file mode 100644 index 0000000000..9ee56868e2 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/Logger.java @@ -0,0 +1,19 @@ +package com.coderising.ood.ocp.chasing; + +import com.coderising.ood.ocp.chasing.formatter.ILogFormatter; +import com.coderising.ood.ocp.chasing.sender.ILogSender; + +public class Logger { + + private ILogFormatter formatter; + private ILogSender sender; + + public Logger(ILogFormatter formatter, ILogSender sender){ + this.formatter = formatter; + this.sender = sender; + } + public void log(String msg){ + sender.send(formatter.format(msg)); + } +} + diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/MailUtil.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/MailUtil.java new file mode 100644 index 0000000000..3ebf73ec62 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/MailUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp.chasing; + +public class MailUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/SMSUtil.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/SMSUtil.java new file mode 100644 index 0000000000..5f649d963b --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/SMSUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp.chasing; + +public class SMSUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/formatter/ILogFormatter.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/formatter/ILogFormatter.java new file mode 100644 index 0000000000..0c713dde7d --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/formatter/ILogFormatter.java @@ -0,0 +1,5 @@ +package com.coderising.ood.ocp.chasing.formatter; + +public interface ILogFormatter { + String format(String txt); +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/formatter/LogWithDateFormatter.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/formatter/LogWithDateFormatter.java new file mode 100644 index 0000000000..fb9555db9a --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/formatter/LogWithDateFormatter.java @@ -0,0 +1,12 @@ +package com.coderising.ood.ocp.chasing.formatter; + +import com.coderising.ood.ocp.chasing.DateUtil; + +public class LogWithDateFormatter implements ILogFormatter { + + @Override + public String format(String txt) { + return DateUtil.getCurrentDateAsString() + ": " + txt; + } + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/formatter/RawLog.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/formatter/RawLog.java new file mode 100644 index 0000000000..fdf2008c54 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/formatter/RawLog.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp.chasing.formatter; + +public class RawLog implements ILogFormatter { + + @Override + public String format(String txt) { + return txt; + } + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/sender/ILogSender.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/sender/ILogSender.java new file mode 100644 index 0000000000..339584d6e4 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/sender/ILogSender.java @@ -0,0 +1,5 @@ +package com.coderising.ood.ocp.chasing.sender; + +public interface ILogSender { + void send(String msg); +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/sender/MailSender.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/sender/MailSender.java new file mode 100644 index 0000000000..37652883ae --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/sender/MailSender.java @@ -0,0 +1,12 @@ +package com.coderising.ood.ocp.chasing.sender; + +import com.coderising.ood.ocp.chasing.MailUtil; + +public class MailSender implements ILogSender { + + @Override + public void send(String msg) { + MailUtil.send(msg); + } + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/sender/SMSSender.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/sender/SMSSender.java new file mode 100644 index 0000000000..2c7f92bf3b --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/sender/SMSSender.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp.chasing.sender; + +public class SMSSender implements ILogSender { + + @Override + public void send(String msg) { + System.out.println(msg); + } + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/sender/StdoutSender.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/sender/StdoutSender.java new file mode 100644 index 0000000000..7e10d45b4f --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/chasing/sender/StdoutSender.java @@ -0,0 +1,12 @@ +package com.coderising.ood.ocp.chasing.sender; + +import com.coderising.ood.ocp.chasing.SMSUtil; + +public class StdoutSender implements ILogSender { + + @Override + public void send(String msg) { + SMSUtil.send(msg); + } + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Formatter.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Formatter.java new file mode 100644 index 0000000000..b6e2ccbc16 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Formatter.java @@ -0,0 +1,7 @@ +package com.coderising.ood.ocp.good; + +public interface Formatter { + + String format(String msg); + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/FormatterFactory.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/FormatterFactory.java new file mode 100644 index 0000000000..3c2009a674 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/FormatterFactory.java @@ -0,0 +1,13 @@ +package com.coderising.ood.ocp.good; + +public class FormatterFactory { + public static Formatter createFormatter(int type){ + if(type == 1){ + return new RawFormatter(); + } + if (type == 2){ + return new HtmlFormatter(); + } + return null; + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/HtmlFormatter.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/HtmlFormatter.java new file mode 100644 index 0000000000..3d375f5acc --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/HtmlFormatter.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp.good; + +public class HtmlFormatter implements Formatter { + + @Override + public String format(String msg) { + + return null; + } + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Logger.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Logger.java new file mode 100644 index 0000000000..f206472d0d --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Logger.java @@ -0,0 +1,18 @@ +package com.coderising.ood.ocp.good; + +public class Logger { + + private Formatter formatter; + private Sender sender; + + public Logger(Formatter formatter,Sender sender){ + this.formatter = formatter; + this.sender = sender; + } + public void log(String msg){ + sender.send(formatter.format(msg)) ; + } + + +} + diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/RawFormatter.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/RawFormatter.java new file mode 100644 index 0000000000..7f1cb4ae30 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/RawFormatter.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp.good; + +public class RawFormatter implements Formatter { + + @Override + public String format(String msg) { + + return null; + } + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Sender.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Sender.java new file mode 100644 index 0000000000..aaa46c1fb7 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Sender.java @@ -0,0 +1,7 @@ +package com.coderising.ood.ocp.good; + +public interface Sender { + + void send(String msg); + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..9f9e749af7 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..402c4f6f97 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,199 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery = null; + + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected String productID = null; + protected String productDesc = null; + + private static Configuration config; + + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + File f = new File("D:\\jp\\study\\coding2017-master\\students\\282692248\\ood\\ood-assignment\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + + + config = new Configuration(); + + setSMTPHost(); + setAltSMTPHost(); + + + setFromAddress(); + + + setLoadQuery(); + + sendEMails(mailDebug, loadMailingList()); + + + } + + + + + protected void setProductID(String productID) + { + this.productID = productID; + + } + + protected String getproductID() + { + return productID; + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected void setSMTPHost() + { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() + { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + protected void setFromAddress() + { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setMessage(HashMap userInfo) throws IOException + { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + + + + } + + + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + private void setProductDesc(String desc) { + this.productDesc = desc; + } + + + protected void configureEMail(HashMap userInfo) throws IOException + { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try + { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } + + else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/Configuration.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/Configuration.java new file mode 100644 index 0000000000..a34fd144aa --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp.chasing; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/ConfigurationKeys.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/ConfigurationKeys.java new file mode 100644 index 0000000000..9d0f0caa1b --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp.chasing; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/PromotionMail.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/PromotionMail.java new file mode 100644 index 0000000000..8008f6b11b --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/PromotionMail.java @@ -0,0 +1,45 @@ +package com.coderising.ood.srp.chasing; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +import com.coderising.ood.srp.chasing.model.Product; +import com.coderising.ood.srp.chasing.model.User; +import com.coderising.ood.srp.chasing.service.MailService; +import com.coderising.ood.srp.chasing.service.ProductService; +import com.coderising.ood.srp.chasing.service.PromotionService; +import com.coderising.ood.srp.chasing.service.UserService; + +public class PromotionMail { + private MailService mailServer = new MailService(new Configuration());; + private ProductService productService = null; + private UserService userService = new UserService(); + private PromotionService promptService = new PromotionService(); + + public static void main(String[] args) throws Exception { + File f = new File("D:\\coding2017\\students\\282692248\\ood\\ood-assignment\\src\\main\\java\\com\\coderising\\ood\\srp\\chasing\\product_promotion.txt"); + PromotionMail pe = new PromotionMail(f); + pe.sendPromptMails(); + } + + public PromotionMail(File file){ + productService = new ProductService(file); + } + + /** 主要业务逻辑:发送促销信息 */ + protected void sendPromptMails() throws IOException { + System.out.println("开始发送邮件"); + Product product = productService.loadProduct(); + List users = userService.loadUserByProduct(product); + if (users != null) { + for(User user:users){ + mailServer.sendMail(user.getEmail(), promptService.getPromptProfile(), + promptService.buildPromptMessageForUser(product, user)); + } + } + else { + System.out.println("没有邮件发送"); + } + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/model/Product.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/model/Product.java new file mode 100644 index 0000000000..a4843a26c6 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/model/Product.java @@ -0,0 +1,27 @@ +package com.coderising.ood.srp.chasing.model; + +public class Product { + protected String productID = null; + protected String productDesc = null; + + public Product() {} + + public Product(String productID, String productDesc) { + super(); + this.productID = productID; + this.productDesc = productDesc; + } + + public String getProductID() { + return productID; + } + public void setProductID(String productID) { + this.productID = productID; + } + public String getProductDesc() { + return productDesc; + } + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/model/User.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/model/User.java new file mode 100644 index 0000000000..aed750d6ce --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/model/User.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp.chasing.model; + +public class User { + private String name; + private String email; + + public User(String name, String email) { + super(); + this.name = name; + this.email = email; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/product_promotion.txt b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/service/MailService.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/service/MailService.java new file mode 100644 index 0000000000..957eac2928 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/service/MailService.java @@ -0,0 +1,62 @@ +package com.coderising.ood.srp.chasing.service; + +import com.coderising.ood.srp.chasing.Configuration; +import com.coderising.ood.srp.chasing.ConfigurationKeys; +import com.coderising.ood.srp.chasing.util.MailUtil; + +public class MailService { + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String systemAddress = null; + + public MailService(Configuration config){ + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + systemAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + /** + * 发送邮件 + * @param toAddress 收信人 + * @param subject 主题 + * @param message 正文 + */ + public void sendMail(String toAddress, String subject, String message){ + if(toAddress == null || toAddress.length() <= 0){ + return; + } + try{ + MailUtil.sendEmail(toAddress, systemAddress, subject, message, smtpHost); + }catch(Exception e){ + try{ + MailUtil.sendEmail(toAddress, systemAddress, subject, message, altSmtpHost); + }catch(Exception e2){ + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + public String getSmtpHost() { + return smtpHost; + } + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + + public String getFromAddress() { + return systemAddress; + } + + public void setFromAddress(String fromAddress) { + this.systemAddress = fromAddress; + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/service/ProductService.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/service/ProductService.java new file mode 100644 index 0000000000..00e55a806b --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/service/ProductService.java @@ -0,0 +1,32 @@ +package com.coderising.ood.srp.chasing.service; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import com.coderising.ood.srp.chasing.model.Product; + +public class ProductService { + File f; + public ProductService(File f){ + this.f = f; + } + /** 获取促销商品 */ + public Product loadProduct() throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(f)); + String temp = br.readLine(); + String[] data = temp.split(" "); + System.out.println("产品ID = " + data[0] + "\n"); + System.out.println("产品描述 = " + data[1] + "\n"); + return new Product(data[0], data[1]); + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/service/PromotionService.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/service/PromotionService.java new file mode 100644 index 0000000000..a4f3aa0a12 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/service/PromotionService.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp.chasing.service; + +import java.io.IOException; + +import com.coderising.ood.srp.chasing.model.Product; +import com.coderising.ood.srp.chasing.model.User; + +public class PromotionService { + /** 促销信息概要 */ + public String getPromptProfile(){ + return "您关注的产品降价了"; + } + + /** 为指定用户生成促销信息 */ + public String buildPromptMessageForUser(Product product, User userInfo) throws IOException { + return "尊敬的 "+userInfo.getName()+", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!" ; + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/service/UserService.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/service/UserService.java new file mode 100644 index 0000000000..ccc8a44b31 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/service/UserService.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp.chasing.service; + +import java.util.List; + +import com.coderising.ood.srp.chasing.model.Product; +import com.coderising.ood.srp.chasing.model.User; +import com.coderising.ood.srp.chasing.util.DBUtil; + +public class UserService { + /** 获取关注指定商品的用户 */ + public List loadUserByProduct(Product product){ + String sql = "Select name from subscriptions " + + "where product_id= '" + product.getProductID() +"' " + + "and send_mail=1 "; + System.out.println("loadQuery set"); + return DBUtil.query(sql); + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/util/DBUtil.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/util/DBUtil.java new file mode 100644 index 0000000000..a1f5faf1f4 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/util/DBUtil.java @@ -0,0 +1,21 @@ +package com.coderising.ood.srp.chasing.util; +import java.util.ArrayList; +import java.util.List; + +import com.coderising.ood.srp.chasing.model.User; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + List userList = new ArrayList<>(); + for (int i = 1; i <= 3; i++) { + userList.add(new User("User" + i,"aa@bb.com")); + } + return userList; + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/util/MailUtil.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/util/MailUtil.java new file mode 100644 index 0000000000..6bc230b7bb --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/chasing/util/MailUtil.java @@ -0,0 +1,14 @@ +package com.coderising.ood.srp.chasing.util; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/Affiliation.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/Affiliation.java new file mode 100644 index 0000000000..091165a2af --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/Affiliation.java @@ -0,0 +1,5 @@ +package com.coderising.payroll; + +public interface Affiliation { + public double calculateDeductions(Paycheck pc); +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/BankMethod.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/BankMethod.java new file mode 100644 index 0000000000..a7b0dd9436 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/BankMethod.java @@ -0,0 +1,8 @@ +package com.coderising.payroll; + +public class BankMethod implements PaymentMethod{ + private String account; + public void pay(Paycheck pc){ + System.out.println("转到银行账号:"+account+"。备注:"+pc); + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/BiWeeklySchedule.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/BiWeeklySchedule.java new file mode 100644 index 0000000000..943b4ae757 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/BiWeeklySchedule.java @@ -0,0 +1,18 @@ +package com.coderising.payroll; + +import java.util.Date; + +public class BiWeeklySchedule implements PaymentSchedule{ + private Date firstPayDay; + public BiWeeklySchedule(String firstPayDay){ + this.firstPayDay = DateUtil.parseDate(firstPayDay); + } + + public boolean isPayDate(Date date){ + return DateUtil.getDaysBetween(firstPayDay, date)%14 == 0; + } + + public Date getPayPeriodStartDate( Date payPeriodEndDate){ + return DateUtil.add(payPeriodEndDate, -13); + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/ComissionClassification.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/ComissionClassification.java new file mode 100644 index 0000000000..e8ef651b11 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/ComissionClassification.java @@ -0,0 +1,28 @@ +package com.coderising.payroll; + +import java.util.ArrayList; +import java.util.List; + +public class ComissionClassification implements PaymentClassification { + private double salary; + private double rate; + List receipts = new ArrayList<>(); + + public ComissionClassification(double salary, double rate, List receipts) { + super(); + this.salary = salary; + this.rate = rate; + this.receipts = receipts; + } + + + public double calculatePay(Paycheck pc){ + double totalAmount = 0.0; + for(SalesReceipt sr:receipts){ + if(DateUtil.between(sr.getSaleDate(),pc.getPayPeriodStartDate(), pc.getPayPeriodEndDate())){ + totalAmount += sr.getAmount(); + } + } + return salary + totalAmount*rate; + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/DateUtil.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/DateUtil.java new file mode 100644 index 0000000000..0b2c6aad54 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/DateUtil.java @@ -0,0 +1,99 @@ +package com.coderising.payroll; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +public class DateUtil { + public static final long SECOND_IN_MS = 1000L; + public static final long MINUTE_IN_S = 60L; + public static final long HOUR_IN_MINUTE = 60L; + public static final long DAY_IN_HOUR = 24L; + public static final long DAY_IN_MS = DAY_IN_HOUR*HOUR_IN_MINUTE*MINUTE_IN_S*SECOND_IN_MS; + private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + + public static boolean isFriday(Date date){ + Calendar calendar = new GregorianCalendar(); + calendar.setTime(date); + return calendar.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY; + } + + public static int getDaysBetween(Date beginDate, Date endDate){ + assert(endDate.after(beginDate)); + return (int)((endDate.getTime() - beginDate.getTime())/DAY_IN_MS); + } + + public static Date parseDate(String strDate){ + try{ + return sdf.parse(strDate); + } + catch(ParseException e){ + throw new RuntimeException(e); + } + } + + public static Date add(Date date, int dayCount){ + Calendar calendar = new GregorianCalendar(); + calendar.setTime(date); + calendar.add(Calendar.DATE, dayCount); + return calendar.getTime(); + } + + /** + * 判断当前日期是否是当月最后一个工作日 + * true: 当前日期是工作日并且与下一工作日不同月 + * */ + public static boolean isLastWorkDayOfMonth(Date d){ + if(isWeekday(d)){ + Date nextWeekday = nextWeekday(d); + Calendar calendar = new GregorianCalendar(); + calendar.setTime(d); + int mouth = calendar.get(Calendar.MONTH); + calendar.setTime(nextWeekday); + return mouth != calendar.get(Calendar.MONTH); + } + return false; + } + + public static boolean isWeekday(Date d){ + Calendar calendar = new GregorianCalendar(); + calendar.setTime(d); + int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); + return Calendar.MONDAY <= dayOfWeek && dayOfWeek <= Calendar.FRIDAY; + } + + public static Date nextWeekday(Date d){ + Calendar calendar = new GregorianCalendar(); + calendar.setTime(d); + int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); + switch (dayOfWeek) { + case Calendar.FRIDAY: + calendar.add(Calendar.DATE, 3); + break; + case Calendar.SATURDAY: + calendar.add(Calendar.DATE, 2); + break; + default: + calendar.add(Calendar.DATE, 1); + break; + } + return calendar.getTime(); + } + + public static Date getFirstDayOfMonth(Date d){ + Calendar calendar = new GregorianCalendar(); + calendar.setTime(d); + calendar.set(Calendar.DAY_OF_MONTH, 1); + return calendar.getTime(); + } + + public static boolean between(Date d, Date startDate, Date endDate){ + return d.compareTo(startDate)>=0 && d.compareTo(endDate)<=0; + } + + public static String format(Date d){ + return sdf.format(d); + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/Employee.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/Employee.java new file mode 100644 index 0000000000..75fbc04ddf --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/Employee.java @@ -0,0 +1,56 @@ +package com.coderising.payroll; + +import java.util.Date; + +public class Employee { + String id; + String name; + String address; + Affiliation affiliation = new NonAffiliation(); + + + PaymentClassification classification; + PaymentSchedule schedule; + PaymentMethod paymentMethod; + + public Employee(String id, String name, String address){ + this.id = id; + this.name = name; + this.address = address; + } + public boolean isPayDay(Date d) { + return schedule.isPayDate(d); + } + + public Date getPayPeriodStartDate(Date d) { + return schedule.getPayPeriodStartDate(d); + } + + public void payDay(Paycheck pc){ + double grossPay = classification.calculatePay(pc); + double deductions = affiliation.calculateDeductions(pc); + double netPay = grossPay - deductions; + pc.setGrossPay(grossPay); + pc.setDeductions(deductions); + pc.setNetPay(netPay); + this.paymentMethod.pay(pc); + } + + public void setClassification(PaymentClassification classification) { + this.classification = classification; + } + public void setSchedule(PaymentSchedule schedule) { + this.schedule = schedule; + } + public void setPaymentMethod(PaymentMethod paymentMethod) { + this.paymentMethod = paymentMethod; + } + public void setAffiliation(Affiliation affiliation) { + this.affiliation = affiliation; + } + @Override + public String toString() { + return "Employee [id=" + id + ", name=" + name + ", address=" + address + "]"; + } +} + diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/HoldMethod.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/HoldMethod.java new file mode 100644 index 0000000000..d1f4b48a4d --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/HoldMethod.java @@ -0,0 +1,7 @@ +package com.coderising.payroll; + +public class HoldMethod implements PaymentMethod{ + public void pay(Paycheck pc){ + System.out.println("转到财务处:"+pc); + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/HourlyClassification.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/HourlyClassification.java new file mode 100644 index 0000000000..9cdce41184 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/HourlyClassification.java @@ -0,0 +1,40 @@ +package com.coderising.payroll; + +import java.util.ArrayList; +import java.util.List; + +public class HourlyClassification implements PaymentClassification{ + private double hourlyRate; + private List timeCards = new ArrayList<>(); + + public HourlyClassification(double hourlyRate, List timeCards) { + super(); + this.hourlyRate = hourlyRate; + this.timeCards = timeCards; + } + + public double getHourlyRate() { + return hourlyRate; + } + + public void setHourlyRate(double hourlyRate) { + this.hourlyRate = hourlyRate; + } + + public double calculatePay(Paycheck pc){ + double salary = 0.0; + for(TimeCard tc:timeCards){ + if(DateUtil.between(tc.getDate(), pc.getPayPeriodStartDate(), pc.getPayPeriodEndDate())){ + salary += calculatePayForTimeCard(tc); + } + } + return salary; + } + + private double calculatePayForTimeCard(TimeCard tc){ + if(tc.getHours() > 8){ + return 8*hourlyRate + (tc.getHours()-8)*1.5*hourlyRate; + } + return tc.getHours()*hourlyRate; + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/MailMethod.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/MailMethod.java new file mode 100644 index 0000000000..19e59fa512 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/MailMethod.java @@ -0,0 +1,8 @@ +package com.coderising.payroll; + +public class MailMethod implements PaymentMethod{ + private String address; + public void pay(Paycheck pc){ + System.out.println("邮寄到:"+address+"。备注:"+pc); + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/MonthlySchedule.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/MonthlySchedule.java new file mode 100644 index 0000000000..86f9b7e21c --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/MonthlySchedule.java @@ -0,0 +1,13 @@ +package com.coderising.payroll; + +import java.util.Date; + +public class MonthlySchedule implements PaymentSchedule{ + public boolean isPayDate(Date date){ + return DateUtil.isLastWorkDayOfMonth(date); + } + + public Date getPayPeriodStartDate( Date payPeriodEndDate){ + return DateUtil.getFirstDayOfMonth(payPeriodEndDate); + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/NonAffiliation.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/NonAffiliation.java new file mode 100644 index 0000000000..31129fbab4 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/NonAffiliation.java @@ -0,0 +1,7 @@ +package com.coderising.payroll; + +public class NonAffiliation implements Affiliation{ + public double calculateDeductions(Paycheck pc){ + return 0.0; + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/Paycheck.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/Paycheck.java new file mode 100644 index 0000000000..81af0d4d66 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/Paycheck.java @@ -0,0 +1,41 @@ +package com.coderising.payroll; + +import java.util.Date; + +public class Paycheck { + private Date payPeriodStart; + private Date payPeriodEnd; + private double grossPay; + private double netPay; + private double deductions; + + public Paycheck(Date payPeriodStart, Date payPeriodEnd){ + this.payPeriodStart = payPeriodStart; + this.payPeriodEnd = payPeriodEnd; + } + public void setGrossPay(double grossPay) { + this.grossPay = grossPay; + + } + public void setDeductions(double deductions) { + this.deductions = deductions; + } + public void setNetPay(double netPay){ + this.netPay = netPay; + } + public Date getPayPeriodEndDate() { + + return this.payPeriodEnd; + } + public Date getPayPeriodStartDate() { + + return this.payPeriodStart; + } + @Override + public String toString() { + return "[开始时间=" + DateUtil.format(payPeriodStart) + ", 结束时间=" + DateUtil.format(payPeriodEnd) + ", 应发=" + + grossPay + ", 扣款=" + deductions + ", 实发=" + netPay + "]"; + } + + +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/PaymentClassification.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/PaymentClassification.java new file mode 100644 index 0000000000..f2bf2e26e9 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/PaymentClassification.java @@ -0,0 +1,5 @@ +package com.coderising.payroll; + +public interface PaymentClassification { + public double calculatePay(Paycheck pc); +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/PaymentMethod.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/PaymentMethod.java new file mode 100644 index 0000000000..5e549916b6 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/PaymentMethod.java @@ -0,0 +1,5 @@ +package com.coderising.payroll; + +public interface PaymentMethod { + public void pay(Paycheck pc); +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/PaymentSchedule.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/PaymentSchedule.java new file mode 100644 index 0000000000..500d72404d --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/PaymentSchedule.java @@ -0,0 +1,8 @@ +package com.coderising.payroll; + +import java.util.Date; + +public interface PaymentSchedule { + public boolean isPayDate(Date date); + public Date getPayPeriodStartDate( Date payPeriodEndDate); +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/SalariedClassification.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/SalariedClassification.java new file mode 100644 index 0000000000..d7c556405e --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/SalariedClassification.java @@ -0,0 +1,14 @@ +package com.coderising.payroll; + +public class SalariedClassification implements PaymentClassification { + private double salary; + + public SalariedClassification(double salary) { + super(); + this.salary = salary; + } + + public double calculatePay(Paycheck pc){ + return salary; + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/SalesReceipt.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/SalesReceipt.java new file mode 100644 index 0000000000..18297d3fc5 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/SalesReceipt.java @@ -0,0 +1,21 @@ +package com.coderising.payroll; + +import java.util.Date; + +public class SalesReceipt { + private Date saleDate; + private double amount; + + + public SalesReceipt(Date saleDate, double amount) { + super(); + this.saleDate = saleDate; + this.amount = amount; + } + public Date getSaleDate() { + return saleDate; + } + public double getAmount() { + return amount; + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/TimeCard.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/TimeCard.java new file mode 100644 index 0000000000..2aadeabb48 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/TimeCard.java @@ -0,0 +1,19 @@ +package com.coderising.payroll; + +import java.util.Date; + +public class TimeCard { + private Date date; + private int hours; + + public TimeCard(Date date, int hours){ + this.date = date; + this.hours = hours; + } + public Date getDate() { + return date; + } + public int getHours() { + return hours; + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/UnionAffiliation.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/UnionAffiliation.java new file mode 100644 index 0000000000..c9021baf0f --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/UnionAffiliation.java @@ -0,0 +1,17 @@ +package com.coderising.payroll; + +public class UnionAffiliation implements Affiliation{ + private String memberId; + private double weeklyDue; + + public UnionAffiliation(double weeklyDue) { + super(); + this.weeklyDue = weeklyDue; + } + + public double calculateDeductions(Paycheck pc){ + //简单实现 + int dayCount = DateUtil.getDaysBetween(pc.getPayPeriodStartDate(), pc.getPayPeriodEndDate()); + return (dayCount+1)/7 * weeklyDue; + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/WeeklySchedule.java b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/WeeklySchedule.java new file mode 100644 index 0000000000..b9788bd18a --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/java/com/coderising/payroll/WeeklySchedule.java @@ -0,0 +1,12 @@ +package com.coderising.payroll; + +import java.util.Date; + +public class WeeklySchedule implements PaymentSchedule{ + public boolean isPayDate(Date date){ + return DateUtil.isFriday(date); + } + public Date getPayPeriodStartDate( Date payPeriodEndDate){ + return DateUtil.add(payPeriodEndDate, -6); + } +} diff --git a/students/282692248/ood/ood-assignment/src/main/resources/employees.txt b/students/282692248/ood/ood-assignment/src/main/resources/employees.txt new file mode 100644 index 0000000000..6f2535dd25 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/resources/employees.txt @@ -0,0 +1,9 @@ +1 jerry china hourly 0.0 20.0 +2 tom usa hourly 0.0 30.0 +3 herry china hourly 0.0 25.0 +4 lily uk comission 1000.0 0.01 +5 merry china comission 1200.0 0.02 +6 lida japan comission 800.0 0.01 +7 kerry china salaried 5000.0 0.0 +8 jemmy japan salaried 8000.0 0.0 +9 jim usa salaried 7500.0 0.0 \ No newline at end of file diff --git a/students/282692248/ood/ood-assignment/src/main/resources/salesreceipt.txt b/students/282692248/ood/ood-assignment/src/main/resources/salesreceipt.txt new file mode 100644 index 0000000000..c9105f4a20 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/resources/salesreceipt.txt @@ -0,0 +1,9 @@ +2017-06-30 4 3000.0 +2017-07-11 4 5000.0 +2017-07-14 4 4000.0 +2017-06-29 5 2000.0 +2017-07-02 5 3000.0 +2017-07-15 5 3000.0 +2017-07-01 6 4000.0 +2017-07-08 6 3000.0 +2017-07-16 6 2000.0 \ No newline at end of file diff --git a/students/282692248/ood/ood-assignment/src/main/resources/timecard.txt b/students/282692248/ood/ood-assignment/src/main/resources/timecard.txt new file mode 100644 index 0000000000..995a2d20d5 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/resources/timecard.txt @@ -0,0 +1,9 @@ +2017-07-07 1 9 +2017-07-11 1 7 +2017-07-14 1 5 +2017-07-08 2 10 +2017-07-13 2 6 +2017-07-15 2 7 +2017-07-12 3 9 +2017-07-14 3 9 +2017-07-16 3 9 \ No newline at end of file diff --git a/students/282692248/ood/ood-assignment/src/main/resources/union.txt b/students/282692248/ood/ood-assignment/src/main/resources/union.txt new file mode 100644 index 0000000000..c15a30d749 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/main/resources/union.txt @@ -0,0 +1,4 @@ +1 +5 +7 +9 \ No newline at end of file diff --git a/students/282692248/ood/ood-assignment/src/test/java/com/coderising/payroll/EmployeeTest.java b/students/282692248/ood/ood-assignment/src/test/java/com/coderising/payroll/EmployeeTest.java new file mode 100644 index 0000000000..2bd6757ae2 --- /dev/null +++ b/students/282692248/ood/ood-assignment/src/test/java/com/coderising/payroll/EmployeeTest.java @@ -0,0 +1,119 @@ +package com.coderising.payroll; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.Test; + +public class EmployeeTest { + + @Test + public void test() throws Exception{ + Date d = DateUtil.parseDate("2017-07-31"); + List employeeList = loadEmployees(); + for(Employee e:employeeList){ + if(e.isPayDay(d)){ + Paycheck pc = new Paycheck(e.getPayPeriodStartDate(d), d); + System.out.println("发工资--> "+e); + e.payDay(pc); + } + } + } + + private List loadEmployees()throws Exception{ + List employees = new ArrayList<>(); + Set unioners = loadUnionIds(); + UnionAffiliation ua = new UnionAffiliation(5.0); + Map> tcMap = loadTimeCard(); + Map> srMap = loadSalyReceipt(); + String employeesFileName = "D:\\coding2017\\students\\282692248\\ood\\ood-assignment\\src\\main\\resources\\employees.txt"; + BufferedReader br = new BufferedReader(new FileReader(employeesFileName)); + String line = null;//id name address type salary rate + while( (line = br.readLine()) != null ){ + String[] fileds = line.split("\t"); + String id = fileds[0]; + Employee employee = new Employee(id,fileds[1], fileds[2]); + switch (fileds[3]) { + case "hourly": + employee.setClassification(new HourlyClassification(Double.parseDouble(fileds[5]),tcMap.get(id))); + employee.setSchedule(new WeeklySchedule()); + break; + case "comission": + employee.setClassification(new ComissionClassification(Double.parseDouble(fileds[4]), + Double.parseDouble(fileds[5]), srMap.get(id))); + employee.setSchedule(new BiWeeklySchedule("2017-05-05")); + break; + case "salaried": + employee.setClassification(new SalariedClassification(Double.parseDouble(fileds[4]))); + employee.setSchedule(new MonthlySchedule()); + break; + default: + throw new RuntimeException("unkonwn type ["+fileds[3]+"]"); + } + employee.setPaymentMethod(new HoldMethod()); + if(unioners.contains(id)){ + employee.setAffiliation(ua); + } + employees.add(employee); + } + br.close(); + return employees; + } + + private Set loadUnionIds() throws Exception{ + Set unioners = new HashSet<>(); + String unionFileName = "D:\\coding2017\\students\\282692248\\ood\\ood-assignment\\src\\main\\resources\\union.txt"; + BufferedReader br = new BufferedReader(new FileReader(unionFileName)); + String line = null; + while( (line = br.readLine()) != null ){ + unioners.add(line); + } + br.close(); + return unioners; + } + + private Map> loadTimeCard() throws Exception{ + Map> result = new HashMap<>(); + String timecardFileName = "D:\\coding2017\\students\\282692248\\ood\\ood-assignment\\src\\main\\resources\\timecard.txt"; + BufferedReader br = new BufferedReader(new FileReader(timecardFileName)); + String line = null; + while( (line = br.readLine()) != null ){//date id hours + String[] fields = line.split("\t"); + TimeCard tc = new TimeCard(DateUtil.parseDate(fields[0]),Integer.parseInt(fields[2])); + List tcList = result.get(fields[1]); + if(tcList == null){ + tcList = new ArrayList<>(); + result.put(fields[1], tcList); + } + tcList.add(tc); + } + br.close(); + return result; + } + + private Map> loadSalyReceipt() throws Exception{ + Map> result = new HashMap<>(); + String receiptFileName = "D:\\coding2017\\students\\282692248\\ood\\ood-assignment\\src\\main\\resources\\salesreceipt.txt"; + BufferedReader br = new BufferedReader(new FileReader(receiptFileName)); + String line = null; + while( (line = br.readLine()) != null ){//date id amount + String[] fields = line.split("\t"); + SalesReceipt sr = new SalesReceipt(DateUtil.parseDate(fields[0]),Double.parseDouble(fields[2])); + List srList = result.get(fields[1]); + if(srList == null){ + srList = new ArrayList<>(); + result.put(fields[1], srList); + } + srList.add(sr); + } + br.close(); + return result; + } +} diff --git a/students/2831099157/ood-assignment/out/production/main/com/coderising/ood/srp/product_promotion.txt b/students/2831099157/ood-assignment/out/production/main/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/2831099157/ood-assignment/out/production/main/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/2831099157/ood-assignment/pom.xml b/students/2831099157/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/2831099157/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java new file mode 100644 index 0000000000..cd49152e09 --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java @@ -0,0 +1,20 @@ +package com.coderising.ood.ocp; + +import com.coderising.ood.ocp.formatter.Formatter; +import com.coderising.ood.ocp.sender.Sender; + +public class Logger { + private Formatter formatter; + private Sender sender; + + public Logger(Formatter formatter,Sender sender){ + this.formatter = formatter; + this.sender = sender; + } + public void log(String msg){ + sender.send(formatter.format(msg)) ; + } + + +} + diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/MainTest.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/MainTest.java new file mode 100644 index 0000000000..cfa756a14e --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/MainTest.java @@ -0,0 +1,20 @@ +package com.coderising.ood.ocp; + +import com.coderising.ood.ocp.formatter.FormatterFactory; +import com.coderising.ood.ocp.sender.SenderFactory; + +/** + * Created by Iden on 2017/6/21. + */ +public class MainTest { + public static void main(String[] args) { + + Logger logger = new Logger(FormatterFactory.createFormatter(FormatterFactory.ONLY_STRING), + SenderFactory.createSender(SenderFactory.ENAIL)); + logger.log("Messge 1"); + + Logger logger2 = new Logger(FormatterFactory.createFormatter(FormatterFactory.WITH_CURRENT_DATA), + SenderFactory.createSender(SenderFactory.SMS)); + logger2.log("Messge 2"); + } +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/Formatter.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/Formatter.java new file mode 100644 index 0000000000..aee4b86da5 --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/Formatter.java @@ -0,0 +1,9 @@ +package com.coderising.ood.ocp.formatter; + +/** + * Created by Iden on 2017/6/21. + */ +public interface Formatter { + + String format(String msg); +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/FormatterFactory.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/FormatterFactory.java new file mode 100644 index 0000000000..8a1b99fe6a --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/FormatterFactory.java @@ -0,0 +1,21 @@ +package com.coderising.ood.ocp.formatter; + +/** + * Created by Iden on 2017/6/21. + */ +public class FormatterFactory { + + public static final int ONLY_STRING = 1; + public static final int WITH_CURRENT_DATA = 2; + + public static Formatter createFormatter(int type) { + if (type == ONLY_STRING) { + return new OnlyStringFormatter(); + } + if (type == WITH_CURRENT_DATA) { + return new WithCurrentDateFormatter(); + } + return null; + } + +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/OnlyStringFormatter.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/OnlyStringFormatter.java new file mode 100644 index 0000000000..312a2c8d90 --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/OnlyStringFormatter.java @@ -0,0 +1,12 @@ +package com.coderising.ood.ocp.formatter; + +/** + * Created by Iden on 2017/6/21. + */ +public class OnlyStringFormatter implements Formatter{ + + @Override + public String format(String msg) { + return msg; + } +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/WithCurrentDateFormatter.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/WithCurrentDateFormatter.java new file mode 100644 index 0000000000..bec30c2b15 --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/WithCurrentDateFormatter.java @@ -0,0 +1,16 @@ +package com.coderising.ood.ocp.formatter; + +import com.coderising.ood.ocp.utils.DateUtil; + +/** + * Created by Iden on 2017/6/21. + */ +public class WithCurrentDateFormatter implements Formatter{ + + @Override + public String format(String msg) { + String txtDate = DateUtil.getCurrentDateAsString(); + String logMsg = txtDate + ": " + msg; + return logMsg; + } +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/sender/EmailSender.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/sender/EmailSender.java new file mode 100644 index 0000000000..921003ba6f --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/sender/EmailSender.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp.sender; + +/** + * Created by Iden on 2017/6/21. + */ +public class EmailSender implements Sender { + @Override + public void send(String msg) { + System.out.println("Email发送,内容为:"+msg); + } +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/sender/PrintSender.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/sender/PrintSender.java new file mode 100644 index 0000000000..af3ce1dc57 --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/sender/PrintSender.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp.sender; + +/** + * Created by Iden on 2017/6/21. + */ +public class PrintSender implements Sender { + @Override + public void send(String msg) { + System.out.println("Print发送,内容为:"+msg); + } +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/sender/SMSSender.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/sender/SMSSender.java new file mode 100644 index 0000000000..6dabed6969 --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/sender/SMSSender.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp.sender; + +/** + * Created by Iden on 2017/6/21. + */ +public class SMSSender implements Sender { + @Override + public void send(String msg) { + System.out.println("SMS发送,内容为:"+ msg); + } +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/sender/Sender.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/sender/Sender.java new file mode 100644 index 0000000000..7187f23f6a --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/sender/Sender.java @@ -0,0 +1,9 @@ +package com.coderising.ood.ocp.sender; + +/** + * Created by Iden on 2017/6/21. + */ +public interface Sender { + + void send(String msg); +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/sender/SenderFactory.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/sender/SenderFactory.java new file mode 100644 index 0000000000..ff2346ce58 --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/sender/SenderFactory.java @@ -0,0 +1,30 @@ +package com.coderising.ood.ocp.sender; + +import com.coderising.ood.ocp.formatter.Formatter; +import com.coderising.ood.ocp.formatter.OnlyStringFormatter; +import com.coderising.ood.ocp.formatter.WithCurrentDateFormatter; + +/** + * Created by Iden on 2017/6/21. + */ +public class SenderFactory { + + public static final int ENAIL = 1; + public static final int SMS = 2; + public static final int PRINT = 3; + + + public static Sender createSender(int type) { + if (type == ENAIL) { + return new EmailSender(); + } + if (type == SMS) { + return new SMSSender(); + } + if (type == PRINT) { + return new PrintSender(); + } + return null; + } + +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/utils/DateUtil.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/utils/DateUtil.java new file mode 100644 index 0000000000..4b1cf6c78d --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/utils/DateUtil.java @@ -0,0 +1,13 @@ +package com.coderising.ood.ocp.utils; + +import java.text.SimpleDateFormat; +import java.util.Date; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return SimpleDateFormat.getInstance().format(new Date()); + } + +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/utils/MailUtil.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/utils/MailUtil.java new file mode 100644 index 0000000000..7214e763b5 --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/utils/MailUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp.utils; + +public class MailUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/utils/SMSUtil.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/utils/SMSUtil.java new file mode 100644 index 0000000000..d59b7e6644 --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/ocp/utils/SMSUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp.utils; + +public class SMSUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..9eb1b21f29 --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,21 @@ +package com.coderising.ood.srp; + +import com.coderising.ood.srp.service.GoodsArrivalNotice; +import com.coderising.ood.srp.service.Notice; + +/** + * 可以根据不同运营方案,添加GetProductsFunction,SendMailFunction接口实现类及Notice子类,向订阅者发送通告 + */ +public class PromotionMail { + + public static void main(String[] args) throws Exception { + //降价促销 +// Notice notice = new PricePromotion(); + //到货通知 + Notice notice = new GoodsArrivalNotice(); + notice.sendMail(notice.getProducts()); + + } + + +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/configure/Configuration.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/configure/Configuration.java new file mode 100644 index 0000000000..5c0697782a --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/configure/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp.configure; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/configure/ConfigurationKeys.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/configure/ConfigurationKeys.java new file mode 100644 index 0000000000..c9cfba4974 --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/configure/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp.configure; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/dao/DBUtil.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/dao/DBUtil.java new file mode 100644 index 0000000000..c0e7f6508d --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/dao/DBUtil.java @@ -0,0 +1,27 @@ +package com.coderising.ood.srp.dao; +import com.coderising.ood.srp.model.User; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + User user = new User(); + user.setName("User" + i); + user.seteMail("aa@bb.com"); + userList.add(user); + } + + return userList; + } +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/interfaces/GetProductsFunction.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/interfaces/GetProductsFunction.java new file mode 100644 index 0000000000..f0894ea3c7 --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/interfaces/GetProductsFunction.java @@ -0,0 +1,13 @@ +package com.coderising.ood.srp.interfaces; + +import com.coderising.ood.srp.model.Product; + +import java.util.List; + +/** + * Created by Iden on 2017/6/14. + */ +public interface GetProductsFunction { + + List getProducts(); +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/interfaces/SendMailFunction.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/interfaces/SendMailFunction.java new file mode 100644 index 0000000000..cd27a45767 --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/interfaces/SendMailFunction.java @@ -0,0 +1,13 @@ +package com.coderising.ood.srp.interfaces; + +import com.coderising.ood.srp.model.Product; + +import java.util.List; + +/** + * Created by Iden on 2017/6/14. + */ +public interface SendMailFunction { + + void sendMail(List products); +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/model/Mail.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/model/Mail.java new file mode 100644 index 0000000000..b94f27b29d --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/model/Mail.java @@ -0,0 +1,112 @@ +package com.coderising.ood.srp.model; + +import com.coderising.ood.srp.configure.Configuration; +import com.coderising.ood.srp.configure.ConfigurationKeys; + +/** + * Created by Iden on 2017/6/14. + */ +public class Mail { + private String fromAddress; + private String toAddress; + private String subject; + private String content; + private String smtpHost = null; + private String altSmtpHost = null; + + public Mail() { + Configuration config = new Configuration(); + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + + public String getSmtpHost() { + return smtpHost; + } + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + + + public void send() { + if(null==toAddress){ + System.out.println("发送地址不能为空"); + return; + } + try { + sendMailBySmtpHost(); + } catch (Exception e) { + try { + sendMailBySmtpHost(); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + + } + } + + private void sendMailBySmtpHost() { + System.out.println("通过SMTP服务器开始发送邮件"); + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(content).append("\n"); + System.out.println(buffer.toString()); + } + + private void sendMailByAlSmtpHost() { + System.out.println("通过备用SMTP服务器开始发送邮件"); + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(content).append("\n"); + System.out.println(buffer.toString()); + } +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/model/Product.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/model/Product.java new file mode 100644 index 0000000000..f9f5b5a145 --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/model/Product.java @@ -0,0 +1,46 @@ +package com.coderising.ood.srp.model; + +import com.coderising.ood.srp.dao.DBUtil; + +import java.util.List; + +/** + * Created by Iden on 2017/6/14. + */ +public class Product { + String id; + String description; + + public Product(String id, String descript) { + this.id = id; + this.description = descript; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public List getSubscribers() { + List userList = null; + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + id + "' " + + "and send_mail=1 "; + userList = DBUtil.query(sendMailQuery); + return userList; + + } + + +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/model/User.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/model/User.java new file mode 100644 index 0000000000..38bec29f59 --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/model/User.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp.model; + +/** + * Created by Iden on 2017/6/14. + */ +public class User { + String name; + String eMail; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String geteMail() { + return eMail; + } + + public void seteMail(String eMail) { + this.eMail = eMail; + } +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/service/GetProductsFromFile.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/service/GetProductsFromFile.java new file mode 100644 index 0000000000..92a1090c5e --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/service/GetProductsFromFile.java @@ -0,0 +1,47 @@ +package com.coderising.ood.srp.service; + +import com.coderising.ood.srp.interfaces.GetProductsFunction; +import com.coderising.ood.srp.model.Product; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Created by Iden on 2017/6/14. + */ +public class GetProductsFromFile implements GetProductsFunction { + public String filePath = "E:\\StudyProjects\\Java\\Workspace\\HomeWork\\coding2017\\liuxin\\ood\\ood-assignment\\" + + "src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"; + + @Override + public List getProducts() { + BufferedReader br = null; + List products = new ArrayList<>(); + try { + File file = new File(filePath); + br = new BufferedReader(new FileReader(file)); + String temp = null; + while ((temp = br.readLine()) != null) { + String[] data = temp.split(" "); + Product product = new Product(data[0], data[1]); + System.out.println("促销产品ID = " + product.getId()); + System.out.println("促销产品描述 = " + product.getDescription()); + products.add(product); + } + + } catch (IOException e) { + System.out.println("读取文件失败"); + } finally { + try { + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return products; + } +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/service/GoodsArrivalNotice.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/service/GoodsArrivalNotice.java new file mode 100644 index 0000000000..ee4723ec06 --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/service/GoodsArrivalNotice.java @@ -0,0 +1,13 @@ +package com.coderising.ood.srp.service; + +/** + * Created by Iden on 2017/6/14. + * 到货通知 + */ +public class GoodsArrivalNotice extends Notice { + public GoodsArrivalNotice() { + getProductsFunction = new GetProductsFromFile(); + sendMailFunction = new SendGoodsArrivalMail(); + } + +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/service/Notice.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/service/Notice.java new file mode 100644 index 0000000000..6ac8e62402 --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/service/Notice.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp.service; + +import com.coderising.ood.srp.interfaces.GetProductsFunction; +import com.coderising.ood.srp.interfaces.SendMailFunction; +import com.coderising.ood.srp.model.Product; + +import java.util.List; + +/** + * Created by Iden on 2017/6/14. + * 各类通知(降价促销,抢购活动,到货通知等等) + */ +public abstract class Notice { + GetProductsFunction getProductsFunction; + SendMailFunction sendMailFunction; + + public List getProducts() { + return getProductsFunction.getProducts(); + } + + public void sendMail(List products) { + sendMailFunction.sendMail(products); + } + +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/service/PricePromotion.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/service/PricePromotion.java new file mode 100644 index 0000000000..ebb59571c0 --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/service/PricePromotion.java @@ -0,0 +1,12 @@ +package com.coderising.ood.srp.service; + +/** + * Created by Iden on 2017/6/14. + */ +public class PricePromotion extends Notice { + public PricePromotion() { + getProductsFunction = new GetProductsFromFile(); + sendMailFunction = new SendPriceMail(); + } + +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/service/SendGoodsArrivalMail.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/service/SendGoodsArrivalMail.java new file mode 100644 index 0000000000..79f3a6985f --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/service/SendGoodsArrivalMail.java @@ -0,0 +1,42 @@ +package com.coderising.ood.srp.service; + +import com.coderising.ood.srp.interfaces.SendMailFunction; +import com.coderising.ood.srp.model.Mail; +import com.coderising.ood.srp.model.Product; +import com.coderising.ood.srp.model.User; + +import java.util.Iterator; +import java.util.List; + +/** + * Created by Iden on 2017/6/14. + */ +public class SendGoodsArrivalMail implements SendMailFunction { + + + @Override + public void sendMail(List products) { + if (null == products || products.size() == 0) { + System.out.println("没有发现到货的产品"); + return; + } + Iterator iterator = products.iterator(); + while (iterator.hasNext()) { + Product product = iterator.next(); + List userList = product.getSubscribers(); + if (null == userList || userList.size() == 0) { + System.out.println("没有人订阅" + product.getDescription() + " 信息"); + continue; + } + Iterator iter = userList.iterator(); + while (iter.hasNext()) { + User user = (User) iter.next(); + Mail mail = new Mail(); + mail.setSubject("您关注的产品到货了"); + mail.setContent("尊敬的 " + user.getName() + ", 您关注的产品 " + product.getDescription() + " 到货了,欢迎购买"); + mail.setToAddress(user.geteMail()); + mail.send(); + } + } + } +} diff --git a/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/service/SendPriceMail.java b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/service/SendPriceMail.java new file mode 100644 index 0000000000..bae4803e3f --- /dev/null +++ b/students/2831099157/ood-assignment/src/main/java/com/coderising/ood/srp/service/SendPriceMail.java @@ -0,0 +1,42 @@ +package com.coderising.ood.srp.service; + +import com.coderising.ood.srp.interfaces.SendMailFunction; +import com.coderising.ood.srp.model.Mail; +import com.coderising.ood.srp.model.Product; +import com.coderising.ood.srp.model.User; + +import java.util.Iterator; +import java.util.List; + +/** + * Created by Iden on 2017/6/14. + */ +public class SendPriceMail implements SendMailFunction { + + + @Override + public void sendMail(List products) { + if (null == products || products.size() == 0) { + System.out.println("没有发现需要促销的产品"); + return; + } + Iterator iterator = products.iterator(); + while (iterator.hasNext()) { + Product product = iterator.next(); + List userList = product.getSubscribers(); + if (null == userList || userList.size() == 0) { + System.out.println("没有人订阅 " + product.getDescription() + " 信息"); + continue; + } + Iterator iter = userList.iterator(); + while (iter.hasNext()) { + User user = (User) iter.next(); + Mail mail = new Mail(); + mail.setSubject("您关注的产品降价了"); + mail.setContent("尊敬的 " + user.getName() + ", 您关注的产品 " + product.getDescription() + " 降价了,欢迎购买"); + mail.setToAddress(user.geteMail()); + mail.send(); + } + } + } +} diff --git "a/students/2831099157/ood-assignment/\344\277\203\351\224\200Mail\345\217\221\351\200\201\347\273\203\344\271\240\357\274\210\351\207\215\346\236\204\357\274\211.md" "b/students/2831099157/ood-assignment/\344\277\203\351\224\200Mail\345\217\221\351\200\201\347\273\203\344\271\240\357\274\210\351\207\215\346\236\204\357\274\211.md" new file mode 100644 index 0000000000..33634cb9a9 --- /dev/null +++ "b/students/2831099157/ood-assignment/\344\277\203\351\224\200Mail\345\217\221\351\200\201\347\273\203\344\271\240\357\274\210\351\207\215\346\236\204\357\274\211.md" @@ -0,0 +1,23 @@ +# 第一次OOD练习 # + +## 需求 ## +### 原项目已经实现根据产品列表文件发送促销Mail,需求一直在变化,比如通过数据库获取促销产品或者促销活动改为到货通知,抢购等;为了应变各种变化,需重构代码。 ### +## 需求分析 ## +需求可变因素:
+ +1. 促销产品列表文件可能会变更,或者变更获取方式(如通过数据库获取) +2. 促销活动会根据运营情况变更 +## 重构方案 ## +1. 提取GetProductsFunction,SendMailFunction接口 +2. 添加Notice抽象类,针对接口添加getProducts,sendMai方法 -------各类通知(降价促销,抢购活动,到货通知等等) +3. 添加Mail,Product,User实体类 +4. Mail初始化设置smtpHost,alSmtpHost,fromAddress参数,添加sendMail功能 +5. Product添加getSubscribers功能 +6. 添加GetProductsFunction,SendMailFunction接口实现类 +7. 添加PricePromotion继承Promotion,实现降价促销功能,实例化GetProductsFunction,SendMailFunction接口 +8. 主函数调用sendMail方法 + +## 重构后 ## +重构后项目,可以根据不同运营方案,添加GetProductsFunction,SendMailFunction接口实现类及Notice子类,向订阅者发送通告 + + diff --git a/students/2831099157/out/production/main/com/coderising/ood/srp/product_promotion.txt b/students/2831099157/out/production/main/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/2831099157/out/production/main/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java new file mode 100644 index 0000000000..9a4cbb0f0c --- /dev/null +++ b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java @@ -0,0 +1,28 @@ +/** + * 版权 (c) 2017 palmshe.com + * 保留所有权利。 + */ +package com.coderising.ood.ocp; + +import com.coderising.ood.ocp.formatter.LogFormatter; +import com.coderising.ood.ocp.handler.LogHandler; + +/** + * @Description: + * @author palmshe + * @date 2017年6月19日 下午9:10:02 + */ +public class Logger { + + private LogHandler logHandler; + private LogFormatter logFormatter; + + public Logger(LogHandler handler, LogFormatter formatter){ + this.logHandler= handler; + this.logFormatter= formatter; + } + + public void log(String msg){ + this.logHandler.handleLog(this.logFormatter.formatMsg(msg)); + } +} diff --git a/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/Main.java b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/Main.java new file mode 100644 index 0000000000..9a072602b0 --- /dev/null +++ b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/Main.java @@ -0,0 +1,29 @@ +/** + * 版权 (c) 2017 palmshe.com + * 保留所有权利。 + */ +package com.coderising.ood.ocp; + +import com.coderising.ood.ocp.formatter.DateUtil; +import com.coderising.ood.ocp.formatter.LogFormatter; +import com.coderising.ood.ocp.handler.LogHandler; +import com.coderising.ood.ocp.handler.MailUtil; +import com.coderising.ood.ocp.handler.SMSUtil; + +/** + * @Description: + * @author palmshe + * @date 2017年6月19日 下午9:36:38 + */ +public class Main { + + public static void main(String[] args) { + LogHandler sms= new SMSUtil(); + LogHandler mail= new MailUtil(); + LogFormatter date= new DateUtil(); + Logger log= new Logger(sms, date); + log.log("hello world"); + log= new Logger(mail, date); + log.log("hello coder"); + } +} diff --git a/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/DateUtil.java b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/DateUtil.java new file mode 100644 index 0000000000..7b45fd15dd --- /dev/null +++ b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/DateUtil.java @@ -0,0 +1,20 @@ +package com.coderising.ood.ocp.formatter; + +import java.util.Date; + +public class DateUtil implements LogFormatter{ + + private String getCurrentDateAsString() { + + return "current date: "+ new Date(); + } + + /* (non-Javadoc) + * @see com.coderising.ood.ocp.LogFormatter#formatMsg(java.lang.String) + */ + @Override + public String formatMsg(String msg) { + return getCurrentDateAsString()+ ", "+ msg; + } + +} diff --git a/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/LogFormatter.java b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/LogFormatter.java new file mode 100644 index 0000000000..0be87702f2 --- /dev/null +++ b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/formatter/LogFormatter.java @@ -0,0 +1,15 @@ +/** + * 版权 (c) 2017 palmshe.com + * 保留所有权利。 + */ +package com.coderising.ood.ocp.formatter; + +/** + * @Description: + * @author palmshe + * @date 2017年6月19日 下午9:07:00 + */ +public interface LogFormatter { + + String formatMsg(String msg); +} diff --git a/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/LogHandler.java b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/LogHandler.java new file mode 100644 index 0000000000..e86cebba24 --- /dev/null +++ b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/LogHandler.java @@ -0,0 +1,17 @@ +/** + * 版权 (c) 2017 palmshe.com + * 保留所有权利。 + */ +package com.coderising.ood.ocp.handler; + +import java.io.Serializable; + +/** + * @Description: + * @author palmshe + * @date 2017年6月19日 下午9:08:04 + */ +public interface LogHandler extends Serializable{ + + void handleLog(String msg); +} diff --git a/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/MailUtil.java b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/MailUtil.java new file mode 100644 index 0000000000..e9fb2d90da --- /dev/null +++ b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/MailUtil.java @@ -0,0 +1,9 @@ +package com.coderising.ood.ocp.handler; + +public class MailUtil implements LogHandler{ + + public void handleLog(String logMsg) { + System.out.println("MailUtil handle, msg= "+ logMsg); + } + +} diff --git a/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/PrintUtil.java b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/PrintUtil.java new file mode 100644 index 0000000000..8f2ab2b697 --- /dev/null +++ b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/PrintUtil.java @@ -0,0 +1,21 @@ +/** + * 版权 (c) 2017 palmshe.com + * 保留所有权利。 + */ +package com.coderising.ood.ocp.handler; + +/** + * @Description: + * @author palmshe + * @date 2017年6月19日 下午9:22:49 + */ +public class PrintUtil implements LogHandler{ + + /* (non-Javadoc) + * @see com.coderising.ood.ocp.LogHandler#send(java.lang.String) + */ + @Override + public void handleLog(String msg) { + System.out.println("PrintUtil handle, msg= "+ msg); + } +} diff --git a/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/SMSUtil.java b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/SMSUtil.java new file mode 100644 index 0000000000..4bd916587d --- /dev/null +++ b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/ocp/handler/SMSUtil.java @@ -0,0 +1,9 @@ +package com.coderising.ood.ocp.handler; + +public class SMSUtil implements LogHandler{ + + public void handleLog(String logMsg) { + System.out.println("SMSUtil handle, msg= "+ logMsg); + } + +} diff --git a/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java index f328c1816a..1faff3f68d 100644 --- a/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java +++ b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -15,7 +15,7 @@ public class Configuration { * @param key * @return */ - public String getProperty(String key) { + public static String getProperty(String key) { return configurations.get(key); } diff --git a/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/srp/DataGenerator.java b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/srp/DataGenerator.java new file mode 100644 index 0000000000..6e9f1c2e84 --- /dev/null +++ b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/srp/DataGenerator.java @@ -0,0 +1,64 @@ +/** + * 版权 (c) 2017 palmshe.com + * 保留所有权利。 + */ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @Description: + * @author palmshe + * @date 2017年6月11日 下午10:24:46 + */ +public class DataGenerator { + + /** + * @Description:获取商品 + * @param file + * @return + * @throws IOException + */ + public static Map generateGoods(File file) throws IOException{ + Map good= new HashMap(); + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + good.put(PromotionMail.ID_KEY, data[0]); + good.put(PromotionMail.DESC_KEY, data[1]); + + System.out.println("产品ID = " + data[0] + "\n"); + System.out.println("产品描述 = " + data[1] + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + return good; + } + + /** + * @Description:获取客户 + * @param good + * @return + * @throws Exception + */ + public static List loadMailingList(Map good) throws Exception { + String id= (String)good.get(PromotionMail.ID_KEY); + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + id +"' " + + "and send_mail=1 "; + + return DBUtil.query(sendMailQuery); + } +} diff --git a/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/srp/InitDataUtils.java b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/srp/InitDataUtils.java deleted file mode 100644 index 35cdb939f6..0000000000 --- a/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/srp/InitDataUtils.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * 版权 (c) 2017 palmshe.com - * 保留所有权利。 - */ -package com.coderising.ood.srp; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * @Description: 加载所需要的数据,以便PromotionMail取用 - * @author palmshe - * @date 2017年6月11日 下午10:24:46 - */ -public class InitDataUtils { - - protected static final String GOOD_NAME= "good_name"; - protected static final String GOOD_ID= "good_id"; - - /** - * @Description:生产商品 - * @param file - * @return - * @throws IOException - */ - public static List generateGoods(File file) throws IOException{ - List goods= new ArrayList(); - BufferedReader br = null; - try { - br = new BufferedReader(new FileReader(file)); - String temp = br.readLine(); - String[] data = temp.split(" "); - - for (int i = 0; i < 1; i++) { - Map goodMaps= new HashMap(); - goodMaps.put(GOOD_ID, data[0]); - goodMaps.put(GOOD_NAME, data[1]); - goods.add(goodMaps); - } - -// setProductID(data[0]); -// setProductDesc(data[1]); - -// System.out.println("产品ID = " + productID + "\n"); -// System.out.println("产品描述 = " + productDesc + "\n"); - - } catch (IOException e) { - throw new IOException(e.getMessage()); - } finally { - br.close(); - } - - return goods; - } -} diff --git a/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java index 9f9e749af7..e31d8a9b75 100644 --- a/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java +++ b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -2,17 +2,40 @@ public class MailUtil { - public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, - boolean debug) { - //假装发了一封邮件 + private static String fromAddress; + private static String smtpServer; + private static String altSmtpServer; + + public MailUtil(String fromAddress, String smtpServer, String altSmtpServer){ + this.fromAddress= fromAddress; + this.smtpServer= smtpServer; + this.altSmtpServer= altSmtpServer; + } + + /** + * @Description:发送邮件 + * @param pm + * @param debug + */ + public void sendEmail(PromotionMail pm, boolean debug){ + try { + sendEmail(fromAddress, pm.toAddress, pm.subject, pm.message, smtpServer, debug); + } catch (Exception e1) { + try { + sendEmail(fromAddress, pm.toAddress, pm.subject, pm.message, altSmtpServer, debug); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + private void sendEmail(String from, String to, String subject, String message, String server, boolean debug){ +// 假装发了一封邮件 StringBuilder buffer = new StringBuilder(); - buffer.append("From:").append(fromAddress).append("\n"); - buffer.append("To:").append(toAddress).append("\n"); + buffer.append("From:").append(from).append("\n"); + buffer.append("To:").append(to).append("\n"); buffer.append("Subject:").append(subject).append("\n"); buffer.append("Content:").append(message).append("\n"); System.out.println(buffer.toString()); - } - - } diff --git a/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/srp/Main.java b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/srp/Main.java new file mode 100644 index 0000000000..8029d24a4c --- /dev/null +++ b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/srp/Main.java @@ -0,0 +1,34 @@ +/** + * 版权 (c) 2017 palmshe.com + * 保留所有权利。 + */ +package com.coderising.ood.srp; + +import java.io.File; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +/** + * @Description: + * @author palmshe + * @date 2017年6月12日 下午10:07:23 + */ +public class Main { + public static void main(String[] args) { + try { + File f = new File("E:\\Workspace-Sourcetree\\coding2017\\students\\2842295913\\ood-assignment\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"); + MailUtil maiUtil= new MailUtil(Configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN), Configuration.getProperty(ConfigurationKeys.SMTP_SERVER), Configuration.getProperty(ConfigurationKeys.ALT_SMTP_SERVER)); + Map good = DataGenerator.generateGoods(f); + List users= DataGenerator.loadMailingList(good); + if (!users.isEmpty()) { + Iterator it= users.iterator(); + while (it.hasNext()) { + maiUtil.sendEmail(new PromotionMail((Map)it.next(), good), true); + } + } + } catch (Exception e) { + System.out.println("构造发送邮件数据失败:"+ e.getMessage()); + } + } +} diff --git a/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java index f293eb1f45..a773d878ee 100644 --- a/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java +++ b/students/2842295913/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -1,209 +1,26 @@ package com.coderising.ood.srp; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; import java.util.Map; public class PromotionMail { - - protected String sendMailQuery = null; - - - protected String smtpHost = null; - protected String altSmtpHost = null; - protected String fromAddress = null; protected String toAddress = null; protected String subject = null; protected String message = null; - protected String productID = null; protected String productDesc = null; - private static Configuration config; - - - - private static final String NAME_KEY = "NAME"; - private static final String EMAIL_KEY = "EMAIL"; - - - public static void main(String[] args) throws Exception { - - File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); - boolean emailDebug = false; - - PromotionMail pe = new PromotionMail(f, emailDebug); - - } - - - public PromotionMail(File file, boolean mailDebug) throws Exception { - - //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 - readFile(file); - - - config = new Configuration(); - - setSMTPHost(); - setAltSMTPHost(); - - - setFromAddress(); - - - setLoadQuery(); - - sendEMails(mailDebug, loadMailingList()); - - - } - - - - - private void setProductID(String productID) - { - this.productID = productID; - - } - - protected String getproductID() - { - return productID; - } - - protected void setLoadQuery() throws Exception { - - sendMailQuery = "Select name from subscriptions " - + "where product_id= '" + productID +"' " - + "and send_mail=1 "; - - - System.out.println("loadQuery set"); - } - - - protected void setSMTPHost() - { - smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); - } - - - protected void setAltSMTPHost() - { - altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); - - } - - - protected void setFromAddress() - { - fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); - } - - protected void setMessage(HashMap userInfo) throws IOException - { - - String name = (String) userInfo.get(NAME_KEY); - - subject = "您关注的产品降价了"; - message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; - - - - } - - - protected void readFile(File file) throws IOException // @02C - { - BufferedReader br = null; - try { - br = new BufferedReader(new FileReader(file)); - String temp = br.readLine(); - String[] data = temp.split(" "); - - setProductID(data[0]); - setProductDesc(data[1]); - - System.out.println("产品ID = " + productID + "\n"); - System.out.println("产品描述 = " + productDesc + "\n"); - - } catch (IOException e) { - throw new IOException(e.getMessage()); - } finally { - br.close(); - } - } - - private void setProductDesc(String desc) { - this.productDesc = desc; - } - - - protected void configureEMail(HashMap userInfo) throws IOException - { - toAddress = (String) userInfo.get(EMAIL_KEY); - if (toAddress.length() > 0) - setMessage(userInfo); - } - - protected List loadMailingList() throws Exception { - return DBUtil.query(this.sendMailQuery); - } - - - protected void sendEMails(boolean debug, List mailingList) throws IOException - { - - System.out.println("开始发送邮件"); - - - if (mailingList != null) { - Iterator iter = mailingList.iterator(); - while (iter.hasNext()) { - configureEMail((HashMap) iter.next()); - try - { - if (toAddress.length() > 0) - MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); - } - catch (Exception e) - { - - try { - MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); - - } catch (Exception e2) - { - System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); - } - } - } - - - } - - else { - System.out.println("没有邮件发送"); - - } - - } - - /** - * @Description:设置商品信息 - * @param goods - */ - public void setGoods(List goods){ - Map goodMap= (HashMap)goods.get(0); - setProductDesc((String)goodMap.get(InitDataUtils.GOOD_NAME)); - setProductID((String)goodMap.get(InitDataUtils.GOOD_ID)); + protected static final String NAME_KEY = "NAME"; + protected static final String EMAIL_KEY = "EMAIL"; + protected static final String ID_KEY = "ID"; + protected static final String DESC_KEY = "DESC"; + + public PromotionMail(Map user, Map good){ + String name = (String)user.get(NAME_KEY); + this.productDesc= (String)good.get(DESC_KEY); + this.productID= (String)good.get(ID_KEY); + this.toAddress= (String)user.get(EMAIL_KEY); + this.subject = "您关注的产品降价了"; + this.message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; } } diff --git a/students/294022181/ocp-assignment/src/com/coderising/ocp/EmailLogPrinter.java b/students/294022181/ocp-assignment/src/com/coderising/ocp/EmailLogPrinter.java new file mode 100644 index 0000000000..d0d5fbe7e2 --- /dev/null +++ b/students/294022181/ocp-assignment/src/com/coderising/ocp/EmailLogPrinter.java @@ -0,0 +1,10 @@ +package com.coderising.ocp; + +public class EmailLogPrinter implements LogPrinter { + + @Override + public void print(String log) { + //MailUtil.send(log); + } + +} diff --git a/students/294022181/ocp-assignment/src/com/coderising/ocp/LogPrinter.java b/students/294022181/ocp-assignment/src/com/coderising/ocp/LogPrinter.java new file mode 100644 index 0000000000..f7f50226fb --- /dev/null +++ b/students/294022181/ocp-assignment/src/com/coderising/ocp/LogPrinter.java @@ -0,0 +1,5 @@ +package com.coderising.ocp; + +public interface LogPrinter { + void print(String log); +} diff --git a/students/294022181/ocp-assignment/src/com/coderising/ocp/LogProcessor.java b/students/294022181/ocp-assignment/src/com/coderising/ocp/LogProcessor.java new file mode 100644 index 0000000000..e5343c7d25 --- /dev/null +++ b/students/294022181/ocp-assignment/src/com/coderising/ocp/LogProcessor.java @@ -0,0 +1,5 @@ +package com.coderising.ocp; + +public interface LogProcessor { + String process(String msg); +} diff --git a/students/294022181/ocp-assignment/src/com/coderising/ocp/LogWithDateProcessor.java b/students/294022181/ocp-assignment/src/com/coderising/ocp/LogWithDateProcessor.java new file mode 100644 index 0000000000..f4c574e9fc --- /dev/null +++ b/students/294022181/ocp-assignment/src/com/coderising/ocp/LogWithDateProcessor.java @@ -0,0 +1,12 @@ +package com.coderising.ocp; + +import java.util.Date; + +public class LogWithDateProcessor implements LogProcessor { + + @Override + public String process(String msg) { + String txtDate = new Date().toString(); + return txtDate + ": " + msg; + } +} diff --git a/students/294022181/ocp-assignment/src/com/coderising/ocp/Logger.java b/students/294022181/ocp-assignment/src/com/coderising/ocp/Logger.java new file mode 100644 index 0000000000..071bb88a63 --- /dev/null +++ b/students/294022181/ocp-assignment/src/com/coderising/ocp/Logger.java @@ -0,0 +1,23 @@ +package com.coderising.ocp; + +public class Logger { + private LogProcessor processor; + private LogPrinter printer; + + public Logger(LogProcessor processor, LogPrinter printer) { + this.processor = processor; + this.printer = printer; + } + + public void log(String msg) { + String logMsg = msg; + + if (processor != null) { + logMsg = processor.process(logMsg); + } + + if (printer != null) { + printer.print(logMsg); + } + } +} diff --git a/students/294022181/ocp-assignment/src/com/coderising/ocp/NormalLogPrinter.java b/students/294022181/ocp-assignment/src/com/coderising/ocp/NormalLogPrinter.java new file mode 100644 index 0000000000..dce3556358 --- /dev/null +++ b/students/294022181/ocp-assignment/src/com/coderising/ocp/NormalLogPrinter.java @@ -0,0 +1,10 @@ +package com.coderising.ocp; + +public class NormalLogPrinter implements LogPrinter { + + @Override + public void print(String log) { + System.out.println(log); + } + +} diff --git a/students/294022181/ocp-assignment/src/com/coderising/ocp/RawLogProcessor.java b/students/294022181/ocp-assignment/src/com/coderising/ocp/RawLogProcessor.java new file mode 100644 index 0000000000..4aa5badd37 --- /dev/null +++ b/students/294022181/ocp-assignment/src/com/coderising/ocp/RawLogProcessor.java @@ -0,0 +1,10 @@ +package com.coderising.ocp; + +public class RawLogProcessor implements LogProcessor { + + @Override + public String process(String msg) { + return msg; + } + +} diff --git a/students/294022181/ocp-assignment/src/com/coderising/ocp/SmsLogPrinter.java b/students/294022181/ocp-assignment/src/com/coderising/ocp/SmsLogPrinter.java new file mode 100644 index 0000000000..88a0913761 --- /dev/null +++ b/students/294022181/ocp-assignment/src/com/coderising/ocp/SmsLogPrinter.java @@ -0,0 +1,10 @@ +package com.coderising.ocp; + +public class SmsLogPrinter implements LogPrinter { + + @Override + public void print(String log) { + //SMSUtil.send(log); + } + +} diff --git a/students/294022181/ood-assignment/product_promotion.txt b/students/294022181/ood-assignment/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/294022181/ood-assignment/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/294022181/ood-assignment/src/com/coderising/ood/srp/Configuration.java b/students/294022181/ood-assignment/src/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/294022181/ood-assignment/src/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/294022181/ood-assignment/src/com/coderising/ood/srp/ConfigurationKeys.java b/students/294022181/ood-assignment/src/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/294022181/ood-assignment/src/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/294022181/ood-assignment/src/com/coderising/ood/srp/DBUtil.java b/students/294022181/ood-assignment/src/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/294022181/ood-assignment/src/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/294022181/ood-assignment/src/com/coderising/ood/srp/Email.java b/students/294022181/ood-assignment/src/com/coderising/ood/srp/Email.java new file mode 100644 index 0000000000..956cb57493 --- /dev/null +++ b/students/294022181/ood-assignment/src/com/coderising/ood/srp/Email.java @@ -0,0 +1,85 @@ +package com.coderising.ood.srp; + +public class Email { + private String smtpHost; + private String altSmtpHost; + private String fromAddress; + private String toAddress; + private String subject; + private String message; + private boolean debug; + + public Email() { + + } + + public String getSmtpHost() { + return smtpHost; + } + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public boolean isDebug() { + return debug; + } + + public void setDebug(boolean debug) { + this.debug = debug; + } + + public void sendToTarget() { + try { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } catch (Exception e) { + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } +} diff --git a/students/294022181/ood-assignment/src/com/coderising/ood/srp/MailUtil.java b/students/294022181/ood-assignment/src/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..9f9e749af7 --- /dev/null +++ b/students/294022181/ood-assignment/src/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/294022181/ood-assignment/src/com/coderising/ood/srp/Product.java b/students/294022181/ood-assignment/src/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..fbb4f29db3 --- /dev/null +++ b/students/294022181/ood-assignment/src/com/coderising/ood/srp/Product.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; + +public class Product { + private String productID; + private String productDesc; + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + +} diff --git a/students/294022181/ood-assignment/src/com/coderising/ood/srp/ProductDao.java b/students/294022181/ood-assignment/src/com/coderising/ood/srp/ProductDao.java new file mode 100644 index 0000000000..ad5c53356e --- /dev/null +++ b/students/294022181/ood-assignment/src/com/coderising/ood/srp/ProductDao.java @@ -0,0 +1,36 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +public class ProductDao { + + public Product getProduct(String productFileName) throws IOException { + BufferedReader br = null; + Product product = null; + + try { + File file = new File(productFileName); + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + String productID = data[0]; + String productDesc = data[1]; + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + product = new Product(); + product.setProductID(productID); + product.setProductDesc(productDesc); + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + + return product; + } +} diff --git a/students/294022181/ood-assignment/src/com/coderising/ood/srp/PromotionMail.java b/students/294022181/ood-assignment/src/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..1cda5d5859 --- /dev/null +++ b/students/294022181/ood-assignment/src/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,70 @@ +package com.coderising.ood.srp; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + private Configuration config; + private ProductDao productDao; + private SubscriptionDao subscriptionDao; + + public static void main(String[] args) throws Exception { + boolean emailDebug = false; + String productFileName = "./product_promotion.txt"; + PromotionMail pe = new PromotionMail(productFileName, emailDebug); + } + + public PromotionMail(String productFileName, boolean mailDebug) throws Exception { + config = new Configuration(); + productDao = new ProductDao(); + subscriptionDao = new SubscriptionDao(); + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + Product product = productDao.getProduct(productFileName); + + if (product == null) { + return; + } + + sendEMails(mailDebug, product, subscriptionDao.loadMailingList(product.getProductID())); + } + + protected void sendEMails(boolean debug, Product product, List mailingList) throws IOException { + + System.out.println("开始发送邮件"); + + if (mailingList != null) { + Email email = new Email(); + String smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + String altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + String fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + Iterator iter = mailingList.iterator(); + + while (iter.hasNext()) { + HashMap userInfo = (HashMap) iter.next(); + String toAddress = (String) userInfo.get(EMAIL_KEY); + + if (toAddress.length() > 0) { + String name = (String) userInfo.get(NAME_KEY); + String subject = "您关注的产品降价了"; + String message = "尊敬的 " + name + ", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!" ; + email.setFromAddress(fromAddress); + email.setToAddress(toAddress); + email.setSmtpHost(smtpHost); + email.setAltSmtpHost(altSmtpHost); + email.setSubject(subject); + email.setMessage(message); + email.setDebug(debug); + email.sendToTarget(); + } + } + } else { + System.out.println("没有邮件发送"); + } + + } +} diff --git a/students/294022181/ood-assignment/src/com/coderising/ood/srp/SubscriptionDao.java b/students/294022181/ood-assignment/src/com/coderising/ood/srp/SubscriptionDao.java new file mode 100644 index 0000000000..2cd57ed644 --- /dev/null +++ b/students/294022181/ood-assignment/src/com/coderising/ood/srp/SubscriptionDao.java @@ -0,0 +1,15 @@ +package com.coderising.ood.srp; + +import java.util.List; + +public class SubscriptionDao { + + public List loadMailingList(String productID) throws Exception { + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + System.out.println("loadQuery set"); + return DBUtil.query(sendMailQuery); + } +} diff --git a/students/294022181/ood-assignment/src/com/coderising/ood/srp/product_promotion.txt b/students/294022181/ood-assignment/src/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/294022181/ood-assignment/src/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/303252800/.gitignore b/students/303252800/.gitignore new file mode 100644 index 0000000000..41e8fd6dd8 --- /dev/null +++ b/students/303252800/.gitignore @@ -0,0 +1,22 @@ +target/ +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.idea +*.iws +*.iml +*.ipr +*.zip +*.class +*.jar +*.war +rebel.xml +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ \ No newline at end of file diff --git a/students/303252800/practice13-ood-srp/pom.xml b/students/303252800/practice13-ood-srp/pom.xml new file mode 100644 index 0000000000..7c3a372045 --- /dev/null +++ b/students/303252800/practice13-ood-srp/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + + com.coding2017 + practice13-ood-srp + 1.0-SNAPSHOT + + + 1.6 + UTF-8 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${java.version} + ${java.version} + ${java.encoding} + + + + + \ No newline at end of file diff --git a/students/303252800/practice13-ood-srp/readme.md b/students/303252800/practice13-ood-srp/readme.md new file mode 100644 index 0000000000..e5f4455a16 --- /dev/null +++ b/students/303252800/practice13-ood-srp/readme.md @@ -0,0 +1,8 @@ +# practice13-ood-srp + +  重构一个项目使之符合 SRP (单一职责原则) + +- `EmailConfiguration` 邮件配置职责类 +- `PromotionProduct` 促销产品职责类 +- `PromotionSubscriber` 促销订阅职责类 +- `PromotionNotifier` 促销通知职责类 diff --git a/students/303252800/practice13-ood-srp/src/main/java/com/coding2017/practice13/EmailConfiguration.java b/students/303252800/practice13-ood-srp/src/main/java/com/coding2017/practice13/EmailConfiguration.java new file mode 100644 index 0000000000..3dde0cb7bc --- /dev/null +++ b/students/303252800/practice13-ood-srp/src/main/java/com/coding2017/practice13/EmailConfiguration.java @@ -0,0 +1,47 @@ +package com.coding2017.practice13; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +// 邮件配置职责类 +public final class EmailConfiguration { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + + private static final Map configurations = new HashMap(); + + static { + configurations.put(SMTP_SERVER, "smtp.163.com"); + configurations.put(ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(EMAIL_ADMIN, "admin@company.com"); + } + + // 外部不能创建实例 + private EmailConfiguration() { + } + + // 外部不能更改配置 + public static Map getInstance() { + return Collections.unmodifiableMap(configurations); + } + + + public static String getProperty(String key) { + return configurations.get(key); + } + + public static String getFromAddress() { + return configurations.get(EmailConfiguration.EMAIL_ADMIN); + } + + public static String getSmtpServer() { + return configurations.get(EmailConfiguration.SMTP_SERVER); + } + + public static String getAltSmtpServer() { + return configurations.get(EmailConfiguration.ALT_SMTP_SERVER); + } +} diff --git a/students/303252800/practice13-ood-srp/src/main/java/com/coding2017/practice13/MainApplication.java b/students/303252800/practice13-ood-srp/src/main/java/com/coding2017/practice13/MainApplication.java new file mode 100644 index 0000000000..b04ed0f0a1 --- /dev/null +++ b/students/303252800/practice13-ood-srp/src/main/java/com/coding2017/practice13/MainApplication.java @@ -0,0 +1,17 @@ +package com.coding2017.practice13; + +import java.util.List; + +public class MainApplication { + + public static void main(String[] args) throws Exception { + List products = PromotionProduct.readFromFile("com/coderising/ood/srp/product_promotion.txt"); + + for (PromotionProduct product : products) { + List subscribers = PromotionSubscriber.querySubscribers(product.getProductId()); + for (PromotionSubscriber subscriber : subscribers) { + PromotionNotifier.sendEmail(product, subscriber); + } + } + } +} diff --git a/students/303252800/practice13-ood-srp/src/main/java/com/coding2017/practice13/PromotionNotifier.java b/students/303252800/practice13-ood-srp/src/main/java/com/coding2017/practice13/PromotionNotifier.java new file mode 100644 index 0000000000..30c8a44f00 --- /dev/null +++ b/students/303252800/practice13-ood-srp/src/main/java/com/coding2017/practice13/PromotionNotifier.java @@ -0,0 +1,54 @@ +package com.coding2017.practice13; + +import java.text.MessageFormat; + +// 促销通知职责类 +public class PromotionNotifier { + + private static String subject = "您关注的产品降价了"; + private static String message = "尊敬的 {1} , 您关注的产品 {2} 降价了,欢迎购买!"; + + /** + * 发送邮件通知 + * + * @param product 促销产品 + * @param subscriber 订阅人 + */ + public static void sendEmail(PromotionProduct product, PromotionSubscriber subscriber) { + System.out.println("开始发送邮件"); + String content = MessageFormat.format(message, subscriber.getSubscriber(), product.getProductDesc()); + if (subscriber.getToAddress().length() > 0) { + try { + sendEmail(EmailConfiguration.getFromAddress(), subscriber.getToAddress(), subject, content, EmailConfiguration.getSmtpServer()); + } catch (Exception e1) { + try { + sendEmail(EmailConfiguration.getFromAddress(), subscriber.getToAddress(), subject, content, EmailConfiguration.getAltSmtpServer()); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } else { + System.out.println("没有邮件发送"); + } + } + + /** + * 执行发送邮件 + * + * @param fromAddress 发件人地址 + * @param toAddress 收件人地址 + * @param subject 邮件标题 + * @param content 邮件内容 + * @param smtpHost smtp服务器地址 + */ + private static void sendEmail(String fromAddress, String toAddress, String subject, String content, String smtpHost) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(content).append("\n"); + System.out.println(buffer.toString()); + } + +} diff --git a/students/303252800/practice13-ood-srp/src/main/java/com/coding2017/practice13/PromotionProduct.java b/students/303252800/practice13-ood-srp/src/main/java/com/coding2017/practice13/PromotionProduct.java new file mode 100644 index 0000000000..59200d05bf --- /dev/null +++ b/students/303252800/practice13-ood-srp/src/main/java/com/coding2017/practice13/PromotionProduct.java @@ -0,0 +1,52 @@ +package com.coding2017.practice13; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +// 促销产品职责类 +public class PromotionProduct { + + /** 产品ID */ + private String productId; + /** 产品描述 */ + private String productDesc; + + public String getProductId() { + return productId; + } + + public String getProductDesc() { + return productDesc; + } + + public static List readFromFile(String filepath) throws IOException { + List products = new ArrayList(); + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(new File(filepath))); + String line = null; + while ((line = br.readLine()) != null) { + String[] data = line.split(" "); + PromotionProduct product = new PromotionProduct(); + product.productId = data[0]; + product.productDesc = data[1]; + products.add(product); + System.out.println("产品ID = " + product.getProductId() + "\n"); + System.out.println("产品描述 = " + product.getProductDesc() + "\n"); + } + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + if (br != null) { + br.close(); + } + } + return products; + } + + +} diff --git a/students/303252800/practice13-ood-srp/src/main/java/com/coding2017/practice13/PromotionSubscriber.java b/students/303252800/practice13-ood-srp/src/main/java/com/coding2017/practice13/PromotionSubscriber.java new file mode 100644 index 0000000000..e58760e6ca --- /dev/null +++ b/students/303252800/practice13-ood-srp/src/main/java/com/coding2017/practice13/PromotionSubscriber.java @@ -0,0 +1,35 @@ +package com.coding2017.practice13; + +import java.util.ArrayList; +import java.util.List; + +// 促销订阅人职责类 +public class PromotionSubscriber { + + /** 订阅人邮件地址 */ + private String toAddress; + /** 订阅人姓名 */ + private String subscriber; + + public String getToAddress() { + return toAddress; + } + + public String getSubscriber() { + return subscriber; + } + + /** + * 查询促销产品订阅人列表 + * + * @param productId 产品ID + * @return 订阅人列表 + */ + public static List querySubscribers(String productId) { + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productId + "' " + + "and send_mail=1 "; + System.out.println("loadQuery set"); + return new ArrayList(); + } +} diff --git a/students/303252800/practice13-ood-srp/src/main/resources/com/coderising/ood/srp/Configuration.java b/students/303252800/practice13-ood-srp/src/main/resources/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/303252800/practice13-ood-srp/src/main/resources/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/303252800/practice13-ood-srp/src/main/resources/com/coderising/ood/srp/ConfigurationKeys.java b/students/303252800/practice13-ood-srp/src/main/resources/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/303252800/practice13-ood-srp/src/main/resources/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/303252800/practice13-ood-srp/src/main/resources/com/coderising/ood/srp/DBUtil.java b/students/303252800/practice13-ood-srp/src/main/resources/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/303252800/practice13-ood-srp/src/main/resources/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/303252800/practice13-ood-srp/src/main/resources/com/coderising/ood/srp/MailUtil.java b/students/303252800/practice13-ood-srp/src/main/resources/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..9f9e749af7 --- /dev/null +++ b/students/303252800/practice13-ood-srp/src/main/resources/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/303252800/practice13-ood-srp/src/main/resources/com/coderising/ood/srp/PromotionMail.java b/students/303252800/practice13-ood-srp/src/main/resources/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..781587a846 --- /dev/null +++ b/students/303252800/practice13-ood-srp/src/main/resources/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,199 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery = null; + + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected String productID = null; + protected String productDesc = null; + + private static Configuration config; + + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + + + config = new Configuration(); + + setSMTPHost(); + setAltSMTPHost(); + + + setFromAddress(); + + + setLoadQuery(); + + sendEMails(mailDebug, loadMailingList()); + + + } + + + + + protected void setProductID(String productID) + { + this.productID = productID; + + } + + protected String getproductID() + { + return productID; + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected void setSMTPHost() + { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() + { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + protected void setFromAddress() + { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setMessage(HashMap userInfo) throws IOException + { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + + + + } + + + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + private void setProductDesc(String desc) { + this.productDesc = desc; + } + + + protected void configureEMail(HashMap userInfo) throws IOException + { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try + { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } + + else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/303252800/practice13-ood-srp/src/main/resources/com/coderising/ood/srp/product_promotion.txt b/students/303252800/practice13-ood-srp/src/main/resources/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/303252800/practice13-ood-srp/src/main/resources/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/309229350/readme.md b/students/309229350/readme.md new file mode 100644 index 0000000000..48b857086e --- /dev/null +++ b/students/309229350/readme.md @@ -0,0 +1 @@ +#测试git,第一次提交 diff --git a/students/313001956/pom.xml b/students/313001956/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/313001956/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/313001956/src/main/java/NewFile.xml b/students/313001956/src/main/java/NewFile.xml new file mode 100644 index 0000000000..8c9fd6a466 --- /dev/null +++ b/students/313001956/src/main/java/NewFile.xml @@ -0,0 +1,2223 @@ + + + + + + + 0 + 47 + ʾϢ + + + + + + 3426231013320298 + 342623101332029801 + + + 1962-04-13 + + + ͱ + 342623196204132713 +
޳Ȼ売
+ +
+ + + + 000118082607853555 + 000118082607853555 + 0001 + ΪҽԺ + 1684.8300 + 1601.2700 + 300.0000 + 1280.8000 + 0.0000 + 404.0300 + T50.901 + 2017-07-16 10:11:41 + 2017-07-18 8:26:33 + 21 + 2017-07-18 8:27:23 + 272.5300 + 0.0000 + 1 + 168.5000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231012461948 + 342623101246194801 + + + 1943-03-08 + + + ͱ + 342623194303088958 +
޳̴ֶȻ壴
+ һũ +
+ + + + 000207080039619556 + 000207080039619556 + 0002 + ΪҽҽԺ + 5733.1200 + 3768.3700 + 0.0000 + 5073.3000 + -200.1600 + 859.9800 + ZDZ486 + 2017-07-05 9:20:00 + 2017-07-17 9:44:01 + 2104 + 2017-07-18 7:40:27 + 933.1200 + 0.0000 + 1 + 573.3000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 1013110051 + 342623101311005013 + + + 1974-08-10 + + + ͱ + 342623197408102756 +
޳ͷ
+ һũ +
+ + + + 233521081028602568 + 233521081028602568 + 2335 + ϺߺҽԺ + 4933.0300 + 4737.6300 + 0.0000 + 4105.0000 + 0.0000 + 828.0300 + F20.901 + 2017-06-21 8:13:52 + 2017-07-18 8:17:45 + 21 + 2017-07-18 8:30:35 + 874.3300 + 53.0000 + 1 + 493.3000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231512130395 + 342623151213039502 + ȴ + Ů + 1951-01-21 + ԰ﱦ + Ů + һũ + 342623195101213022 +
ʯ԰Ȼ壳
+ һũ +
+ + + + 005616080011604122 + 005616080011604122 + 0056 + ΪػۿҽԺ + 1705.5200 + 1621.6800 + 0.0000 + 1295.5000 + 154.1400 + 255.8800 + ZDZ103 + 2017-07-16 7:59:54 + 2017-07-18 7:53:40 + 2104 + 2017-07-18 8:03:08 + 280.5200 + 0.0000 + 1 + 170.5000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426232006190458 + 342623200619045801 + żӢ + Ů + 1938-10-26 + żӢ + Ů + ͱ + 342623193810264720 +
԰½Ȼ
+ һũ +
+ + + + 000115145258439815 + 000115145258439815 + 0001 + ΪҽԺ + 4978.6200 + 4842.1800 + 0.0000 + 4837.8000 + -854.9700 + 995.7900 + ZDZ015 + 2017-07-14 7:52:19 + 2017-07-18 9:18:41 + 2104 + 2017-07-18 9:17:18 + 338.6200 + 0.0000 + 1 + 497.8000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231801301806 + 342623180130180602 + 쾲÷ + Ů + 1973-04-24 + ι + Ů + һũ + 342623197304245349 +
ɽɽȻ壴
+ һũ +
+ + + + 004218092418328810 + 004218092418328810 + 0042 + ΪؼҽԺ + 1799.6000 + 1267.3000 + 0.0000 + 1439.7000 + 0.0000 + 359.9000 + N18.903 + 2017-04-13 9:22:06 + 2017-07-18 9:22:06 + 15 + 2017-07-18 9:25:42 + 239.9000 + 0.0000 + 1 + 180.0000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231616030563 + 342623161603056303 + Ӣ + Ů + 1948-03-27 + μҸ + Ů + ͱ + 342623194803273826 +
Ȼ声
+ һũ +
+ + + + 112418102447877740 + 112418102447877740 + 1124 + ҽƴѧҽԺԭ + 6931.3800 + 5664.5300 + 0.0000 + 4851.9000 + 0.0000 + 2079.4800 + Z47.002 + 2017-07-10 9:43:26 + 2017-07-18 8:47:45 + 21 + 2017-07-18 10:28:50 + 1772.5800 + 0.0000 + 1 + 693.1000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426232402160473 + 342623240216047302 + ѧ + + 1948-10-17 + ѧ + + ͱ + 342623194810171393 +
ӰȻ声
+ һũ +
+ + + + 129218074258857075 + 129218074258857075 + 1292 + ɽҽԺ + 2659.0000 + 2436.6000 + 0.0000 + 1994.2000 + 0.0000 + 664.8000 + N40 01 + 2017-07-12 7:36:50 + 2017-07-14 7:36:50 + 21 + 2017-07-18 7:47:09 + 430.7000 + 0.0000 + 1 + 265.9000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426232001040088 + 342623200104008801 + Ȼ + + 1955-04-28 + Ȼ + + ͱ + 342623195504287034 +
幵Ȼ声
+ һũ +
+ + + + 112711090227086225 + 112711090227086225 + 1127 + ߺеڶҽԺ + 11444.3100 + 10554.8100 + 0.0000 + 11087.4000 + 0.0000 + 356.9100 + D46.901 + 2017-07-11 9:03:27 + 2017-07-18 8:26:06 + 21 + 2017-07-18 8:42:49 + 2933.3100 + 1521.2000 + 1 + 1144.4000 + 1 + 410.8000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231816230821 + 342623181623082101 + α + + 1974-11-22 + α + + ͱ + 342623197411223612 +
ɽʯȻ売
+ һũ +
+ + + + 233517154520542487 + 233517154520542487 + 2335 + ϺߺҽԺ + 5757.5400 + 5495.3400 + 0.0000 + 4699.2000 + 0.0000 + 1058.3400 + F20.901 + 2017-06-17 15:48:22 + 2017-07-18 8:18:42 + 21 + 2017-07-18 8:31:55 + 1134.1400 + 0.0000 + 1 + 575.8000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231803431056 + 342623180343105601 + ² + + 1968-12-05 + ² + + ͱ + 342623196812053613 +
ɽСկȻ
+ һũ +
+ + + + 004212161554691195 + 004212161554691195 + 0042 + ΪؼҽԺ + 3227.7900 + 3079.2700 + 300.0000 + 2700.8000 + 0.0000 + 526.9900 + J98.505 + 2017-07-12 16:16:11 + 2017-07-18 11:33:18 + 21 + 2017-07-18 15:05:19 + 549.7900 + 0.0000 + 1 + 322.8000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231808180842 + 342623180818084204 + ´ + Ů + 1969-03-15 + + Ů + ͱ + 342623196903155324 +
ɽ򽨳ӾȻ声
+ һũ +
+ + + + 246614065803519157 + 246614065803519157 + 2466 + ΪƹҽԺ + 2323.0000 + 2296.0000 + 0.0000 + 2206.9000 + 0.0000 + 116.1000 + N93.801 + 2017-07-14 6:58:05 + 2017-07-18 7:44:54 + 21 + 2017-07-18 8:10:03 + 248.4000 + 0.0000 + 1 + 232.3000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231909090376 + 342623190909037604 + + Ů + 2005-05-24 + ѧ + Ů + һũ + 341422200505245923 +
ţȻ声
+ һũ +
+ + + + 000112075724118546 + 000112075724118546 + 0001 + ΪҽԺ + 2199.1900 + 2066.7700 + 0.0000 + 1829.9000 + -70.5700 + 439.8600 + ZDZ226 + 2017-07-12 8:03:36 + 2017-07-18 10:46:03 + 2104 + 2017-07-18 11:12:22 + 289.1900 + 0.0000 + 1 + 219.9000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231019210964 + 342623101921096404 + ׺ʹ + + 1991-10-20 + ձ + + ͱ + 342623199110200352 +
޳Ȼ壱
+ һũ +
+ + + + 112618093606289584 + 112618093606289584 + 1126 + ߺеҽԺ + 829.8000 + 476.4000 + 0.0000 + 622.3000 + 0.0000 + 207.5000 + F20.901 + 2017-07-14 9:34:54 + 2017-07-14 9:34:54 + 15 + 2017-07-18 9:36:51 + -209.5000 + 0.0000 + 1 + 83.0000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426232508040208 + 342623250804020805 + + Ů + 1963-09-23 + + Ů + ͱ + 342623196309235022 +
Ȫ÷庫Ȼ壹
+ һũ +
+ + + + 004218071743845620 + 004218071743845620 + 0042 + ΪؼҽԺ + 735.0000 + 595.0000 + 0.0000 + 588.0000 + 0.0000 + 147.0000 + N18.903 + 2017-07-17 7:16:17 + 2017-07-18 7:16:17 + 15 + 2017-07-18 7:18:24 + -79.5000 + 0.0000 + 1 + 73.5000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426233102040322 + 342623310204032204 + + + 1953-07-15 + + + ͱ + 34262319530715681X +
ɽ罧彧Ȼ壶
+ һũ +
+ + + + 112715110644012483 + 112715110644012483 + 1127 + ߺеڶҽԺ + 3986.3200 + 3521.5700 + 0.0000 + 4108.6000 + -919.5800 + 797.3000 + ZDZ034 + 2017-07-15 11:06:22 + 2017-07-18 9:34:43 + 2103 + 2017-07-18 9:47:23 + -223.6800 + 0.0000 + 1 + 398.6000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426232002170768 + 342623200217076801 + + + 1939-01-05 + + + ͱ + 342623193901054710 +
ʤǰȻ
+ һũ +
+ + + + 000118082021080533 + 000118082021080533 + 0001 + ΪҽԺ + 2955.1800 + 2945.1800 + 0.0000 + 2798.9000 + 0.0000 + 156.2800 + C64 01 + 2017-07-07 8:18:56 + 2017-07-18 8:18:56 + 15 + 2017-07-18 8:20:56 + 151.7800 + 0.0000 + 1 + 295.5000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426232708120384 + 342623270812038402 + Ӣ + Ů + 1953-09-24 + ʯҵ + Ů + һũ + 34262319530924360X +
ͷʯȻ声
+ һũ +
+ + + + 000218082940310312 + 000218082940310312 + 0002 + ΪҽҽԺ + 3780.0400 + 3662.7600 + 0.0000 + 4578.0000 + -1364.9700 + 567.0100 + ZDZ420 + 2017-07-07 9:03:00 + 2017-07-18 8:04:01 + 2104 + 2017-07-18 8:46:05 + -719.9600 + 0.0000 + 1 + 378.0000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231028150665 + 342623102815066502 + ԬΪ + + 1939-02-19 + ԬΪ + + ͱ + 342623193902192736 +
޳ԬȻ壱
+ һũ +
+ + + + 000112104607382178 + 000112104607382178 + 0001 + ΪҽԺ + 2102.3600 + 2060.4800 + 0.0000 + 2760.2000 + -973.2300 + 315.3900 + ZDZ560 + 2017-07-12 10:52:45 + 2017-07-18 9:38:36 + 2104 + 2017-07-18 9:42:46 + -747.6400 + 0.0000 + 1 + 210.2000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426232901381552 + 342623290138155202 + ʤ + + 1993-11-01 + + + ͱ + 342623199311015794 +
ëëȻ声
+ һũ +
+ + + + 112606081455041224 + 112606081455041224 + 1126 + ߺеҽԺ + 9096.1500 + 6881.7500 + 0.0000 + 8641.3000 + -898.6900 + 1353.5400 + ZDZ046 + 2017-06-06 8:13:19 + 2017-07-18 10:49:11 + 2107 + 2017-07-18 12:28:42 + 1330.1500 + 465.7000 + 1 + 909.6000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426232005050137 + 342623200505013705 + Ҧ + Ů + 1939-01-09 + ʤ + Ů + ͱ + 342623193901094827 +
Ȼ声
+ һũ +
+ + + + 000118090426455871 + 000118090426455871 + 0001 + ΪҽԺ + 2867.3300 + 2716.2900 + 0.0000 + 2736.7000 + -442.8700 + 573.5000 + ZDZ136 + 2017-07-14 19:37:23 + 2017-07-18 8:32:28 + 2104 + 2017-07-18 9:05:34 + 117.3300 + 0.0000 + 1 + 286.7000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426233006190720 + 342623300619072002 + + + 1976-03-30 + μ + + ͱ + 342623197603307554 +
ʮȻ声
+ һũ +
+ + + + 233521080914049038 + 233521080914049038 + 2335 + ϺߺҽԺ + 5093.8400 + 4908.4400 + 0.0000 + 4216.3000 + 0.0000 + 877.5400 + F20.901 + 2017-06-21 8:12:37 + 2017-07-18 8:16:57 + 21 + 2017-07-18 8:27:03 + 886.9400 + 0.0000 + 1 + 509.4000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231802241569 + 342623180224156901 + ܱ + + 1972-01-10 + ܱ + + ͱ + 342623197201105335 +
ɽƹܴȻ
+ һũ +
+ + + + 246615063314827750 + 246615063314827750 + 2466 + ΪƹҽԺ + 2378.0000 + 2378.0000 + 100.0000 + 2259.1000 + 0.0000 + 118.9000 + J03.904 + 2017-07-14 8:05:24 + 2017-07-18 7:23:35 + 21 + 2017-07-18 8:14:24 + 256.7000 + 0.0000 + 1 + 237.8000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231603020437 + 342623160302043701 + Ӧ + + 1965-01-22 + Ӧ + + һũ + 34262319650122557X +
ׯȻ壳
+ һũ +
+ + + + 111219172205505280 + 111219172205505280 + 1112 + ҽƴѧһҽԺ + 36353.2800 + 11043.6600 + 0.0000 + 31299.1000 + 0.0000 + 5054.1800 + C43.601 + 2017-06-19 15:40:00 + 2017-07-18 0:00:00 + 21 + 2017-07-18 14:52:41 + 11723.6800 + 4034.2000 + 1 + 3635.3000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426232212110409 + 342623221211040906 + + Ů + 1949-08-22 + ҦΪ + Ů + һũ + 342623194908222187 +
°Ȼ声
+ һũ +
+ + + + 112818090609587595 + 112818090609587595 + 1128 + ҽѧԺ߮ɽҽԺ + 1060.3100 + 268.5100 + 0.0000 + 742.1000 + 0.0000 + 318.2100 + C16.902 + 2017-07-11 9:04:09 + 2017-07-11 9:04:09 + 15 + 2017-07-18 9:06:45 + -575.7900 + 0.0000 + 1 + 106.0000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426232705120425 + 342623270512042501 + ϲ + + 1936-10-22 + ϲ + + һũ + 342623193610223596 +
幨Ȼ声
+ һũ +
+ + + + 000112080308801349 + 000112080308801349 + 0001 + ΪҽԺ + 4868.9400 + 4681.9400 + 300.0000 + 4274.4000 + 0.0000 + 594.5400 + N28.101 + 2017-07-12 8:09:17 + 2017-07-18 14:55:18 + 21 + 2017-07-18 15:07:09 + 781.4400 + 0.0000 + 1 + 486.9000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231914050425 + 342623191405042502 + ϴ÷ + Ů + 1967-04-02 + + Ů + ͱ + 342623196704026829 +
ţٺȻ壸
+ һũ +
+ + + + 000118104220021677 + 000118104220021677 + 0001 + ΪҽԺ + 8555.7000 + 8472.3000 + 0.0000 + 8127.9000 + 0.0000 + 427.8000 + N18.902 + 2017-07-12 10:41:28 + 2017-07-18 10:41:28 + 15 + 2017-07-18 10:42:45 + 1054.3000 + 70.9000 + 1 + 855.6000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231515180628 + 342623151518062801 + + + 1947-09-16 + + + + 342623194709168536 +
ʯ̫ƽСȻ壴
+ һũ +
+ + + + 000112105012505391 + 000112105012505391 + 0001 + ΪҽԺ + 3150.0400 + 3001.0400 + 0.0000 + 4140.0000 + -1462.4700 + 472.5100 + ZDZ348 + 2017-07-12 10:56:18 + 2017-07-18 10:20:17 + 2104 + 2017-07-18 10:18:16 + -974.9600 + 0.0000 + 1 + 315.0000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231517110543 + 342623151711054303 + ˼ + + 1971-01-13 + ˿ά + + һũ + 342623197101138439 +
ʯɽ˼ҴȻ壱
+ һũ +
+ + + + 112418141245997147 + 112418141245997147 + 1124 + ҽƴѧҽԺԭ + 4761.6900 + 4266.0900 + 0.0000 + 3076.1000 + -695.3200 + 2380.9100 + ZDZ347 + 2017-07-10 10:14:32 + 2017-07-18 14:09:18 + 2102 + 2017-07-18 14:14:13 + 1161.6900 + 0.0000 + 1 + 476.1000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426232702100504 + 342623270210050402 + ż + Ů + 1946-08-15 + ־ + Ů + һũ + 34262319460815344X +
Ȼ声
+ һũ +
+ + + + 888888180842361258 + 888888180842361258 + 888888 + ʡҽƻ + 23809.2000 + 11816.2000 + 4761.8000 + 11904.5000 + 0.0000 + 11904.7000 + M48.061 + 2017-05-09 0:00:00 + 2017-06-02 0:00:00 + 21 + 2017-07-18 8:43:52 + 9523.8000 + 0.0000 + 3 + 2380.9000 + 2 + 0.0000 + 2 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231906111237 + 342623190611123703 + ƽ + Ů + 1970-04-11 + + Ů + ͱ + 34262319700411614X +
ţ򶫺彯Ȼ壴
+ һũ +
+ + + + 113118085747515065 + 113118085747515065 + 1131 + ͭеҽԺ + 2108.7200 + 877.9000 + 0.0000 + 1581.5000 + 0.0000 + 527.2200 + F32.902 + 2017-01-03 8:51:29 + 2017-07-05 8:51:29 + 15 + 2017-07-18 8:58:53 + 238.1200 + 0.0000 + 1 + 210.9000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426232514070385 + 342623251407038501 + ʤ + + 1974-09-23 + ʤ + + һũ + 342623197409235016 +
ȪȻ壸
+ һũ +
+ + + + 000118102549575673 + 000118102549575673 + 0001 + ΪҽԺ + 2968.4000 + 2891.6200 + 300.0000 + 2512.0000 + 0.0000 + 456.4000 + Z99.914 + 2017-07-07 9:05:38 + 2017-07-18 10:29:41 + 21 + 2017-07-18 10:27:20 + 453.2000 + 0.0000 + 1 + 296.8000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231614270998 + 342623161427099802 + ÷ + Ů + 1977-01-06 + ӵ + Ů + һũ + 342623197701064023 +
Ȼ声
+ һũ +
+ + + + 112618081402655014 + 112618081402655014 + 1126 + ߺеҽԺ + 1063.6000 + 3.6000 + 0.0000 + 797.7000 + 0.0000 + 265.9000 + F20.901 + 2017-03-14 8:12:04 + 2017-03-14 8:12:04 + 15 + 2017-07-18 8:14:58 + -127.7000 + 0.0000 + 1 + 106.4000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231027020500 + 342623102702050002 + ҵ + Ů + 1946-12-04 + + Ů + ͱ + 342623194612042726 +
޳ׯ山Ȼ壱
+ һũ +
+ + + + 000118100955337559 + 000118100955337559 + 0001 + ΪҽԺ + 1126.5700 + 977.2800 + 0.0000 + 962.0000 + 0.0000 + 164.5700 + N18.902 + 2017-07-17 8:35:20 + 2017-07-18 9:51:58 + 21 + 2017-07-18 10:11:09 + -22.7300 + 0.0000 + 1 + 112.7000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426233104080410 + 342623310408041002 + Ӣ + Ů + 1978-07-07 + + Ů + ͱ + 342623197807075740 +
ɽ彫Ȼ壶
+ һũ +
+ + + + 004210163614466214 + 004210163614466214 + 0042 + ΪؼҽԺ + 4153.7300 + 3954.2700 + 0.0000 + 3790.3000 + -259.7000 + 623.1300 + ZDZ053 + 2017-07-10 16:36:00 + 2017-07-18 7:56:49 + 2104 + 2017-07-18 8:02:39 + 478.7300 + 0.0000 + 1 + 415.3000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231021090716 + 342623102109071602 + + Ů + 1939-04-29 + ʤ + Ů + ͱ + 342623193904290022 +
޳׳Ȼ声
+ һũ +
+ + + + 000218090046744447 + 000218090046744447 + 0002 + ΪҽҽԺ + 4713.6100 + 4360.6200 + 0.0000 + 4221.3000 + -214.7900 + 707.1000 + ZDZ705 + 2017-07-11 8:23:00 + 2017-07-18 8:23:01 + 2104 + 2017-07-18 9:06:03 + 663.6100 + 0.0000 + 1 + 471.3000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426232609090400 + 342623260909040001 + + + 1991-01-24 + ƽ + + һũ + 342623199101244855 +
յȻ壴
+ һũ +
+ + + + 234118100913563244 + 234118100913563244 + 2341 + ߺҽԺ + 12041.2000 + 9418.2000 + 500.0000 + 8661.2000 + 0.0000 + 3380.0000 + S99.901 + 2017-06-25 9:03:57 + 2017-07-01 9:03:57 + 34 + 2017-07-18 10:09:46 + 8474.0000 + 0.0000 + 2 + 1204.1000 + 2 + 3889.9000 + 2 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231602260770 + 342623160226077005 + + + 1977-08-20 + + + ͱ + 342623197708204199 +
ɽմȻ声
+ һũ +
+ + + + 004218144113217583 + 004218144113217583 + 0042 + ΪؼҽԺ + 2195.4000 + 1915.5000 + 0.0000 + 1847.6000 + 0.0000 + 347.8000 + N18.903 + 2017-04-29 9:22:06 + 2017-07-15 9:22:06 + 15 + 2017-07-18 14:44:22 + 267.3000 + 0.0000 + 1 + 219.5000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231906111238 + 342623190611123801 + + + 1953-03-22 + + + ͱ + 342623195303226155 +
ţ򶫺彯Ȼ壴
+ һũ +
+ + + + 888888180910373435 + 888888180910373435 + 888888 + ʡҽƻ + 28049.0000 + 24115.0000 + 0.0000 + 18479.6000 + 0.0000 + 9569.4000 + J60 01 + 2017-06-12 0:00:00 + 2017-07-07 0:00:00 + 21 + 2017-07-18 9:15:57 + 6764.5000 + 0.0000 + 3 + 2804.9000 + 2 + 0.0000 + 2 + 0 + 3 + 1 + 1 + + +
+ + + + 3426232501030177 + 342623250103017704 + Ӣ + Ů + 1943-01-16 + + Ů + һũ + 342623194301163029 +
Ȫ役Ȼ壳
+ һũ +
+ + + + 005815202526443116 + 005815202526443116 + 0058 + Ϊ̩ҽԺ + 1549.0000 + 1475.2000 + 100.0000 + 1454.4000 + 0.0000 + 94.6000 + I10 05 + 2017-07-15 20:25:26 + 2017-07-18 9:08:12 + 21 + 2017-07-18 9:48:38 + 149.5000 + 0.0000 + 1 + 154.9000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426231909050079 + 342623190905007901 + + + 1947-03-16 + + + + 342623194703166273 +
ţȻ壱
+ һũ +
+ + + + 264912072701645298 + 264912072701645298 + 2649 + ΪҽԺ + 2446.0000 + 2414.0000 + 0.0000 + 2323.7000 + 0.0000 + 122.3000 + ZDZ001 + 2017-07-12 7:25:54 + 2017-07-18 9:57:12 + 21 + 2017-07-18 10:03:11 + 266.9000 + 0.0000 + 1 + 244.6000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426232104250962 + 342623210425096203 + ƽ + + 1969-02-24 + ´ + + ͱ + 342623196902247710 +
ҦȻƣ
+ һũ +
+ + + + 000118093718673134 + 000118093718673134 + 0001 + ΪҽԺ + 1236.7200 + 1201.7200 + 0.0000 + 1145.1000 + 0.0000 + 91.6200 + N18.902 + 2017-01-05 9:35:57 + 2017-07-18 9:35:57 + 15 + 2017-07-18 9:37:53 + -84.6800 + 0.0000 + 1 + 123.7000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426233204070330 + 342623320407033001 + ï + + 1970-09-19 + ï + + ͱ + 342623197009196513 +
ɽɽȻ
+ һũ +
+ + + + 112624085058312777 + 112624085058312777 + 1126 + ߺеҽԺ + 12234.4000 + 10947.4000 + 0.0000 + 11541.5000 + -950.9200 + 1643.8200 + ZDZ046 + 2017-05-24 8:50:00 + 2017-07-18 10:10:21 + 2107 + 2017-07-18 12:42:17 + 2219.4000 + 803.1000 + 1 + 1223.4000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426232602050151 + 342623260205015103 + Ө + Ů + 1957-09-10 + ά + Ů + ͱ + 342623195709104828 +
յƽȻ壱
+ һũ +
+ + + + 000111075141336280 + 000111075141336280 + 0001 + ΪҽԺ + 3333.6000 + 3183.1400 + 300.0000 + 2786.0000 + 0.0000 + 547.6000 + R00.201 + 2017-07-11 7:58:02 + 2017-07-18 8:45:01 + 21 + 2017-07-18 10:24:06 + 581.0000 + 0.0000 + 1 + 333.4000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426233201090836 + 342623320109083601 + + + 1968-06-11 + + + ͱ + 342623196806116518 +
Ȼ壵
+ һũ +
+ + + + 004318093638175330 + 004318093638175330 + 0043 + Ϊ޷ҽԺ + 1963.0000 + 1953.0000 + 0.0000 + 1864.9000 + 0.0000 + 98.1000 + I63.902 + 2017-07-09 0:00:00 + 2017-07-18 9:41:33 + 21 + 2017-07-18 9:44:44 + -5.6000 + 0.0000 + 1 + 196.3000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+ + + + 3426232402050175 + 342623240205017501 + + + 1936-01-03 + + + ͱ + 34262319360103139X +
ӰȻ
+ һũ +
+ + + + 888888181039278391 + 888888181039278391 + 888888 + ʡҽƻ + 10347.5000 + 9313.5000 + 0.0000 + 3434.8000 + 0.0000 + 6912.7000 + ZDZ023 + 2017-06-12 0:00:00 + 2017-06-16 0:00:00 + 99 + 2017-07-18 10:39:56 + 5878.0000 + 0.0000 + 3 + 1034.8000 + 2 + 0.0000 + 2 + 0 + 3 + 1 + 1 + + +
+ + + + 3426232804160253 + 342623280416025301 + ϲ + + 1937-08-26 + ϲ + + ͱ + 342623193708267917 +
߹Ȼƣ
+ һũ +
+ + + + 000118104842815812 + 000118104842815812 + 0001 + ΪҽԺ + 6654.8400 + 5699.6600 + 0.0000 + 5510.2000 + 0.0000 + 1144.6400 + N18.902 + 2017-01-17 10:47:19 + 2017-07-18 10:47:19 + 15 + 2017-07-18 10:49:09 + 1510.1400 + 0.0000 + 1 + 665.5000 + 1 + 0.0000 + 1 + 0 + 3 + 1 + 1 + + +
+
+
+ \ No newline at end of file diff --git a/students/313001956/src/main/java/com/coderising/atm/ATM.java b/students/313001956/src/main/java/com/coderising/atm/ATM.java new file mode 100644 index 0000000000..782dc48d13 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/atm/ATM.java @@ -0,0 +1,127 @@ +package com.coderising.atm; + +import java.util.ArrayList; +import java.util.List; + +import com.coderising.atm.transactions.Transaction; +import com.coderising.atm.transactions.TransactionBase; + +public class ATM { + CardReader cardReader; + CashDepensier cashDepensier; + DepositSlot depositSlot; + Printer printer; + SuperKeypad superKeypad; + BankProxy bankProxy; + + public ATM(CardReader cardReader, CashDepensier cashDepensier, DepositSlot depositSlot, Printer printer, + SuperKeypad superKeypad, BankProxy bankProxy) { + this.cardReader = cardReader; + this.cashDepensier = cashDepensier; + this.depositSlot = depositSlot; + this.printer = printer; + this.superKeypad = superKeypad; + this.bankProxy = bankProxy; + } + + public boolean hashEnoughMoney(int amount) { + // TODO Auto-generated method stub + return cashDepensier.hashEnoughMoney(amount); + } + + public boolean dispenseMoney(int amount) { + // TODO Auto-generated method stub + return cashDepensier.dispenseMoney(amount); + } + + public int retriveMoney() { + // TODO Auto-generated method stub + return depositSlot.retriveMoney(); + } + + public SuperKeypad getSuperKeypad() { + return this.superKeypad; + } + + public static void main(String[] args) { + ATM atm = null; + try { + + atm = new ATM(new CardReader(), new CashDepensier(), new DepositSlot(), new Printer(), + new SuperKeypad(new Display(), new KeyBoard()), new BankProxy()); + int account = atm.cardReader.getAccount(); + atm.getSuperKeypad().displayMessage("??????ATM"); + Thread.sleep(2000); + // ?????? + atm.getSuperKeypad().displayMessage("?????" + account); + + String type = ""; + int password = 0; + List transactions = new ArrayList<>(); + TransactionBase tx = null; + while (true) { + type = atm.superKeypad.getTransactionType(); + if (type.equals("D") || type.equals("W") || type.equals("T") || type.equals("B")) { + password = verifyPassword(atm, account); + } + tx = atm.superKeypad.getTransaction(account, password, type); + if (tx.getType().equals("P")) { + atm.printer.print(transactions); + + break; + } else if (tx.getType().equals("E")) { + + break; + } else if (tx != null) { + + if (!tx.preProcess(atm)) { + Thread.sleep(2000); + continue; + } + if (!atm.bankProxy.process(tx)) { + Thread.sleep(2000); + continue; + } + if (!tx.postProcess(atm)) { + Thread.sleep(2000); + continue; + } + // atm.getSuperKeypad().displayMessage("????????"); + transactions.add(tx); + } + } + + } catch (Exception ex) { + atm.superKeypad.displayMessage(ex.getMessage()); + + } finally { + atm.cardReader.ejectCard(); + } + } + + private static int verifyPassword(ATM atm, int account) { + int password = 0; + int failCount = 0; + boolean verified = false; + atm.getSuperKeypad().displayMessage("??????????????"); + while (!verified) { + password = atm.superKeypad.getPassword(); + verified = atm.bankProxy.verify(account, password); + if (!verified) { + + failCount++; + if (failCount >= 3) { + break; + } + + atm.getSuperKeypad().displayMessage("?????????????????" + (3 - failCount) + "????"); + } + } + if (!verified) { + atm.bankProxy.FreezeAccount(account); + throw new RuntimeException("????????????3??,?????????????"); + } + return password; + } + +} diff --git a/students/313001956/src/main/java/com/coderising/atm/BankProxy.java b/students/313001956/src/main/java/com/coderising/atm/BankProxy.java new file mode 100644 index 0000000000..a88404de7a --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/atm/BankProxy.java @@ -0,0 +1,24 @@ +package com.coderising.atm; + +import com.coderising.atm.transactions.Transaction; +import com.coderising.bank.ATMProxy; +import com.coderising.bank.Bank; + +public class BankProxy { + ATMProxy atmProxy = new ATMProxy(new Bank()); + + public boolean verify(int account, int password) { + + return atmProxy.verify(account, password); + } + + public boolean process(Transaction tx) { + String netPackage = tx.toNetworkPackage(); + atmProxy.process(netPackage, null); + return true; + } + + public void FreezeAccount(int account) { + + } +} diff --git a/students/313001956/src/main/java/com/coderising/atm/CardReader.java b/students/313001956/src/main/java/com/coderising/atm/CardReader.java new file mode 100644 index 0000000000..ea50a652bd --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/atm/CardReader.java @@ -0,0 +1,45 @@ +package com.coderising.atm; + +public class CardReader { + //ATM atm; + + public CardReader() { + //this.atm = atm; + } + + public static final int CARDNUM = 12345678; + + public int getAccount() { + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + if (!detectCard()) { + //System.out.println("???????"); + throw new RuntimeException("???????"); + } + + int cardnum = readCardNum(); + return cardnum; + + } + + private int readCardNum() { + // TODO Auto-generated method stub + return CARDNUM; + } + + // ????????????????????????????? + private boolean detectCard() { + return true; + } + + + public void ejectCard() { + // TODO Auto-generated method stub + + } +} + diff --git a/students/313001956/src/main/java/com/coderising/atm/CashDepensier.java b/students/313001956/src/main/java/com/coderising/atm/CashDepensier.java new file mode 100644 index 0000000000..477ae26c2c --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/atm/CashDepensier.java @@ -0,0 +1,15 @@ +package com.coderising.atm; + +public class CashDepensier { + + public boolean hashEnoughMoney(int amount) { + // TODO Auto-generated method stub + return amount<=1000; + } + + public boolean dispenseMoney(int amount) { + // TODO Auto-generated method stub + return amount<=1000; + } + +} diff --git a/students/313001956/src/main/java/com/coderising/atm/DepositSlot.java b/students/313001956/src/main/java/com/coderising/atm/DepositSlot.java new file mode 100644 index 0000000000..2acce638aa --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/atm/DepositSlot.java @@ -0,0 +1,10 @@ +package com.coderising.atm; + +public class DepositSlot { + + public int retriveMoney() { + int rd = (int) (Math.random() * 10); + return rd * 100; + } + +} diff --git a/students/313001956/src/main/java/com/coderising/atm/Display.java b/students/313001956/src/main/java/com/coderising/atm/Display.java new file mode 100644 index 0000000000..96cc481c73 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/atm/Display.java @@ -0,0 +1,11 @@ +package com.coderising.atm; + +public class Display { + public void displayMessage(String message) { + System.out.println(message); + } + + public void displayPassword(char message) { + System.out.print(message); + } +} diff --git a/students/313001956/src/main/java/com/coderising/atm/KeyBoard.java b/students/313001956/src/main/java/com/coderising/atm/KeyBoard.java new file mode 100644 index 0000000000..0123e4760b --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/atm/KeyBoard.java @@ -0,0 +1,54 @@ +package com.coderising.atm; + +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Scanner; + +import javax.swing.JFrame; + +public class KeyBoard implements KeyListener { + + int charA = 0; + + public String getUserInput() { + BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); + try { + return br.readLine(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return ""; + } + + @Override + public void keyPressed(KeyEvent e) { + SuperKeypad sk = (SuperKeypad) e.getSource(); + charA = e.getKeyCode(); + sk.display.displayPassword('*'); + if (charA != 10) { + sk.appendStr((char) (int) charA); + } else { + sk.display.displayPassword((char) (int) charA); + sk.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + sk.removeKeyListener(this); + sk.reGetPassword(); + } + } + + @Override + public void keyReleased(KeyEvent e) { + // TODO Auto-generated method stub + + } + + @Override + public void keyTyped(KeyEvent e) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/313001956/src/main/java/com/coderising/atm/Network.java b/students/313001956/src/main/java/com/coderising/atm/Network.java new file mode 100644 index 0000000000..ea8a7e2107 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/atm/Network.java @@ -0,0 +1,5 @@ +package com.coderising.atm; + +public class Network { + +} diff --git a/students/313001956/src/main/java/com/coderising/atm/Printer.java b/students/313001956/src/main/java/com/coderising/atm/Printer.java new file mode 100644 index 0000000000..1931a40be4 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/atm/Printer.java @@ -0,0 +1,17 @@ +package com.coderising.atm; + +import java.util.List; + +import com.coderising.atm.transactions.Transaction; +import com.coderising.atm.transactions.TransactionBase; + +public class Printer { + + public void print(List transactions) { + for (int i = 0; i < transactions.size(); i++) { + System.out.println(transactions.get(i).toNetworkPackage()); + } + + } + +} diff --git a/students/313001956/src/main/java/com/coderising/atm/SuperKeypad.java b/students/313001956/src/main/java/com/coderising/atm/SuperKeypad.java new file mode 100644 index 0000000000..db5470611c --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/atm/SuperKeypad.java @@ -0,0 +1,131 @@ +package com.coderising.atm; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.concurrent.LinkedBlockingQueue; + +import javax.swing.JFrame; + +import com.coderising.atm.transactions.DepositTx; +import com.coderising.atm.transactions.QueryBalanceTx; +import com.coderising.atm.transactions.Transaction; +import com.coderising.atm.transactions.TransactionBase; +import com.coderising.atm.transactions.TransferTx; +import com.coderising.atm.transactions.WithdrawTx; + +public class SuperKeypad extends JFrame { + + Display display; + KeyBoard keyBoard; + private boolean whileKey = true; + private StringBuilder sb = new StringBuilder(); + + public SuperKeypad(Display display, KeyBoard keyBoard) { + this.display = display; + this.keyBoard = keyBoard; + + // initFrame(keyBoard); + } + + private void initFrame(KeyBoard keyBoard) { + this.setSize(0, 0); + this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + this.setTitle("my jframe"); + this.setVisible(true); + + } + + public int getPassword() { + // ???? + // this.addKeyListener(keyBoard); + return Integer.valueOf(keyBoard.getUserInput()); + + } + + public String reGetPassword() { + // display.displayMessage(sb.toString()); + // ??????? + return sb.toString(); + } + + public void displayMessage(String message) { + display.displayMessage(message); + } + + public void setWhileKey(boolean whileKey) { + this.whileKey = whileKey; + } + + public void appendStr(char ch) { + sb.append(ch); + } + + public String getTransactionType() { + displayMessage("??????????? D : ??? W: ??? T: ??? B???????? P:??? E:???"); + String type = keyBoard.getUserInput(); + return type; + } + + public TransactionBase getTransaction(int account, int password, String type) { + TransactionBase tx = null; + + if (type.equals("D")) { + displayMessage("????????"); + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + tx = new DepositTx(account, password, Transaction.DEPOSIT); + } else if (type.equals("W")) { + displayMessage("???????????"); + int amount = Integer.valueOf(keyBoard.getUserInput()); + tx = new WithdrawTx(account, password, Transaction.WITHDRAW, amount); + } else if (type.equals("T")) { + displayMessage("???????????"); + int toAccount = Integer.valueOf(keyBoard.getUserInput()); + displayMessage("???????????"); + int transferMoney = Integer.valueOf(keyBoard.getUserInput()); + tx = new TransferTx(account, password, Transaction.TRANFER, toAccount, transferMoney); + } else if (type.equals("B")) { + tx = new QueryBalanceTx(account, password, Transaction.BALANCE); + } else if (type.equals("P")) { + tx = new TransactionBase(account, password, Transaction.PRINT) { + + @Override + public boolean preProcess(ATM atm) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean postProcess(ATM atm) { + // TODO Auto-generated method stub + return false; + } + }; + } else if (type.equals("E")) { + tx = new TransactionBase(account, password, Transaction.EXIT) { + + @Override + public boolean preProcess(ATM atm) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean postProcess(ATM atm) { + // TODO Auto-generated method stub + return false; + } + }; + } else { + displayMessage("??????????????????"); + } + + return tx; + } +} diff --git a/students/313001956/src/main/java/com/coderising/atm/transactions/DepositTx.java b/students/313001956/src/main/java/com/coderising/atm/transactions/DepositTx.java new file mode 100644 index 0000000000..bdfdca9c1e --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/atm/transactions/DepositTx.java @@ -0,0 +1,36 @@ +package com.coderising.atm.transactions; + +import com.coderising.atm.ATM; + +public class DepositTx extends TransactionBase { + + private int acctualMoney; + + public DepositTx(int account, int password, String type) { + super(account, password, type); + } + + @Override + public boolean preProcess(ATM atm) { + // TODO Auto-generated method stub + acctualMoney= atm.retriveMoney(); + + return true; + } + + @Override + public boolean postProcess(ATM atm) { + // TODO Auto-generated method stub + return true; + } + + public String toNetworkPackage() { + + return super.toNetworkPackage() +"|"+getAcctualMoney(); + } + + public int getAcctualMoney() { + return acctualMoney; + } + +} diff --git a/students/313001956/src/main/java/com/coderising/atm/transactions/QueryBalanceTx.java b/students/313001956/src/main/java/com/coderising/atm/transactions/QueryBalanceTx.java new file mode 100644 index 0000000000..fbe7a25663 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/atm/transactions/QueryBalanceTx.java @@ -0,0 +1,28 @@ +package com.coderising.atm.transactions; + +import com.coderising.atm.ATM; + +public class QueryBalanceTx extends TransactionBase{ + + public QueryBalanceTx(int account, int password, String type) { + super(account, password, type); + // TODO Auto-generated constructor stub + } + + @Override + public boolean preProcess(ATM atm) { + // TODO Auto-generated method stub + return true; + } + + @Override + public boolean postProcess(ATM atm) { + // TODO Auto-generated method stub + return true; + } + +public String toNetworkPackage() { + + return super.toNetworkPackage(); + } +} diff --git a/students/313001956/src/main/java/com/coderising/atm/transactions/Transaction.java b/students/313001956/src/main/java/com/coderising/atm/transactions/Transaction.java new file mode 100644 index 0000000000..1d5812d7d0 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/atm/transactions/Transaction.java @@ -0,0 +1,19 @@ +package com.coderising.atm.transactions; + +import com.coderising.atm.ATM; + +public interface Transaction { + public static final String EXIT = "E"; + public static final String DEPOSIT = "D"; + public static final String WITHDRAW = "W"; + public static final String TRANFER = "T"; + public static final String BALANCE = "B"; + public static final String PRINT = "P"; + + + public boolean preProcess(ATM atm); + + public boolean postProcess(ATM atm); + + public String toNetworkPackage(); + } diff --git a/students/313001956/src/main/java/com/coderising/atm/transactions/TransactionBase.java b/students/313001956/src/main/java/com/coderising/atm/transactions/TransactionBase.java new file mode 100644 index 0000000000..a54b6804e3 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/atm/transactions/TransactionBase.java @@ -0,0 +1,29 @@ +package com.coderising.atm.transactions; + +public abstract class TransactionBase implements Transaction{ + int account; + int password; + String type; + + + public TransactionBase(int account,int password, String type) { + this.account=account; + this.password=password; + this.type=type; + } + + public int getAccount() { + return account; + } + + public String toNetworkPackage() { + // TODO Auto-generated method stub + return getType() +"|"+getAccount(); + } + + public String getType() { + // TODO Auto-generated method stub + return type; + } + +} diff --git a/students/313001956/src/main/java/com/coderising/atm/transactions/TransferTx.java b/students/313001956/src/main/java/com/coderising/atm/transactions/TransferTx.java new file mode 100644 index 0000000000..6e7c3e27c2 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/atm/transactions/TransferTx.java @@ -0,0 +1,39 @@ +package com.coderising.atm.transactions; + +import com.coderising.atm.ATM; + +public class TransferTx extends TransactionBase { + int toAccount; + int transferMoney; + public TransferTx(int account, int password, String type, int toAccount, int transferMoney) { + super(account, password, type); + // TODO Auto-generated constructor stub + this.toAccount=toAccount; + this.transferMoney=transferMoney; + } + + @Override + public boolean preProcess(ATM atm) { + // TODO Auto-generated method stub + return true; + } + + @Override + public boolean postProcess(ATM atm) { + // TODO Auto-generated method stub + return true; + } + +public String toNetworkPackage() { + + return super.toNetworkPackage() +"|"+getToAccount()+"|"+getTransferMoney(); + } + +public int getToAccount() { + return toAccount; +} + +public int getTransferMoney() { + return transferMoney; +} +} diff --git a/students/313001956/src/main/java/com/coderising/atm/transactions/WithdrawTx.java b/students/313001956/src/main/java/com/coderising/atm/transactions/WithdrawTx.java new file mode 100644 index 0000000000..4b2d9a244d --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/atm/transactions/WithdrawTx.java @@ -0,0 +1,41 @@ +package com.coderising.atm.transactions; + +import com.coderising.atm.ATM; + +public class WithdrawTx extends TransactionBase { + + int amount; + + public WithdrawTx(int account,int password,String type, int amount) { + super(account, password, type); + this.amount=amount; + } + + @Override + public boolean preProcess(ATM atm) { + // TODO Auto-generated method stub + boolean result= atm.hashEnoughMoney(getAmount()); + if (!result) { + atm.getSuperKeypad().displayMessage("ATM???????"); + + } + + return result ; + } + + private int getAmount() { + // TODO Auto-generated method stub + return amount; + } + + @Override + public boolean postProcess(ATM atm) { + // TODO Auto-generated method stub + return atm.dispenseMoney(getAmount()); + } + +public String toNetworkPackage() { + + return super.toNetworkPackage() +"|"+getAmount(); + } +} diff --git a/students/313001956/src/main/java/com/coderising/bank/ATMProxy.java b/students/313001956/src/main/java/com/coderising/bank/ATMProxy.java new file mode 100644 index 0000000000..2b636de0ef --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/bank/ATMProxy.java @@ -0,0 +1,41 @@ +package com.coderising.bank; + +import org.junit.experimental.theories.Theories; + +import com.coderising.atm.CardReader; +import com.coderising.bank.transactions.Transaction; + +public class ATMProxy { + private Bank bank; + + public ATMProxy(Bank bank) { + this.bank = bank; + } + + public void run() { + // ??????? + String data = ""; + String response = ""; + process(data, response); + } + + public void process(String data, String response) { + Transaction tx = toActObject(data); + int status = bank.process(tx); + // response.write(status); + } + + private Transaction toActObject(String data) { + // TODO Auto-generated method stub + return null; + } + + public boolean verify(int account, int password) { + + return this.bank.verify(account, password); + } + + public void FreezeAccount(int faccount) { + bank.FreezeAccount(faccount); + } +} diff --git a/students/313001956/src/main/java/com/coderising/bank/Account.java b/students/313001956/src/main/java/com/coderising/bank/Account.java new file mode 100644 index 0000000000..4f3f8fa62a --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/bank/Account.java @@ -0,0 +1,39 @@ +package com.coderising.bank; + +public class Account { + + private int faccount; + private int password; + private int balance; + private boolean isfreeze; + + public Account(int faccount, int password) { + this.faccount = faccount; + this.password = password; + // TODO Auto-generated constructor stub + } + + public int getFaccount() { + return faccount; + } + + public int getPassword() { + return password; + } + + public int getBalance() { + return balance; + } + + public void setBalance(int balance) { + this.balance = balance; + } + + public void setIsfreeze(boolean isfreeze) { + this.isfreeze = isfreeze; + } + + public boolean getIsfreeze() { + return this.isfreeze; + } +} diff --git a/students/313001956/src/main/java/com/coderising/bank/Bank.java b/students/313001956/src/main/java/com/coderising/bank/Bank.java new file mode 100644 index 0000000000..801bd6a9a3 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/bank/Bank.java @@ -0,0 +1,46 @@ +package com.coderising.bank; + +import java.util.ArrayList; +import java.util.List; + +import com.coderising.atm.CardReader; +import com.coderising.bank.transactions.Transaction; + +public class Bank { + + List accounts; + + public Bank() { + accounts = new ArrayList<>(); + Account account = new Account(12345678, 1234); + account.setBalance(5000); + accounts.add(account); + } + + public int process(Transaction tx) { + // TODO Auto-generated method stub + return 0; + } + + public boolean verify(int account, int password) { + Account acc = getAccount(account); + if (acc != null) { + return acc.getPassword() == password; + } + return false; + } + + public Account getAccount(int faccount) { + for (Account acc : accounts) { + if (acc.getFaccount() == faccount) { + return acc; + } + } + + return null; + } + + public void FreezeAccount(int faccount) { + getAccount(faccount).setIsfreeze(true); + } +} diff --git a/students/313001956/src/main/java/com/coderising/bank/transactions/DepositTx.java b/students/313001956/src/main/java/com/coderising/bank/transactions/DepositTx.java new file mode 100644 index 0000000000..e6ce262ccb --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/bank/transactions/DepositTx.java @@ -0,0 +1,27 @@ +package com.coderising.bank.transactions; + +import com.coderising.atm.ATM; + +public class DepositTx extends TransactionBase { + + public DepositTx(int account, int password) { + super(account, password); + } + + @Override + public boolean preProcess(ATM atm) { + // TODO Auto-generated method stub + int acctualMoney= atm.retriveMoney(); + + return false; + } + + @Override + public boolean postProcess(ATM atm) { + // TODO Auto-generated method stub + return false; + } + + + +} diff --git a/students/313001956/src/main/java/com/coderising/bank/transactions/QueryBalanceTx.java b/students/313001956/src/main/java/com/coderising/bank/transactions/QueryBalanceTx.java new file mode 100644 index 0000000000..4aaa570614 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/bank/transactions/QueryBalanceTx.java @@ -0,0 +1,25 @@ +package com.coderising.bank.transactions; + +import com.coderising.atm.ATM; + +public class QueryBalanceTx extends TransactionBase{ + + public QueryBalanceTx(int account, int password) { + super(account, password); + // TODO Auto-generated constructor stub + } + + @Override + public boolean preProcess(ATM atm) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean postProcess(ATM atm) { + // TODO Auto-generated method stub + return false; + } + + +} diff --git a/students/313001956/src/main/java/com/coderising/bank/transactions/Transaction.java b/students/313001956/src/main/java/com/coderising/bank/transactions/Transaction.java new file mode 100644 index 0000000000..1172852e68 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/bank/transactions/Transaction.java @@ -0,0 +1,9 @@ +package com.coderising.bank.transactions; + +import com.coderising.atm.ATM; + +public interface Transaction { + public boolean preProcess(ATM atm); + + public boolean postProcess(ATM atm); + } diff --git a/students/313001956/src/main/java/com/coderising/bank/transactions/TransactionBase.java b/students/313001956/src/main/java/com/coderising/bank/transactions/TransactionBase.java new file mode 100644 index 0000000000..2992310ceb --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/bank/transactions/TransactionBase.java @@ -0,0 +1,17 @@ +package com.coderising.bank.transactions; + +public abstract class TransactionBase implements Transaction{ + int account; + int password; + + + public TransactionBase(int account,int password) { + this.account=account; + this.password=password; + } + + public int getAccount() { + return account; + } + +} diff --git a/students/313001956/src/main/java/com/coderising/bank/transactions/TransferTx.java b/students/313001956/src/main/java/com/coderising/bank/transactions/TransferTx.java new file mode 100644 index 0000000000..d273b76597 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/bank/transactions/TransferTx.java @@ -0,0 +1,25 @@ +package com.coderising.bank.transactions; + +import com.coderising.atm.ATM; + +public class TransferTx extends TransactionBase { + + public TransferTx(int account, int password) { + super(account, password); + // TODO Auto-generated constructor stub + } + + @Override + public boolean preProcess(ATM atm) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean postProcess(ATM atm) { + // TODO Auto-generated method stub + return false; + } + + +} diff --git a/students/313001956/src/main/java/com/coderising/bank/transactions/WithdrawTx.java b/students/313001956/src/main/java/com/coderising/bank/transactions/WithdrawTx.java new file mode 100644 index 0000000000..2a15f6797e --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/bank/transactions/WithdrawTx.java @@ -0,0 +1,32 @@ +package com.coderising.bank.transactions; + +import com.coderising.atm.ATM; + +public class WithdrawTx extends TransactionBase { + + int amount; + + public WithdrawTx(int account,int password,int amount) { + super(account, password); + this.amount=amount; + } + + @Override + public boolean preProcess(ATM atm) { + // TODO Auto-generated method stub + return atm.hashEnoughMoney(getAmount()); + } + + private int getAmount() { + // TODO Auto-generated method stub + return amount; + } + + @Override + public boolean postProcess(ATM atm) { + // TODO Auto-generated method stub + return atm.dispenseMoney(getAmount()); + } + + +} diff --git a/students/313001956/src/main/java/com/coderising/dp/bridge/Circle.java b/students/313001956/src/main/java/com/coderising/dp/bridge/Circle.java new file mode 100644 index 0000000000..138e25b4f8 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/bridge/Circle.java @@ -0,0 +1,23 @@ +package com.coderising.dp.bridge; + +public class Circle implements Shape { + + private Drawing drawing; + private int x; + private int y; + private int r; + + public Circle(Drawing drawing, int x, int y, int r) { + this.drawing = drawing; + this.x = x; + this.y = y; + this.r = r; + + } + + @Override + public void draw() { + drawing.drawCircle(x, y, r); + } + +} diff --git a/students/313001956/src/main/java/com/coderising/dp/bridge/Drawing.java b/students/313001956/src/main/java/com/coderising/dp/bridge/Drawing.java new file mode 100644 index 0000000000..f29acaa393 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/bridge/Drawing.java @@ -0,0 +1,7 @@ +package com.coderising.dp.bridge; + +public interface Drawing { + public void drawLine(int x1,int y1,int x2,int y2); + + public void drawCircle(int x,int y, int r); +} diff --git a/students/313001956/src/main/java/com/coderising/dp/bridge/DrawingGL1.java b/students/313001956/src/main/java/com/coderising/dp/bridge/DrawingGL1.java new file mode 100644 index 0000000000..290853b1be --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/bridge/DrawingGL1.java @@ -0,0 +1,20 @@ +package com.coderising.dp.bridge; + +public class DrawingGL1 implements Drawing { + GraphicLibrary1 lib1; + + public DrawingGL1(GraphicLibrary1 lib1) { + this.lib1 = lib1; + } + + @Override + public void drawLine(int x1, int y1, int x2, int y2) { + lib1.draw_a_line(x1, y1, x2, y2); + } + + @Override + public void drawCircle(int x, int y, int r) { + lib1.draw_a_circle(x, y, r); + } + +} diff --git a/students/313001956/src/main/java/com/coderising/dp/bridge/DrawingGL2.java b/students/313001956/src/main/java/com/coderising/dp/bridge/DrawingGL2.java new file mode 100644 index 0000000000..b24d6e0c65 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/bridge/DrawingGL2.java @@ -0,0 +1,20 @@ +package com.coderising.dp.bridge; + +public class DrawingGL2 implements Drawing { + GraphicLibrary2 lib2; + + public DrawingGL2(GraphicLibrary2 lib2) { + this.lib2 = lib2; + } + + @Override + public void drawLine(int x1, int y1, int x2, int y2) { + lib2.drawLine(x1, x2, y1, y2); + } + + @Override + public void drawCircle(int x, int y, int r) { + lib2.drawCircle(x, y, r); + } + +} diff --git a/students/313001956/src/main/java/com/coderising/dp/bridge/GraphicLibrary1.java b/students/313001956/src/main/java/com/coderising/dp/bridge/GraphicLibrary1.java new file mode 100644 index 0000000000..deb40619a0 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/bridge/GraphicLibrary1.java @@ -0,0 +1,11 @@ +package com.coderising.dp.bridge; + +public class GraphicLibrary1 { + public void draw_a_line(int x1,int y1,int x2,int y2){ + System.out.println("GraphicLibrary1:draw rectangle"); + } + public void draw_a_circle(int x,int y, int r){ + System.out.println("GraphicLibrary1:draw circle"); + } + +} diff --git a/students/313001956/src/main/java/com/coderising/dp/bridge/GraphicLibrary2.java b/students/313001956/src/main/java/com/coderising/dp/bridge/GraphicLibrary2.java new file mode 100644 index 0000000000..84b306a3ff --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/bridge/GraphicLibrary2.java @@ -0,0 +1,11 @@ +package com.coderising.dp.bridge; + +public class GraphicLibrary2 { + public void drawLine(int x1,int x2,int y1,int y2){ + System.out.println("GraphicLibrary2:draw rectangle"); + } + public void drawCircle(int x,int y, int r){ + System.out.println("GraphicLibrary2:draw circle"); + } + +} diff --git a/students/313001956/src/main/java/com/coderising/dp/bridge/Rectangle.java b/students/313001956/src/main/java/com/coderising/dp/bridge/Rectangle.java new file mode 100644 index 0000000000..8239628cb5 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/bridge/Rectangle.java @@ -0,0 +1,23 @@ +package com.coderising.dp.bridge; + +public class Rectangle implements Shape { + private Drawing drawing; + private int x1; + private int y1; + private int x2; + private int y2; + + public Rectangle(Drawing drawing, int x1, int x2, int y1, int y2) { + this.drawing = drawing; + this.x1 = x1; + this.x2 = x2; + this.y1 = y1; + this.y2 = y2; + } + + @Override + public void draw() { + drawing.drawLine(x1, y1, x2, y2); + } + +} diff --git a/students/313001956/src/main/java/com/coderising/dp/bridge/Shape.java b/students/313001956/src/main/java/com/coderising/dp/bridge/Shape.java new file mode 100644 index 0000000000..ec69f08fd4 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/bridge/Shape.java @@ -0,0 +1,5 @@ +package com.coderising.dp.bridge; + +public interface Shape { + public void draw(); +} diff --git a/students/313001956/src/main/java/com/coderising/dp/bridge/testBrige.java b/students/313001956/src/main/java/com/coderising/dp/bridge/testBrige.java new file mode 100644 index 0000000000..c01ee02ef1 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/bridge/testBrige.java @@ -0,0 +1,28 @@ +package com.coderising.dp.bridge; + +public class testBrige { + public static void main(String[] args) { + GraphicLibrary1 lib1 = new GraphicLibrary1(); + GraphicLibrary2 lib2 = new GraphicLibrary2(); + + DrawingGL1 drawingGL1 = new DrawingGL1(lib1); + DrawingGL2 drawingGL2 = new DrawingGL2(lib2); + int x = 8; + int y = 9; + int r = 6; + Circle circle = new Circle(drawingGL1, x, y, r); + circle.draw(); + + circle = new Circle(drawingGL2, x, y, r); + circle.draw(); + + int x1 = 5; + int y1 = 87; + int x2 = 8; + int y2 = 6; + Rectangle rectangle = new Rectangle(drawingGL1, x1, y1, x2, y2); + rectangle.draw(); + rectangle = new Rectangle(drawingGL2, x1, x2, y1, y2); + rectangle.draw(); + } +} diff --git a/students/313001956/src/main/java/com/coderising/dp/builder/TagBuilder.java b/students/313001956/src/main/java/com/coderising/dp/builder/TagBuilder.java new file mode 100644 index 0000000000..07466f04cc --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/builder/TagBuilder.java @@ -0,0 +1,43 @@ +package com.coderising.dp.builder; + +public class TagBuilder { + + private TagNode root; + private TagNode currentNode; + private TagNode currentNodeParent; + + public TagBuilder(String rootTagName) { + this.root = new TagNode(rootTagName); + this.currentNode = this.root; + } + + public TagBuilder addChild(String childTagName) { + TagNode node = new TagNode(childTagName); + this.currentNode.add(node); + currentNodeParent = currentNode; + currentNode = node; + return this; + } + + public TagBuilder addSibling(String siblingTagName) { + TagNode node = new TagNode(siblingTagName); + this.currentNodeParent.add(node); + currentNode = node; + return this; + + } + + public TagBuilder setAttribute(String name, String value) { + this.currentNode.setAttribute(name, value); + return this; + } + + public TagBuilder setText(String value) { + this.currentNode.setValue(value); + return this; + } + + public String toXML() { + return this.root.toXML(); + } +} diff --git a/students/313001956/src/main/java/com/coderising/dp/builder/TagBuilderTest.java b/students/313001956/src/main/java/com/coderising/dp/builder/TagBuilderTest.java new file mode 100644 index 0000000000..10731ec824 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/builder/TagBuilderTest.java @@ -0,0 +1,39 @@ +package com.coderising.dp.builder; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class TagBuilderTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } +//java.lang.Runtime??java.awt.Desktop??java.awt.Toolkit + @Test + public void testToXML() { + + TagBuilder builder = new TagBuilder("order"); + + String xml = builder.addChild("line-items") + .addChild("line-item").setAttribute("pid", "P3677").setAttribute("qty", "3") + .addSibling("line-item").setAttribute("pid", "P9877").setAttribute("qty", "10") + .toXML(); + + String expected = "" + + "" + + "" + + "" + + "" + + ""; + + System.out.println(xml); + assertEquals(expected, xml); + } +} diff --git a/students/313001956/src/main/java/com/coderising/dp/builder/TagNode.java b/students/313001956/src/main/java/com/coderising/dp/builder/TagNode.java new file mode 100644 index 0000000000..2ac26ad7b9 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/builder/TagNode.java @@ -0,0 +1,83 @@ +package com.coderising.dp.builder; + +import java.util.ArrayList; +import java.util.List; + +public class TagNode { + private String tagName; + private String tagValue; + private List children = new ArrayList<>(); + private List attributes = new ArrayList<>(); + + public TagNode(String name){ + this.tagName = name; + } + public void add(TagNode child){ + this.children.add(child); + } + public void setAttribute(String name, String value) { + Attribute attr = findAttribute(name); + if(attr != null){ + attr.value = value; + return; + } + + attributes.add(new Attribute(name,value)); + } + private Attribute findAttribute(String name){ + for(Attribute attr : attributes){ + if(attr.name.equals(name)){ + return attr; + } + } + return null; + } + public void setValue(String value) { + this.tagValue = value; + + } + public String getTagName() { + return tagName; + } + public List getChildren() { + return children; + } + + private static class Attribute{ + public Attribute(String name, String value) { + this.name = name; + this.value = value; + } + String name; + String value; + + } + public String toXML(){ + return toXML(this); + } + private String toXML(TagNode node){ + StringBuilder buffer = new StringBuilder(); + buffer.append("<").append(node.tagName); + if(node.attributes.size()> 0){ + for(int i=0;i"); + return buffer.toString(); + } + buffer.append(">"); + for(TagNode childNode : node.children){ + buffer.append(toXML(childNode)); + } + buffer.append(""); + + + return buffer.toString(); + } + private String toXML(Attribute attr){ + return attr.name+"=\""+attr.value + "\""; + } +} diff --git a/students/313001956/src/main/java/com/coderising/dp/chain/ChainLogger.java b/students/313001956/src/main/java/com/coderising/dp/chain/ChainLogger.java new file mode 100644 index 0000000000..77a19a079c --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/chain/ChainLogger.java @@ -0,0 +1,11 @@ +package com.coderising.dp.chain; + +public class ChainLogger { + public static void main(String[] args) { + Logger logger = new StdoutLogger(Logger.DEBUG) + .setNext(new EmailLogger(Logger.NOTICE).setNext(new FileLogger(Logger.ERR))); + logger.message("?????????", Logger.DEBUG); + logger.message("???????????", Logger.NOTICE); + logger.message("????????????????", Logger.ERR); + } +} diff --git a/students/313001956/src/main/java/com/coderising/dp/chain/EmailLogger.java b/students/313001956/src/main/java/com/coderising/dp/chain/EmailLogger.java new file mode 100644 index 0000000000..7e4e6a2ca9 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/chain/EmailLogger.java @@ -0,0 +1,32 @@ +package com.coderising.dp.chain; + +public class EmailLogger extends Logger{ + + + public EmailLogger(int type) { + this.type = type; + // TODO Auto-generated constructor stub + } + @Override + public Logger setNext(Logger logger) { + + this.nextLogger = logger; + // TODO Auto-generated method stub + return this; + } + + @Override + public void message(String message, int type) { + // TODO Auto-generated method stub + setMessage(message); + if (!hasType(type)) { + nextLogger.message(message, type); + } + } + + + + private void setMessage(String message) { + System.out.println(message + " type:" + type); + } +} diff --git a/students/313001956/src/main/java/com/coderising/dp/chain/FileLogger.java b/students/313001956/src/main/java/com/coderising/dp/chain/FileLogger.java new file mode 100644 index 0000000000..4d39c9ca35 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/chain/FileLogger.java @@ -0,0 +1,28 @@ +package com.coderising.dp.chain; + +public class FileLogger extends Logger { + public FileLogger(int type) { + this.type = type; + // TODO Auto-generated constructor stub + } + + @Override + public Logger setNext(Logger logger) { + this.nextLogger = logger; + // TODO Auto-generated method stub + return this; + } + + @Override + public void message(String message, int type) { + // TODO Auto-generated method stub + setMessage(message); + if (!hasType(type)) { + nextLogger.message(message, type); + } + } + + private void setMessage(String message) { + System.out.println(message + " type:" + type); + } +} diff --git a/students/313001956/src/main/java/com/coderising/dp/chain/Logger.java b/students/313001956/src/main/java/com/coderising/dp/chain/Logger.java new file mode 100644 index 0000000000..8871d0e985 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/chain/Logger.java @@ -0,0 +1,20 @@ +package com.coderising.dp.chain; + +public abstract class Logger { + protected Logger nextLogger; + protected int type; + + + public static final int DEBUG = 1; + public static final int NOTICE = 2; + public static final int ERR = 3; + + public abstract Logger setNext(Logger logger); + + public abstract void message(String message, int type); + + protected boolean hasType(int type) { + // TODO Auto-generated method stub + return this.type == type; + } +} diff --git a/students/313001956/src/main/java/com/coderising/dp/chain/StdoutLogger.java b/students/313001956/src/main/java/com/coderising/dp/chain/StdoutLogger.java new file mode 100644 index 0000000000..e6c76cbeb3 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/chain/StdoutLogger.java @@ -0,0 +1,31 @@ +package com.coderising.dp.chain; + +public class StdoutLogger extends Logger { + + public StdoutLogger(int type) { + this.type = type; + // TODO Auto-generated constructor stub + } + + @Override + public Logger setNext(Logger logger) { + this.nextLogger = logger; + // TODO Auto-generated method stub + return this; + } + + @Override + public void message(String message, int type) { + // TODO Auto-generated method stub + setMessage(message); + if (!hasType(type)) { + nextLogger.message(message, type); + } + } + + + + private void setMessage(String message) { + System.out.println(message + " type:" + type); + } +} diff --git a/students/313001956/src/main/java/com/coderising/dp/chain/chaintest.java b/students/313001956/src/main/java/com/coderising/dp/chain/chaintest.java new file mode 100644 index 0000000000..d80f31842e --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/chain/chaintest.java @@ -0,0 +1,19 @@ +package com.coderising.dp.chain; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class chaintest { + + @Test + public void test() { + //fail("Not yet implemented"); + Logger logger = new StdoutLogger(Logger.DEBUG) + .setNext(new EmailLogger(Logger.NOTICE).setNext(new FileLogger(Logger.ERR))); + logger.message("?????????", Logger.DEBUG); + logger.message("???????????", Logger.NOTICE); + logger.message("????????????????", Logger.ERR); + } + +} diff --git a/students/313001956/src/main/java/com/coderising/dp/command/Command.java b/students/313001956/src/main/java/com/coderising/dp/command/Command.java new file mode 100644 index 0000000000..f4b1b13d10 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/command/Command.java @@ -0,0 +1,6 @@ +package com.coderising.dp.command; + +public interface Command { + + void run(); +} diff --git a/students/313001956/src/main/java/com/coderising/dp/command/CommandTest.java b/students/313001956/src/main/java/com/coderising/dp/command/CommandTest.java new file mode 100644 index 0000000000..0f6295c9a7 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/command/CommandTest.java @@ -0,0 +1,13 @@ +package com.coderising.dp.command; + +public class CommandTest { + public static void main(String[] args) { + Cook cook = new Cook(); + Waiter waiter = new Waiter(); + Command command1=new OrderSteakCommand(cook); + Command command2=new OrderPeaKCommand(cook); + waiter.addOrder(command1); + waiter.addOrder(command2); + waiter.sendOrder(); + } +} diff --git a/students/313001956/src/main/java/com/coderising/dp/command/Cook.java b/students/313001956/src/main/java/com/coderising/dp/command/Cook.java new file mode 100644 index 0000000000..4c56245b25 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/command/Cook.java @@ -0,0 +1,12 @@ +package com.coderising.dp.command; + +public class Cook { + + void cookSteak() { + System.out.println("steak is ok"); + } + + void cookPeak() { + System.out.println("peak is ok"); + } +} diff --git a/students/313001956/src/main/java/com/coderising/dp/command/OrderPeaKCommand.java b/students/313001956/src/main/java/com/coderising/dp/command/OrderPeaKCommand.java new file mode 100644 index 0000000000..b823ba0a24 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/command/OrderPeaKCommand.java @@ -0,0 +1,17 @@ +package com.coderising.dp.command; + +public class OrderPeaKCommand implements Command { + + private Cook cook; + + public OrderPeaKCommand(Cook cook) { + // TODO Auto-generated constructor stub + this.cook = cook; + } + + @Override + public void run() { + // TODO Auto-generated method stub + cook.cookPeak(); + } +} diff --git a/students/313001956/src/main/java/com/coderising/dp/command/OrderSteakCommand.java b/students/313001956/src/main/java/com/coderising/dp/command/OrderSteakCommand.java new file mode 100644 index 0000000000..d5351e05a4 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/command/OrderSteakCommand.java @@ -0,0 +1,17 @@ +package com.coderising.dp.command; + +public class OrderSteakCommand implements Command { + + private Cook cook; + + public OrderSteakCommand(Cook cook) { + // TODO Auto-generated constructor stub + this.cook = cook; + } + + @Override + public void run() { + // TODO Auto-generated method stub + cook.cookSteak(); + } +} diff --git a/students/313001956/src/main/java/com/coderising/dp/command/Waiter.java b/students/313001956/src/main/java/com/coderising/dp/command/Waiter.java new file mode 100644 index 0000000000..0397ff71c0 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/command/Waiter.java @@ -0,0 +1,19 @@ +package com.coderising.dp.command; + +import java.util.ArrayList; +import java.util.List; + +public class Waiter { + + List list = new ArrayList<>(); + + public void addOrder(Command command) { + list.add(command); + } + + public void sendOrder() { + for (Command command : list) { + command.run(); + } + } +} diff --git a/students/313001956/src/main/java/com/coderising/dp/composite/Line.java b/students/313001956/src/main/java/com/coderising/dp/composite/Line.java new file mode 100644 index 0000000000..09fa13dda8 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/composite/Line.java @@ -0,0 +1,11 @@ +package com.coderising.dp.composite; + +public class Line implements Shape { + + @Override + public void draw() { + + System.out.println("Line"); + } + +} diff --git a/students/313001956/src/main/java/com/coderising/dp/composite/Picture.java b/students/313001956/src/main/java/com/coderising/dp/composite/Picture.java new file mode 100644 index 0000000000..342452ac9f --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/composite/Picture.java @@ -0,0 +1,23 @@ +package com.coderising.dp.composite; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.validator.PublicClassValidator; + +public class Picture implements Shape { + List list = new ArrayList<>(); + + public void addList(Shape shape){ + list.add(shape); + } + + @Override + public void draw() { + System.out.println("Picture:"); + for (Shape shape : list) { + shape.draw(); + } + } + +} diff --git a/students/313001956/src/main/java/com/coderising/dp/composite/Rectangle.java b/students/313001956/src/main/java/com/coderising/dp/composite/Rectangle.java new file mode 100644 index 0000000000..2f4fe47ee0 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/composite/Rectangle.java @@ -0,0 +1,11 @@ +package com.coderising.dp.composite; + +public class Rectangle implements Shape { + + @Override + public void draw() { + // TODO Auto-generated method stub + System.out.println("Rectangle"); + } + +} diff --git a/students/313001956/src/main/java/com/coderising/dp/composite/Shape.java b/students/313001956/src/main/java/com/coderising/dp/composite/Shape.java new file mode 100644 index 0000000000..4562f10b12 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/composite/Shape.java @@ -0,0 +1,5 @@ +package com.coderising.dp.composite; + +public interface Shape { + public void draw(); +} diff --git a/students/313001956/src/main/java/com/coderising/dp/composite/Square.java b/students/313001956/src/main/java/com/coderising/dp/composite/Square.java new file mode 100644 index 0000000000..df9c8d9c3a --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/composite/Square.java @@ -0,0 +1,11 @@ +package com.coderising.dp.composite; + +public class Square implements Shape { + + @Override + public void draw() { + // TODO Auto-generated method stub + System.out.println("Square"); + } + +} diff --git a/students/313001956/src/main/java/com/coderising/dp/composite/Text.java b/students/313001956/src/main/java/com/coderising/dp/composite/Text.java new file mode 100644 index 0000000000..6fa91e9608 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/composite/Text.java @@ -0,0 +1,11 @@ +package com.coderising.dp.composite; + +public class Text implements Shape { + + @Override + public void draw() { + // TODO Auto-generated method stub + System.out.println("Text"); + } + +} diff --git a/students/313001956/src/main/java/com/coderising/dp/composite/testComposite.java b/students/313001956/src/main/java/com/coderising/dp/composite/testComposite.java new file mode 100644 index 0000000000..ac8ae44d24 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/composite/testComposite.java @@ -0,0 +1,15 @@ +package com.coderising.dp.composite; + +public class testComposite { + public static void main(String[] args) { + Picture root = new Picture(); + Picture node = new Picture(); + node.addList(new Text()); + node.addList(new Line()); + node.addList(new Square()); + root.addList(node); + root.addList(new Line()); + root.addList(new Rectangle()); + root.draw(); + } +} diff --git a/students/313001956/src/main/java/com/coderising/dp/decorator/DecoratorTest.java b/students/313001956/src/main/java/com/coderising/dp/decorator/DecoratorTest.java new file mode 100644 index 0000000000..8107e042fc --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/decorator/DecoratorTest.java @@ -0,0 +1,11 @@ +package com.coderising.dp.decorator; + +public class DecoratorTest { + public static void main(String[] args) { + Email e1 = new EmailEcript(new EmailDeclare(new EmailImpl("?????????????"))); + System.out.println(e1.getContent()); + + e1 = new EmailDeclare (new EmailEcript(new EmailImpl("?????????????"))); + System.out.println(e1.getContent()); + } +} diff --git a/students/313001956/src/main/java/com/coderising/dp/decorator/Email.java b/students/313001956/src/main/java/com/coderising/dp/decorator/Email.java new file mode 100644 index 0000000000..064de1e837 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/decorator/Email.java @@ -0,0 +1,6 @@ +package com.coderising.dp.decorator; + +public interface Email { + public String getContent(); +} + diff --git a/students/313001956/src/main/java/com/coderising/dp/decorator/EmailDeclare.java b/students/313001956/src/main/java/com/coderising/dp/decorator/EmailDeclare.java new file mode 100644 index 0000000000..eef468dc0c --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/decorator/EmailDeclare.java @@ -0,0 +1,19 @@ +package com.coderising.dp.decorator; + +import org.junit.experimental.theories.Theories; + +public class EmailDeclare extends EmailDecorator { + + + public EmailDeclare(Email email) { + super(email); + } + + @Override + public String getContent() { + return email.getContent() + +"\r\n" + +"???????????????????????????"; + } + +} diff --git a/students/313001956/src/main/java/com/coderising/dp/decorator/EmailDecorator.java b/students/313001956/src/main/java/com/coderising/dp/decorator/EmailDecorator.java new file mode 100644 index 0000000000..0c6665c8e9 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/decorator/EmailDecorator.java @@ -0,0 +1,13 @@ +package com.coderising.dp.decorator; + +public abstract class EmailDecorator implements Email { + protected volatile Email email; + + public EmailDecorator(Email email) { + this.email = email; + } + + public String getContent() { + return email.getContent(); + } +} diff --git a/students/313001956/src/main/java/com/coderising/dp/decorator/EmailEcript.java b/students/313001956/src/main/java/com/coderising/dp/decorator/EmailEcript.java new file mode 100644 index 0000000000..a6e91169c8 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/decorator/EmailEcript.java @@ -0,0 +1,14 @@ +package com.coderising.dp.decorator; + +public class EmailEcript extends EmailDecorator { + + public EmailEcript(Email email) { + super(email); + } + + @Override + public String getContent() { + return "**" + email.getContent() + "**"; + } + +} diff --git a/students/313001956/src/main/java/com/coderising/dp/decorator/EmailImpl.java b/students/313001956/src/main/java/com/coderising/dp/decorator/EmailImpl.java new file mode 100644 index 0000000000..640aef6da3 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/dp/decorator/EmailImpl.java @@ -0,0 +1,12 @@ +package com.coderising.dp.decorator; + +public class EmailImpl implements Email { + private String content; + + public EmailImpl(String content) { + this.content = content; + } + public String getContent() { + return content; + } +} diff --git a/students/313001956/src/main/java/com/coderising/ood/ocp/DateUtil.java b/students/313001956/src/main/java/com/coderising/ood/ocp/DateUtil.java new file mode 100644 index 0000000000..d35f8caa5c --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/ocp/DateUtil.java @@ -0,0 +1,13 @@ +package com.coderising.ood.ocp; + +import java.text.SimpleDateFormat; +import java.util.Date; + +public class DateUtil { + + public static String getCurrentDateAsString() { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + return dateFormat.format(new Date()); + } + +} diff --git a/students/313001956/src/main/java/com/coderising/ood/ocp/EmailLogWay.java b/students/313001956/src/main/java/com/coderising/ood/ocp/EmailLogWay.java new file mode 100644 index 0000000000..a16ba7f283 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/ocp/EmailLogWay.java @@ -0,0 +1,7 @@ +package com.coderising.ood.ocp; + +public class EmailLogWay implements ILogWay { + public void excutelog(String logMsg) { + MailUtil.send(logMsg); + } +} diff --git a/students/313001956/src/main/java/com/coderising/ood/ocp/EmailMessageWay.java b/students/313001956/src/main/java/com/coderising/ood/ocp/EmailMessageWay.java new file mode 100644 index 0000000000..28d846068f --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/ocp/EmailMessageWay.java @@ -0,0 +1,8 @@ +package com.coderising.ood.ocp; + +public class EmailMessageWay implements IMessageWay { + public String getmessage(String msg) { + String txtDate = DateUtil.getCurrentDateAsString(); + return txtDate + ": " + msg; + } +} diff --git a/students/313001956/src/main/java/com/coderising/ood/ocp/ILogWay.java b/students/313001956/src/main/java/com/coderising/ood/ocp/ILogWay.java new file mode 100644 index 0000000000..b90da40f6c --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/ocp/ILogWay.java @@ -0,0 +1,6 @@ +package com.coderising.ood.ocp; + +public interface ILogWay { + + public void excutelog(String logMsg); +} diff --git a/students/313001956/src/main/java/com/coderising/ood/ocp/IMessageWay.java b/students/313001956/src/main/java/com/coderising/ood/ocp/IMessageWay.java new file mode 100644 index 0000000000..42a232eaa7 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/ocp/IMessageWay.java @@ -0,0 +1,6 @@ +package com.coderising.ood.ocp; + +public interface IMessageWay { + + public String getmessage(String msg); +} diff --git a/students/313001956/src/main/java/com/coderising/ood/ocp/Logger.java b/students/313001956/src/main/java/com/coderising/ood/ocp/Logger.java new file mode 100644 index 0000000000..2680f6fac7 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/ocp/Logger.java @@ -0,0 +1,17 @@ +package com.coderising.ood.ocp; + +public class Logger { + + private IMessageWay messageWay; + private ILogWay logWay; + + public Logger(IMessageWay messageWay, ILogWay logWay) { + this.messageWay = messageWay; + this.logWay = logWay; + } + + public void log(String msg) { + + logWay.excutelog(messageWay.getmessage(msg)); + } +} diff --git a/students/313001956/src/main/java/com/coderising/ood/ocp/LoggerTest.java b/students/313001956/src/main/java/com/coderising/ood/ocp/LoggerTest.java new file mode 100644 index 0000000000..6a1cdd3b0f --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/ocp/LoggerTest.java @@ -0,0 +1,21 @@ +package com.coderising.ood.ocp; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class LoggerTest { + + @Test + public void testLog() { + Logger logger =new Logger(new EmailMessageWay(), new EmailLogWay()); + logger.log("hellow world"); + + logger =new Logger(new SMSMessageWay(), new SMSLogWay()); + logger.log("hellow world"); + + logger =new Logger(new PrintMessageWay(), new PrintLogWay()); + logger.log("hellow world"); + } + +} diff --git a/students/313001956/src/main/java/com/coderising/ood/ocp/MailUtil.java b/students/313001956/src/main/java/com/coderising/ood/ocp/MailUtil.java new file mode 100644 index 0000000000..eb891d72c2 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/ocp/MailUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class MailUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + System.out.println("Email:" + logMsg); + } + +} diff --git a/students/313001956/src/main/java/com/coderising/ood/ocp/PrintLogWay.java b/students/313001956/src/main/java/com/coderising/ood/ocp/PrintLogWay.java new file mode 100644 index 0000000000..ff8b180938 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/ocp/PrintLogWay.java @@ -0,0 +1,9 @@ +package com.coderising.ood.ocp; + +public class PrintLogWay implements ILogWay { + @Override + public void excutelog(String logMsg) { + // TODO Auto-generated method stub + System.out.println("Print:" + logMsg); + } +} diff --git a/students/313001956/src/main/java/com/coderising/ood/ocp/PrintMessageWay.java b/students/313001956/src/main/java/com/coderising/ood/ocp/PrintMessageWay.java new file mode 100644 index 0000000000..678d9c2027 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/ocp/PrintMessageWay.java @@ -0,0 +1,9 @@ +package com.coderising.ood.ocp; + +public class PrintMessageWay implements IMessageWay { + @Override + public String getmessage(String msg) { + // TODO Auto-generated method stub + return msg; + } +} diff --git a/students/313001956/src/main/java/com/coderising/ood/ocp/SMSLogWay.java b/students/313001956/src/main/java/com/coderising/ood/ocp/SMSLogWay.java new file mode 100644 index 0000000000..33db6557a7 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/ocp/SMSLogWay.java @@ -0,0 +1,9 @@ +package com.coderising.ood.ocp; + +public class SMSLogWay implements ILogWay { + @Override + public void excutelog(String logMsg) { + // TODO Auto-generated method stub + SMSUtil.send(logMsg); + } +} diff --git a/students/313001956/src/main/java/com/coderising/ood/ocp/SMSMessageWay.java b/students/313001956/src/main/java/com/coderising/ood/ocp/SMSMessageWay.java new file mode 100644 index 0000000000..b6975ed6a2 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/ocp/SMSMessageWay.java @@ -0,0 +1,8 @@ +package com.coderising.ood.ocp; + +public class SMSMessageWay implements IMessageWay{ + @Override +public String getmessage(String msg) { + return msg; +} +} diff --git a/students/313001956/src/main/java/com/coderising/ood/ocp/SMSUtil.java b/students/313001956/src/main/java/com/coderising/ood/ocp/SMSUtil.java new file mode 100644 index 0000000000..16f5e99c77 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/ocp/SMSUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class SMSUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + System.out.println("SMS:" + logMsg); + } + +} diff --git a/students/313001956/src/main/java/com/coderising/ood/srp/Configuration.java b/students/313001956/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..e060caa01b --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + + static Map configurations = new HashMap<>(); + static{ + configurations.put(SMTP_SERVER, "smtp.163.com"); + configurations.put(ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(EMAIL_ADMIN, "admin@company.com"); + } + /** + * ??????????????? ?????????????????map ????? + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } +} diff --git a/students/313001956/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/313001956/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..c3b6f7aadd --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,28 @@ +package com.coderising.ood.srp; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * ???????????? ????????????? + * + * @param sql + * @return + */ + public static List query(String sql, Product product) { + + List userList = new ArrayList<>(); + for (int i = 1; i <= 3; i++) { + User user = new User(); + user.setName("User" + i); + user.setEmail("aa@bb.com"); + user.addProducts(product); + userList.add(user); + } + return userList; + } + +} diff --git a/students/313001956/src/main/java/com/coderising/ood/srp/Mail.java b/students/313001956/src/main/java/com/coderising/ood/srp/Mail.java new file mode 100644 index 0000000000..470470ef7c --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/srp/Mail.java @@ -0,0 +1,34 @@ +package com.coderising.ood.srp; + +import java.util.List; + +public class Mail { + private User user; + private String subject; + private String message; + + public Mail(User user) { + this.user = user; + } + + public User getUser() { + return user; + } + + public String getMessage() { + return "??? " + user.getName() + ", ????????? " + buildDesc() + " ??????????????!"; + } + + public String getSubject() { + return "???????????????"; + } + + private String buildDesc() { + List products=user.getProducts(); + StringBuffer sb = new StringBuffer(); + for (Product p : products) { + sb.append(p.getProductDesc()); + } + return sb.toString(); + } +} diff --git a/students/313001956/src/main/java/com/coderising/ood/srp/MailSender.java b/students/313001956/src/main/java/com/coderising/ood/srp/MailSender.java new file mode 100644 index 0000000000..cfe2dba0fe --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/srp/MailSender.java @@ -0,0 +1,36 @@ +package com.coderising.ood.srp; + +public class MailSender { + + Configuration config; + + public MailSender(Configuration config) { + this.config = config; + } + + public void sendEmails(Mail mail) { + System.out.println("??????????"); + try { + sendEmail(mail, config.getProperty(Configuration.SMTP_SERVER)); + } catch (Exception e) { + try { + sendEmail(mail, config.getProperty(Configuration.ALT_SMTP_SERVER)); + + } catch (Exception e2) { + System.out.println("??????? SMTP????????????????: " + e2.getMessage()); + } + } + } + + public void sendEmail(Mail mail, String smtpHost) { + + // ????????????? + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(config.getProperty(Configuration.EMAIL_ADMIN)).append("\n"); + buffer.append("To:").append(mail.getUser().getEmail()).append("\n"); + buffer.append("Subject:").append(mail.getSubject()).append("\n"); + buffer.append("Content:").append(mail.getMessage()).append("\n"); + System.out.println(buffer.toString()); + } + +} diff --git a/students/313001956/src/main/java/com/coderising/ood/srp/Product.java b/students/313001956/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..5137434bd9 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,22 @@ +package com.coderising.ood.srp; + +public class Product { + private String productID ; + private String productDesc; + + public String getProductDesc() { + return productDesc; + } + + public String getProductID() { + return productID; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + + public void setProductID(String productID) { + this.productID = productID; + } +} diff --git a/students/313001956/src/main/java/com/coderising/ood/srp/ProductServer.java b/students/313001956/src/main/java/com/coderising/ood/srp/ProductServer.java new file mode 100644 index 0000000000..6245a1621d --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/srp/ProductServer.java @@ -0,0 +1,36 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class ProductServer { + private static final String FILE_NAME = "D:\\Java2017\\????\\ood-assignment\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"; + + // ???????????? ???????????????????? ???? P8756 iPhone8 + public List getProductList() throws IOException // @02C + { + File file = new File(FILE_NAME); + BufferedReader br = null; + List prolist = new ArrayList<>(); + try { + br = new BufferedReader(new FileReader(file)); + String temp; + while ((temp = br.readLine()) != null) { + String[] arrStr = temp.split(" "); + Product p = new Product(); + p.setProductID(arrStr[0]); + p.setProductDesc(arrStr[1]); + prolist.add(p); + } + return prolist; + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } +} diff --git a/students/313001956/src/main/java/com/coderising/ood/srp/PromotionJob.java b/students/313001956/src/main/java/com/coderising/ood/srp/PromotionJob.java new file mode 100644 index 0000000000..fbbbd125d7 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/srp/PromotionJob.java @@ -0,0 +1,36 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionJob { + private ProductServer productServer; + private UserServer userServer; + + public PromotionJob(ProductServer productServer, UserServer userServer) { + this.productServer = productServer; + this.userServer = userServer; + } + + public void run() throws IOException { + List productList = productServer.getProductList(); + Product product = productList.get(0); + System.out.println("???ID = " + product.getProductID() + "\n"); + System.out.println("??????? = " + product.getProductDesc() + "\n"); + + List users = userServer.getUserByProduct(product); + + MailSender mailSender = new MailSender(new Configuration()); + for (User user : users) { + mailSender.sendEmails(new Mail(user)); + } + } + +} diff --git a/students/313001956/src/main/java/com/coderising/ood/srp/PromotionJobTest.java b/students/313001956/src/main/java/com/coderising/ood/srp/PromotionJobTest.java new file mode 100644 index 0000000000..2f59d383a7 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/srp/PromotionJobTest.java @@ -0,0 +1,29 @@ +package com.coderising.ood.srp; + +import static org.junit.Assert.*; + +import java.io.IOException; + +import org.junit.Test; + +public class PromotionJobTest { + + @Test + public void testRun() throws IOException { + + Integer i1=4; + Integer i2=4; + Integer i3=400; + Integer i4=400; + + boolean b1=(i1==i2); + boolean b2=(i3==i4); + + System.out.println(b1); + System.out.println(b2); + + PromotionJob pJob = new PromotionJob(new ProductServer(), new UserServer()); + pJob.run(); + } + +} diff --git a/students/313001956/src/main/java/com/coderising/ood/srp/User.java b/students/313001956/src/main/java/com/coderising/ood/srp/User.java new file mode 100644 index 0000000000..19ce2d0d1d --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/srp/User.java @@ -0,0 +1,34 @@ +package com.coderising.ood.srp; + +import java.util.ArrayList; +import java.util.List; + +public class User { + private String name; + private String email; + private List products = new ArrayList<>(); + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + public List getProducts() { + return products; + } + + public void setName(String name) { + this.name = name; + } + + public void setEmail(String email) { + this.email = email; + } + + public void addProducts(Product product) { + this.products.add(product); + } +} diff --git a/students/313001956/src/main/java/com/coderising/ood/srp/UserServer.java b/students/313001956/src/main/java/com/coderising/ood/srp/UserServer.java new file mode 100644 index 0000000000..ebd8ac5c37 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/srp/UserServer.java @@ -0,0 +1,13 @@ +package com.coderising.ood.srp; + +import java.util.List; + +public class UserServer { + public List getUserByProduct(Product product) { + String sendMailQuery = "Select name from subscriptions " + "where product_id= '" + product.getProductID() + "' " + + "and send_mail=1 "; + System.out.println("load Query set"); + List userList = DBUtil.query(sendMailQuery, product); + return userList; + } +} diff --git a/students/313001956/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/313001956/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/313001956/src/main/java/com/coderising/payroll/PayrollService.java b/students/313001956/src/main/java/com/coderising/payroll/PayrollService.java new file mode 100644 index 0000000000..d475fb41e3 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/PayrollService.java @@ -0,0 +1,69 @@ +package com.coderising.payroll; + +import java.util.ArrayList; +import java.util.List; + +import com.coderising.payroll.classification.CommissionedClassification; +import com.coderising.payroll.classification.HourlyClassification; +import com.coderising.payroll.classification.SalariedClassification; +import com.coderising.payroll.domain.Employee; +import com.coderising.payroll.domain.HoldMethod; +import com.coderising.payroll.domain.Paycheck; +import com.coderising.payroll.schedule.BiweeklySchedule; +import com.coderising.payroll.schedule.MonthlySchedule; +import com.coderising.payroll.schedule.WeeklySchedule; +import com.coderising.payroll.transaction.AddEmployeeTransaction; +import com.coderising.payroll.transaction.AddHourlyEmployeeTransaction; + +public class PayrollService { + + + public List getAllEmployees() { + List list = new ArrayList<>(); + list.add(addHourlyEmployee("????", "???", 0.6)); + list.add(addSalariedEmployee("????", "???", 1000, 0.6)); + list.add(addCommissionedEmployee("????", "???", 1500)); + + return list; + } + + + + public void savePaycheck(Paycheck pc) { + //?????????.... + + } + + public Employee addHourlyEmployee(String name, String address, double hourlyRate) { + Employee employee = new Employee(name, address); + employee.setClassification(new HourlyClassification(hourlyRate)); + employee.setPaymentMethod(new HoldMethod()); + employee.setSchedule(new WeeklySchedule()); + return employee; + } + + public Employee addSalariedEmployee(String name, String address, double salary, double saleRate) { + Employee employee = new Employee(name, address); + employee.setClassification(new CommissionedClassification(salary, saleRate)); + employee.setPaymentMethod(new HoldMethod()); + employee.setSchedule(new BiweeklySchedule()); + return employee; + } + + public Employee addCommissionedEmployee(String name, String address, double salary) { + Employee employee = new Employee(name, address); + employee.setClassification(new SalariedClassification(salary)); + employee.setPaymentMethod(new HoldMethod()); + employee.setSchedule(new MonthlySchedule()); + return employee; + } + + List list; + public void addEmployee(AddEmployeeTransaction transaction) { + list.add(transaction); + } + + public static void main(String[] args) { + new PayrollService().addEmployee(new AddHourlyEmployeeTransaction("", "", 0.1)); + } +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/affiliation/NonAffiliation.java b/students/313001956/src/main/java/com/coderising/payroll/affiliation/NonAffiliation.java new file mode 100644 index 0000000000..3cb6228aa4 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/affiliation/NonAffiliation.java @@ -0,0 +1,10 @@ +package com.coderising.payroll.affiliation; + +import com.coderising.payroll.domain.Affiliation; +import com.coderising.payroll.domain.Paycheck; + +public class NonAffiliation implements Affiliation{ + public double calculateDeductions(Paycheck pc){ + return 0.0; + } +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/affiliation/UnionAffiliation.java b/students/313001956/src/main/java/com/coderising/payroll/affiliation/UnionAffiliation.java new file mode 100644 index 0000000000..0938e86803 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/affiliation/UnionAffiliation.java @@ -0,0 +1,38 @@ +package com.coderising.payroll.affiliation; + +import java.util.Date; +import java.util.Map; + +import com.coderising.payroll.domain.Affiliation; +import com.coderising.payroll.domain.Paycheck; +import com.coderising.payroll.domain.ServiceCharge; +import com.coderising.payroll.util.DateUtil; + +public class UnionAffiliation implements Affiliation { + + private String memberId; + private double weeklyDue; + + public UnionAffiliation(String memberId, double weeklyDue) { + this.memberId = memberId; + this.weeklyDue = weeklyDue; + } + + Map charges; + + @Override + public double calculateDeductions(Paycheck pc) { + int fridays = DateUtil.getFridayCountBetween(pc.getPayPeriodStartDate(), pc.getPayPeriodEndDate()); + double totalDue = fridays * weeklyDue; + double totalCharge = 0; + for (ServiceCharge charge : charges.values()) { + if (DateUtil.between(charge.getDate(), pc.getPayPeriodStartDate(), pc.getPayPeriodEndDate())) { + totalCharge += charge.getAmount(); + } + } + double deduction = totalDue + totalCharge; + + return deduction; + } + +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/classification/CommissionedClassification.java b/students/313001956/src/main/java/com/coderising/payroll/classification/CommissionedClassification.java new file mode 100644 index 0000000000..a574001137 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/classification/CommissionedClassification.java @@ -0,0 +1,38 @@ +package com.coderising.payroll.classification; + +import java.util.Date; +import java.util.Map; + +import com.coderising.payroll.domain.Paycheck; +import com.coderising.payroll.domain.PaymentClassification; +import com.coderising.payroll.domain.SalesReceipt; +import com.coderising.payroll.util.DateUtil; + +public class CommissionedClassification implements PaymentClassification { + double salary; + double rate; + + public CommissionedClassification(double salary, double rate) { + this.salary = salary; + this.rate = rate; + } + + Map receipts; + + public void AddSalesReceipt(SalesReceipt receipt){ + receipts.put(receipt.getSaleDate(), receipt); + } + + @Override + public double calculatePay(Paycheck pc) { + int count = 0; + for (SalesReceipt receipt : receipts.values()) { + if (DateUtil.between(receipt.getSaleDate(), pc.getPayPeriodStartDate(), pc.getPayPeriodEndDate())) { + count += receipt.getAmount(); + } + } + + return salary + count* rate; + } + +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/classification/HourlyClassification.java b/students/313001956/src/main/java/com/coderising/payroll/classification/HourlyClassification.java new file mode 100644 index 0000000000..3588cdbef5 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/classification/HourlyClassification.java @@ -0,0 +1,49 @@ +package com.coderising.payroll.classification; + +import java.util.Date; +import java.util.Map; + +import javax.swing.plaf.PanelUI; + +import com.coderising.payroll.domain.Paycheck; +import com.coderising.payroll.domain.PaymentClassification; +import com.coderising.payroll.domain.SalesReceipt; +import com.coderising.payroll.domain.TimeCard; +import com.coderising.payroll.util.DateUtil; + +public class HourlyClassification implements PaymentClassification { + private double rate; + private Map timeCards; + + public HourlyClassification(double hourlyRate) { + this.rate = hourlyRate; + } + + public void addTimeCard(TimeCard tc) { + timeCards.put(tc.getDate(), tc); + } + + @Override + public double calculatePay(Paycheck pc) { + double totalPay=0; + for (TimeCard tc : timeCards.values()) { + if (DateUtil.between(tc.getDate(), pc.getPayPeriodStartDate(), pc.getPayPeriodEndDate())) { + totalPay += caculatePayforTimeCard(tc.getHours()) ; + } + } + + return totalPay; + } + + private double caculatePayforTimeCard(int hours) { + double pay = 0; + if (hours > 8) { + pay = rate * 8 + rate * 1.5 * (hours - 8); + } else { + pay = rate * hours; + } + + return pay; + } + +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/classification/SalariedClassification.java b/students/313001956/src/main/java/com/coderising/payroll/classification/SalariedClassification.java new file mode 100644 index 0000000000..796aae93f1 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/classification/SalariedClassification.java @@ -0,0 +1,16 @@ +package com.coderising.payroll.classification; + +import com.coderising.payroll.domain.Paycheck; +import com.coderising.payroll.domain.PaymentClassification; + +public class SalariedClassification implements PaymentClassification { + private double salary; + public SalariedClassification(double salary){ + this.salary = salary; + } + @Override + public double calculatePay(Paycheck pc) { + return salary; + } + +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/domain/Affiliation.java b/students/313001956/src/main/java/com/coderising/payroll/domain/Affiliation.java new file mode 100644 index 0000000000..74a6b404bc --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/domain/Affiliation.java @@ -0,0 +1,5 @@ +package com.coderising.payroll.domain; + +public interface Affiliation { + public double calculateDeductions(Paycheck pc); +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/domain/Employee.java b/students/313001956/src/main/java/com/coderising/payroll/domain/Employee.java new file mode 100644 index 0000000000..3ef8fe284a --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/domain/Employee.java @@ -0,0 +1,49 @@ +package com.coderising.payroll.domain; + +import java.util.Date; + +public class Employee { + private String id; + private String name; + private String address; + private Affiliation affiliation; + + private PaymentClassification classification; + private PaymentSchedule schedule; + private PaymentMethod paymentMethod; + + public Employee(String name, String address) { + this.name = name; + this.address = address; + } + + public boolean isPayDay(Date d) { + return this.schedule.isPayDate(d); + } + + public Date getPayPeriodStartDate(Date d) { + return this.schedule.getPayPeriodStartDate(d); + } + + public void payDay(Paycheck pc) { + double grosspay = classification.calculatePay(pc); + pc.setGrossPay(grosspay); + double deductions = affiliation.calculateDeductions(pc); + pc.setDeductions(deductions); + pc.setNetPay(grosspay - deductions); + paymentMethod.pay(pc); + + } + + public void setClassification(PaymentClassification classification) { + this.classification = classification; + } + + public void setSchedule(PaymentSchedule schedule) { + this.schedule = schedule; + } + + public void setPaymentMethod(PaymentMethod paymentMethod) { + this.paymentMethod = paymentMethod; + } +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/domain/HoldMethod.java b/students/313001956/src/main/java/com/coderising/payroll/domain/HoldMethod.java new file mode 100644 index 0000000000..0ce19e2291 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/domain/HoldMethod.java @@ -0,0 +1,11 @@ +package com.coderising.payroll.domain; + +public class HoldMethod implements PaymentMethod { + + @Override + public void pay(Paycheck pc) { + + + } + +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/domain/Paycheck.java b/students/313001956/src/main/java/com/coderising/payroll/domain/Paycheck.java new file mode 100644 index 0000000000..6f1ff99413 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/domain/Paycheck.java @@ -0,0 +1,35 @@ +package com.coderising.payroll.domain; + +import java.util.Date; +import java.util.Map; + +public class Paycheck { + private Date payPeriodStart; + private Date payPeriodEnd; + private double grossPay; + private double netPay; + private double deductions; + private Map itsFields; + public Paycheck(Date payPeriodStart, Date payPeriodEnd){ + this.payPeriodStart = payPeriodStart; + this.payPeriodEnd = payPeriodEnd; + } + public void setGrossPay(double grossPay) { + this.grossPay = grossPay; + + } + public void setDeductions(double deductions) { + this.deductions = deductions; + } + public void setNetPay(double netPay){ + this.netPay = netPay; + } + public Date getPayPeriodEndDate() { + + return this.payPeriodEnd; + } + public Date getPayPeriodStartDate() { + + return this.payPeriodStart; + } +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/domain/PaydayTransaction.java b/students/313001956/src/main/java/com/coderising/payroll/domain/PaydayTransaction.java new file mode 100644 index 0000000000..ddd6fc817e --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/domain/PaydayTransaction.java @@ -0,0 +1,23 @@ +package com.coderising.payroll.domain; + +import java.util.Date; +import java.util.List; + +import com.coderising.payroll.PayrollService; + +public class PaydayTransaction { + private Date date; + private PayrollService payrollService; + + public void execute() { + List employees = payrollService.getAllEmployees(); + for (Employee e : employees) { + if (e.isPayDay(date)) { + Paycheck pc = new Paycheck(e.getPayPeriodStartDate(date), date); + e.payDay(pc); + payrollService.savePaycheck(pc); + } + + } + } +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/domain/PaymentClassification.java b/students/313001956/src/main/java/com/coderising/payroll/domain/PaymentClassification.java new file mode 100644 index 0000000000..b6f2120bdb --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/domain/PaymentClassification.java @@ -0,0 +1,5 @@ +package com.coderising.payroll.domain; + +public interface PaymentClassification { + public double calculatePay(Paycheck pc); +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/domain/PaymentMethod.java b/students/313001956/src/main/java/com/coderising/payroll/domain/PaymentMethod.java new file mode 100644 index 0000000000..f07cc5354b --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/domain/PaymentMethod.java @@ -0,0 +1,5 @@ +package com.coderising.payroll.domain; + +public interface PaymentMethod { + public void pay(Paycheck pc); +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/domain/PaymentSchedule.java b/students/313001956/src/main/java/com/coderising/payroll/domain/PaymentSchedule.java new file mode 100644 index 0000000000..96788f4f80 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/domain/PaymentSchedule.java @@ -0,0 +1,8 @@ +package com.coderising.payroll.domain; + +import java.util.Date; + +public interface PaymentSchedule { + public boolean isPayDate(Date date); + public Date getPayPeriodStartDate( Date payPeriodEndDate); +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/domain/SalesReceipt.java b/students/313001956/src/main/java/com/coderising/payroll/domain/SalesReceipt.java new file mode 100644 index 0000000000..a7b0ba41ad --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/domain/SalesReceipt.java @@ -0,0 +1,14 @@ +package com.coderising.payroll.domain; + +import java.util.Date; + +public class SalesReceipt { + private Date saleDate; + private double amount; + public Date getSaleDate() { + return saleDate; + } + public double getAmount() { + return amount; + } +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/domain/ServiceCharge.java b/students/313001956/src/main/java/com/coderising/payroll/domain/ServiceCharge.java new file mode 100644 index 0000000000..88cf1d56dc --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/domain/ServiceCharge.java @@ -0,0 +1,16 @@ +package com.coderising.payroll.domain; + +import java.util.Date; + +public class ServiceCharge { + private Date date; + private int amount; + + public int getAmount() { + return amount; + } + + public Date getDate() { + return date; + } +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/domain/TimeCard.java b/students/313001956/src/main/java/com/coderising/payroll/domain/TimeCard.java new file mode 100644 index 0000000000..ebf6e17a4c --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/domain/TimeCard.java @@ -0,0 +1,15 @@ +package com.coderising.payroll.domain; + +import java.util.Date; + +public class TimeCard { + private Date date; + private int hours; + + public Date getDate() { + return date; + } + public int getHours() { + return hours; + } +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/schedule/BiweeklySchedule.java b/students/313001956/src/main/java/com/coderising/payroll/schedule/BiweeklySchedule.java new file mode 100644 index 0000000000..1ad42c1d19 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/schedule/BiweeklySchedule.java @@ -0,0 +1,38 @@ +package com.coderising.payroll.schedule; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +import com.coderising.payroll.domain.PaymentSchedule; +import com.coderising.payroll.util.DateUtil; + +public class BiweeklySchedule implements PaymentSchedule { + Date firstPayableFriday = DateUtil.parseDate("2017-6-2"); + + @Override + public boolean isPayDate(Date date) { + long daysBetween = DateUtil.getDaysBetween(firstPayableFriday, date); + + return daysBetween % 14 == 0; + } + + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.add(payPeriodEndDate, -13); + } + + public static void main(String[] args) throws Exception { + BiweeklySchedule schedule = new BiweeklySchedule(); + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date d = sdf.parse("2017-07-21"); + + System.out.println(schedule.isPayDate(d)); + + System.out.println(DateUtil.isFriday(d)); + + System.out.println(schedule.getPayPeriodStartDate(d)); + } + +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/schedule/MonthlySchedule.java b/students/313001956/src/main/java/com/coderising/payroll/schedule/MonthlySchedule.java new file mode 100644 index 0000000000..0f85b15a83 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/schedule/MonthlySchedule.java @@ -0,0 +1,22 @@ +package com.coderising.payroll.schedule; + +import java.util.Calendar; +import java.util.Date; + +import com.coderising.payroll.domain.PaymentSchedule; +import com.coderising.payroll.util.DateUtil; + +public class MonthlySchedule implements PaymentSchedule { + + @Override + public boolean isPayDate(Date date) { + return DateUtil.isLastDayOfMonth(date); + + } + + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.getFirstDay(payPeriodEndDate); + } + +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/schedule/WeeklySchedule.java b/students/313001956/src/main/java/com/coderising/payroll/schedule/WeeklySchedule.java new file mode 100644 index 0000000000..54a22ab7db --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/schedule/WeeklySchedule.java @@ -0,0 +1,19 @@ +package com.coderising.payroll.schedule; + +import java.util.Date; + +import com.coderising.payroll.domain.PaymentSchedule; +import com.coderising.payroll.util.DateUtil; + +public class WeeklySchedule implements PaymentSchedule { + + @Override + public boolean isPayDate(Date date) { + return DateUtil.isFriday(date); + } + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.add(payPeriodEndDate, -6); + } + +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/transaction/AddEmployeeTransaction.java b/students/313001956/src/main/java/com/coderising/payroll/transaction/AddEmployeeTransaction.java new file mode 100644 index 0000000000..f1727e1fd5 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/transaction/AddEmployeeTransaction.java @@ -0,0 +1,26 @@ +package com.coderising.payroll.transaction; + +import com.coderising.payroll.domain.Employee; +import com.coderising.payroll.domain.HoldMethod; +import com.coderising.payroll.domain.PaymentClassification; +import com.coderising.payroll.domain.PaymentMethod; +import com.coderising.payroll.domain.PaymentSchedule; + +public abstract class AddEmployeeTransaction { + private String name; + private String address; + public AddEmployeeTransaction(String name,String address){ + this.name = name; + this.address = address; + } + public abstract PaymentSchedule getPaymentSchedule(); + public abstract PaymentClassification getPaymentClassification(); + + public void execute(){ + Employee employee=new Employee(name, address); + employee.setClassification(getPaymentClassification()); + employee.setPaymentMethod(new HoldMethod()); + employee.setSchedule(getPaymentSchedule()); + //????????, ?? + } +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/transaction/AddHourlyEmployeeTransaction.java b/students/313001956/src/main/java/com/coderising/payroll/transaction/AddHourlyEmployeeTransaction.java new file mode 100644 index 0000000000..4db5905352 --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/transaction/AddHourlyEmployeeTransaction.java @@ -0,0 +1,27 @@ +package com.coderising.payroll.transaction; + +import com.coderising.payroll.classification.HourlyClassification; +import com.coderising.payroll.domain.PaymentClassification; +import com.coderising.payroll.domain.PaymentSchedule; +import com.coderising.payroll.schedule.WeeklySchedule; + +public class AddHourlyEmployeeTransaction extends AddEmployeeTransaction { + private double rate; + + public AddHourlyEmployeeTransaction(String name, String address, double hourlyRate) { + super(name, address); + this.rate = hourlyRate; + } + + @Override + public PaymentSchedule getPaymentSchedule() { + return new WeeklySchedule(); + } + + @Override + public PaymentClassification getPaymentClassification() { + return new HourlyClassification(rate); + + } + +} diff --git a/students/313001956/src/main/java/com/coderising/payroll/util/DateUtil.java b/students/313001956/src/main/java/com/coderising/payroll/util/DateUtil.java new file mode 100644 index 0000000000..1a9d28cc5c --- /dev/null +++ b/students/313001956/src/main/java/com/coderising/payroll/util/DateUtil.java @@ -0,0 +1,69 @@ +package com.coderising.payroll.util; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +public class DateUtil { + public static long getDaysBetween(Date d1, Date d2) { + + return (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24); + } + + public static Date parseDate(String txtDate) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + try { + return sdf.parse(txtDate); + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return null; + } + + } + + public static boolean isFriday(Date d) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(d); + return calendar.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY; + } + + public static Date add(Date d, int days) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(d); + calendar.add(Calendar.DAY_OF_MONTH, days); + return calendar.getTime(); + } + + public static boolean isLastDayOfMonth(Date d) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(d); + calendar.add(Calendar.MONTH, 1); + calendar.set(Calendar.DAY_OF_MONTH, 0); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + return sdf.format(d).equals(sdf.format(calendar.getTime())); + } + + public static Date getFirstDay(Date d) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(d); + calendar.set(Calendar.DAY_OF_MONTH, 1); + return calendar.getTime(); + } + + public static void main(String[] args) throws Exception { + System.out.println(DateUtil.isLastDayOfMonth(DateUtil.parseDate("2017-5-30"))); + + System.out.println(DateUtil.getFirstDay(DateUtil.parseDate("2017-6-30"))); + System.out.println(DateUtil.isFriday(DateUtil.parseDate("2017-7-28"))); + } + + public static boolean between(Date d, Date date1, Date date2) { + return d.after(date1) && d.before(date2); + } + + public static int getFridayCountBetween(Date date1, Date date2) { + return (int) (getDaysBetween(date1, date2) / 7); + } +} diff --git a/students/313001956/src/main/java/org/v0_my/Assert.java b/students/313001956/src/main/java/org/v0_my/Assert.java new file mode 100644 index 0000000000..c786200504 --- /dev/null +++ b/students/313001956/src/main/java/org/v0_my/Assert.java @@ -0,0 +1,225 @@ +package org.v0_my; + +/** + * A set of assert methods. + */ + +public class Assert { + /** + * Protect constructor since it is a static only class + */ + protected Assert() { + } + + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError with the given message. + */ + static public void assertTrue(String message, boolean condition) { + if (!condition) + fail(message); + } + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError. + */ + static public void assertTrue(boolean condition) { + assertTrue(null, condition); + } + /** + * Fails a test with the given message. + */ + static public void fail(String message) { + throw new AssertionFailedError(message); + } + /** + * Fails a test with no message. + */ + static public void fail() { + fail(null); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(String message, Object expected, Object actual) { + if (expected == null && actual == null) + return; + if (expected != null && expected.equals(actual)) + return; + failNotEquals(message, expected, actual); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(Object expected, Object actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, double expected, double actual, double delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Double.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Double(expected), new Double(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) // Because comparison with NaN always returns false + failNotEquals(message, new Double(expected), new Double(actual)); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(double expected, double actual, double delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, float expected, float actual, float delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Float.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Float(expected), new Float(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) + failNotEquals(message, new Float(expected), new Float(actual)); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(float expected, float actual, float delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(String message, long expected, long actual) { + assertEquals(message, new Long(expected), new Long(actual)); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(long expected, long actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(String message, boolean expected, boolean actual) { + assertEquals(message, new Boolean(expected), new Boolean(actual)); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(boolean expected, boolean actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(String message, byte expected, byte actual) { + assertEquals(message, new Byte(expected), new Byte(actual)); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(byte expected, byte actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(String message, char expected, char actual) { + assertEquals(message, new Character(expected), new Character(actual)); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(char expected, char actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(String message, short expected, short actual) { + assertEquals(message, new Short(expected), new Short(actual)); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(short expected, short actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(String message, int expected, int actual) { + assertEquals(message, new Integer(expected), new Integer(actual)); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(int expected, int actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(Object object) { + assertNotNull(null, object); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(String message, Object object) { + assertTrue(message, object != null); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(Object object) { + assertNull(null, object); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(String message, Object object) { + assertTrue(message, object == null); + } + /** + * Asserts that two objects refer to the same object. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertSame(String message, Object expected, Object actual) { + if (expected == actual) + return; + failNotSame(message, expected, actual); + } + /** + * Asserts that two objects refer to the same object. If they are not + * the same an AssertionFailedError is thrown. + */ + static public void assertSame(Object expected, Object actual) { + assertSame(null, expected, actual); + } + + static private void failNotEquals(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected:<"+expected+"> but was:<"+actual+">"); + } + + static private void failNotSame(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected same"); + } +} diff --git a/students/313001956/src/main/java/org/v0_my/AssertionFailedError.java b/students/313001956/src/main/java/org/v0_my/AssertionFailedError.java new file mode 100644 index 0000000000..51c2c0559f --- /dev/null +++ b/students/313001956/src/main/java/org/v0_my/AssertionFailedError.java @@ -0,0 +1,12 @@ +package org.v0_my; + +public class AssertionFailedError extends Error { +public AssertionFailedError(){ + +} + + public AssertionFailedError(String message) { + // TODO Auto-generated constructor stub + super(message); + } +} diff --git a/students/313001956/src/main/java/org/v0_my/Test.java b/students/313001956/src/main/java/org/v0_my/Test.java new file mode 100644 index 0000000000..e7f7cc5159 --- /dev/null +++ b/students/313001956/src/main/java/org/v0_my/Test.java @@ -0,0 +1,7 @@ +package org.v0_my; + +public interface Test { + public void run(TestResult testResult); + + public Integer getCaseCount(); +} diff --git a/students/313001956/src/main/java/org/v0_my/TestCase.java b/students/313001956/src/main/java/org/v0_my/TestCase.java new file mode 100644 index 0000000000..ca569bf942 --- /dev/null +++ b/students/313001956/src/main/java/org/v0_my/TestCase.java @@ -0,0 +1,75 @@ +package org.v0_my; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +public abstract class TestCase extends Assert implements Test { + private String name; + + public TestCase(String name) { + this.name = name; + // TODO Auto-generated constructor stub + } + + @Override + public void run(TestResult testResult) { + testResult.run(this); + } + + public void doRun(TestResult testResult) throws Throwable { + setUp(); + try { + runTest(); + + } finally { + tearDown(); + } + } + + protected void setUp() { + + } + + protected void runTest() throws Throwable { + Class clazz = this.getClass(); + Method method=null; + try { + method = clazz.getDeclaredMethod(name); + + } catch (NoSuchMethodException | SecurityException e1) { + // TODO Auto-generated catch block + // e1.printStackTrace(); + } + + if(!Modifier.isPublic(method.getModifiers())){ + fail("method "+name+" is not a public menthod!"); + } + + try { + method.invoke(this); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + // TODO Auto-generated catch block + // e.printStackTrace(); + + Throwable ta = e.getCause(); + // if (ta instanceof AssertionFailedError) { + throw ta; + // } + + } + + } + + protected void tearDown() { + + } + + @Override + public Integer getCaseCount() { + return 1; + } + +} diff --git a/students/313001956/src/main/java/org/v0_my/TestFailure.java b/students/313001956/src/main/java/org/v0_my/TestFailure.java new file mode 100644 index 0000000000..b26b440396 --- /dev/null +++ b/students/313001956/src/main/java/org/v0_my/TestFailure.java @@ -0,0 +1,21 @@ +package org.v0_my; + +public class TestFailure { + + private Test test; + private Throwable throwable; + + public TestFailure(Test test, Throwable throwable) { + // TODO Auto-generated constructor stub + this.test = test; + this.throwable = throwable; + } + + public Test getTestCase() { + return this.test; + } + + public Throwable getThrowable() { + return this.throwable; + } +} diff --git a/students/313001956/src/main/java/org/v0_my/TestResult.java b/students/313001956/src/main/java/org/v0_my/TestResult.java new file mode 100644 index 0000000000..c25d5b6bf3 --- /dev/null +++ b/students/313001956/src/main/java/org/v0_my/TestResult.java @@ -0,0 +1,109 @@ +package org.v0_my; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.v0_my.runner.TestListener; + +public class TestResult { + + private List fails; + private List errs; + private int testCount; + private List listeners; + + public TestResult() { + // TODO Auto-generated constructor stub + fails = new ArrayList<>(); + errs = new ArrayList<>(); + listeners = new ArrayList<>(); + testCount = 0; + } + + public int failsCount() { + return fails.size(); + } + + public void run(final TestCase test) { + // TODO Auto-generated method stub + startTest(test); + try { + test.doRun(this); + } catch (AssertionFailedError e) { + addFail(test, e); + } catch (Throwable e) { + addErr(test, e); + } finally { + endTest(test); + } + } + + private void endTest(Test test) { + // TODO Auto-generated method stub + for (Iterator iter = listeners(); iter.hasNext();) { + TestListener listener = iter.next(); + listener.endTest(test); + } + } + + private void startTest(Test test) { + // TODO Auto-generated method stub + testCount += test.getCaseCount(); + + for (Iterator iter = listeners(); iter.hasNext();) { + TestListener listener = iter.next(); + listener.startTest(test); + } + } + + private void addErr(final Test test, Throwable e) { + errs.add(new TestFailure(test, e)); + + for (Iterator iter = listeners(); iter.hasNext();) { + TestListener listener = iter.next(); + listener.addErr(test, e); + } + } + + private void addFail(final Test test, AssertionFailedError e) { + fails.add(new TestFailure(test, e)); + for (Iterator iter = listeners(); iter.hasNext();) { + TestListener listener = iter.next(); + listener.addFail(test, e); + } + } + + public Iterator fails() { + return fails.iterator(); + } + + public Iterator errs() { + return errs.iterator(); + } + + public int errsCount() { + // TODO Auto-generated method stub + return errs.size(); + } + + public int runCount() { + return testCount; + } + + public boolean isSuccesful() { + return failsCount() == 0 && errsCount() == 0; + } + + public void addListener(TestListener listener) { + listeners.add(listener); + } + + public void removeListener(TestListener listener) { + listeners.remove(listener); + } + + private Iterator listeners() { + return listeners.iterator(); + } +} diff --git a/students/313001956/src/main/java/org/v0_my/TestTuite.java b/students/313001956/src/main/java/org/v0_my/TestTuite.java new file mode 100644 index 0000000000..bdc551bf15 --- /dev/null +++ b/students/313001956/src/main/java/org/v0_my/TestTuite.java @@ -0,0 +1,140 @@ +package org.v0_my; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class TestTuite extends Assert implements Test { + List caselist = new ArrayList<>(10); + List namelist = new ArrayList<>(); + private String name; + + public TestTuite(String name) { + this.name = name; + } + + public TestTuite(final Class clazz) { + // TODO Auto-generated constructor stub + if (!Modifier.isPublic(clazz.getModifiers())) { + fail("the class " + clazz.getName() + " must be public"); + } + Constructor constructor = getConstructor(clazz); + Method[] arrmethod = clazz.getDeclaredMethods(); + for (Method m : arrmethod) { + addTest(m, constructor); + } + + if (arrmethod.length == 0) { + fail("there is no method to test!"); + } + } + + private Constructor getConstructor(Class clazz) { + // TODO Auto-generated method stub + Class[] parameterTypes = new Class[] { String.class }; + Constructor constructor = null; + try { + constructor = clazz.getConstructor(parameterTypes); + } catch (NoSuchMethodException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return constructor; + } + + public void addTest(Method m, Constructor constructor) { + if (!isTestMethod(m)) { + return; + } + String method_name = m.getName(); + if (namelist.contains(method_name)) { + return; + } + namelist.add(method_name); + Object[] initargs = new Object[] { method_name }; + try { + Test t = (Test) constructor.newInstance(initargs); + addTest(t); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException + | InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public void addTest(Test t) { + caselist.add(t); + } + + public void addTest(Class clazz) { + Object obj = null; + try { + obj = clazz.newInstance(); + } catch (InstantiationException | IllegalAccessException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + Method method = null; + try { + Class[] args = new Class[0]; + method=clazz.getMethod("tuite", args); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + try { + Test test = (Test) method.invoke(obj); + addTest(test); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + private boolean isTestMethod(Method m) { + + return m.getName().startsWith("test") && Modifier.isPublic(m.getModifiers()) + && m.getParameterTypes().length == 0 && m.getReturnType().equals(Void.TYPE); + } + + @Override + public void run(TestResult testResult) { + // TODO Auto-generated method stub + for (Test tc : caselist) { + tc.run(testResult); + + } + } + + @Override + public Integer getCaseCount() { + // TODO Auto-generated method stub + int count = 0; + for (Iterator iterator = caselist.iterator(); iterator.hasNext();) { + Test test = iterator.next(); + count += test.getCaseCount(); + } + return count; + } + + public void addTestTuite(Class clazz) { + addTest(new TestTuite(clazz)); + } + +} diff --git a/students/313001956/src/main/java/org/v0_my/extension/RepeatedTest.java b/students/313001956/src/main/java/org/v0_my/extension/RepeatedTest.java new file mode 100644 index 0000000000..f63d9f4938 --- /dev/null +++ b/students/313001956/src/main/java/org/v0_my/extension/RepeatedTest.java @@ -0,0 +1,28 @@ +package org.v0_my.extension; + +import org.v0_my.Test; +import org.v0_my.TestResult; + +public class RepeatedTest extends TestDecorator { + + private int num; + + public RepeatedTest(Test t, int num) { + super(t); + if (num < 0) { + throw new IllegalArgumentException("num must be >0"); + } + this.num = num; + // TODO Auto-generated constructor stub + } + + @Override + public void run(TestResult testResult) { + // TODO Auto-generated method stub + for (int i = 0; i < num; i++) { + super.run(testResult); + } + + } + +} diff --git a/students/313001956/src/main/java/org/v0_my/extension/TestDecorator.java b/students/313001956/src/main/java/org/v0_my/extension/TestDecorator.java new file mode 100644 index 0000000000..f597621c9e --- /dev/null +++ b/students/313001956/src/main/java/org/v0_my/extension/TestDecorator.java @@ -0,0 +1,32 @@ +package org.v0_my.extension; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +import org.v0_my.Test; +import org.v0_my.TestResult; + +public class TestDecorator implements Test { + + Test test; + + public TestDecorator(Test test) { + // TODO Auto-generated constructor stub + this.test = test; + } + + + + @Override + public void run(TestResult testResult) { + test.run(testResult); + } + + @Override + public Integer getCaseCount() { + // TODO Auto-generated method stub + return test.getCaseCount(); + } + +} diff --git a/students/313001956/src/main/java/org/v0_my/extension/TestSetup.java b/students/313001956/src/main/java/org/v0_my/extension/TestSetup.java new file mode 100644 index 0000000000..833635d4dc --- /dev/null +++ b/students/313001956/src/main/java/org/v0_my/extension/TestSetup.java @@ -0,0 +1,34 @@ +package org.v0_my.extension; + +import org.v0_my.Test; +import org.v0_my.TestResult; + +public class TestSetup extends TestDecorator { + + public TestSetup(Test t) { + super(t); + + // TODO Auto-generated constructor stub + } + + @Override + public void run(TestResult testResult) { + // TODO Auto-generated method stub + setup(); + super.run(testResult); + teardown(); + } + + private void teardown() { + // TODO Auto-generated method stub + System.out.println(); + System.out.println("this is alltest teardown."); + } + + private void setup() { + // TODO Auto-generated method stub + + System.out.println("this is alltest setup"); + } + +} diff --git a/students/313001956/src/main/java/org/v0_my/runner/TestBaseRunner.java b/students/313001956/src/main/java/org/v0_my/runner/TestBaseRunner.java new file mode 100644 index 0000000000..5557d164ec --- /dev/null +++ b/students/313001956/src/main/java/org/v0_my/runner/TestBaseRunner.java @@ -0,0 +1,44 @@ +package org.v0_my.runner; + +import java.io.PrintStream; +import java.text.NumberFormat; + +import org.v0_my.AssertionFailedError; +import org.v0_my.Test; + +public class TestBaseRunner implements TestListener { + private PrintStream pStream = System.out; + int column = 0; + + @Override + public synchronized void endTest(Test test) { + // TODO Auto-generated method stub + // pStream.println(); + } + + @Override + public synchronized void startTest(Test test) { + // TODO Auto-generated method stub + pStream.print("."); + if (++column > 20) { + pStream.println(); + column = 0; + } + } + + @Override + public synchronized void addErr(Test test, Throwable e) { + // TODO Auto-generated method stub + pStream.print("E"); + } + + @Override + public synchronized void addFail(Test test, AssertionFailedError e) { + // TODO Auto-generated method stub + pStream.print("F"); + } +public String formatNum(long num) { + return NumberFormat.getInstance().format((double)(num/1000)); +} + +} diff --git a/students/313001956/src/main/java/org/v0_my/runner/TestListener.java b/students/313001956/src/main/java/org/v0_my/runner/TestListener.java new file mode 100644 index 0000000000..e834267a4d --- /dev/null +++ b/students/313001956/src/main/java/org/v0_my/runner/TestListener.java @@ -0,0 +1,14 @@ +package org.v0_my.runner; + +import org.v0_my.AssertionFailedError; +import org.v0_my.Test; + +public interface TestListener { + public void endTest(Test test); + + public void startTest(Test test); + + public void addErr(final Test test, Throwable e) ; + + public void addFail(final Test test, AssertionFailedError e); +} diff --git a/students/313001956/src/main/java/org/v0_my/runner/TestRunner.java b/students/313001956/src/main/java/org/v0_my/runner/TestRunner.java new file mode 100644 index 0000000000..ef63109496 --- /dev/null +++ b/students/313001956/src/main/java/org/v0_my/runner/TestRunner.java @@ -0,0 +1,72 @@ +package org.v0_my.runner; + +import java.io.PrintStream; +import java.util.Iterator; + +import org.v0_my.Test; +import org.v0_my.TestFailure; +import org.v0_my.TestResult; +import org.v0_my.sample.AllTest; + +public class TestRunner extends TestBaseRunner { + + private PrintStream ps = System.out; + + public static void main(String[] args) { + + Test test = AllTest.tuite(); + TestResult tr = new TestResult(); + TestRunner runner = new TestRunner(); + tr.addListener(runner); + long t1 = System.currentTimeMillis(); + test.run(tr); + long t2 = System.currentTimeMillis(); + runner.ps.println(); + runner.ps.println("Time:" + runner.formatNum(t2 - t1) + "s"); + + runner.printResult(tr); + + } + + private void printResult(TestResult tr) { + printFails(tr); + printErrs(tr); + printSummary(tr); + } + + private void printSummary(TestResult tr) { + // TODO Auto-generated method stub + String result = tr.isSuccesful() ? "Success" : "Fail"; + ps.println(result); + ps.println("Test run:" + tr.runCount() + ",Failures:" + tr.failsCount() + ",Errs:" + tr.errsCount()); + } + + private void printErrs(TestResult tr) { + // TODO Auto-generated method stub + int count = tr.errsCount(); + String s = count > 1 ? "there were " + count + " errs" : "there was " + count + " err"; + ps.println(s); + int i = 1; + for (Iterator iter = tr.errs(); iter.hasNext();) { + TestFailure failure = iter.next(); + ps.print((i++) + ")"); + ps.println(failure.getTestCase()); + ps.println(failure.getThrowable()); + } + } + + private void printFails(TestResult tr) { + // TODO Auto-generated method stub + int count = tr.failsCount(); + String s = count > 1 ? "there were " + count + " fails" : "there was " + count + " fail"; + ps.println(s); + int i = 1; + for (Iterator iter = tr.fails(); iter.hasNext();) { + TestFailure failure = iter.next(); + ps.print((i++) + ")"); + ps.println(failure.getTestCase()); + ps.println(failure.getThrowable()); + } + } + +} diff --git a/students/313001956/src/main/java/org/v0_my/sample/AllTest.java b/students/313001956/src/main/java/org/v0_my/sample/AllTest.java new file mode 100644 index 0000000000..1468d14090 --- /dev/null +++ b/students/313001956/src/main/java/org/v0_my/sample/AllTest.java @@ -0,0 +1,20 @@ +package org.v0_my.sample; + +import org.v0_my.Test; +import org.v0_my.TestTuite; +import org.v0_my.extension.RepeatedTest; +import org.v0_my.sample.caculator.CalculatorTuite; +import org.v0_my.sample.person.PersonTest; + +import junit.extensions.TestSetup; + +public class AllTest { +public static Test tuite() { + TestTuite tuite=new TestTuite("AllTest"); + tuite.addTest(CalculatorTuite.tuite()); + //tuite.addTestTuite(PersonTest.class); + //return tuite; + tuite.addTest(new RepeatedTest(new TestTuite(PersonTest.class), 1)); + return new org.v0_my.extension.TestSetup(tuite); +} +} diff --git a/students/313001956/src/main/java/org/v0_my/sample/caculator/CaculatorTestCase.java b/students/313001956/src/main/java/org/v0_my/sample/caculator/CaculatorTestCase.java new file mode 100644 index 0000000000..ee3e47be0c --- /dev/null +++ b/students/313001956/src/main/java/org/v0_my/sample/caculator/CaculatorTestCase.java @@ -0,0 +1,51 @@ +package org.v0_my.sample.caculator; + +import org.junit.experimental.theories.Theories; +import org.v0_my.TestCase; + +public class CaculatorTestCase extends TestCase { + + Calculator calculator = null; + + public CaculatorTestCase(String name) { + super(name); + // TODO Auto-generated constructor stub + } + + public void setUp() { + // TODO Auto-generated method stub + calculator = new Calculator(); + } + + public void tearDown() { + // TODO Auto-generated method stub + calculator = null; + } + + public void testAdd() { + + calculator.add(10); + int a=0; + int b=1/a; + assertEquals(10, calculator.getResult()); + System.out.println("testadd"); + } + + public void testSubtract() { + calculator.add(10); + calculator.subtract(5); + assertEquals(4, calculator.getResult()); + System.out.println("testSubtract"); + } + + public static void main(String[] args) { + // TestCase testCase = new CaculatorTestCase("testAdd"); + // testCase.run(); +// Test tt = new TestTuite(CaculatorTestCase.class); +// TestResult testResult=new TestResult(); +// tt.run(testResult); +// System.out.println(testResult.getFailtestCount()); +// System.out.println(testResult.getErrtestCount()); + } + +} diff --git a/students/313001956/src/main/java/org/v0_my/sample/caculator/Calculator.java b/students/313001956/src/main/java/org/v0_my/sample/caculator/Calculator.java new file mode 100644 index 0000000000..19ecae3af4 --- /dev/null +++ b/students/313001956/src/main/java/org/v0_my/sample/caculator/Calculator.java @@ -0,0 +1,22 @@ +package org.v0_my.sample.caculator; + +public class Calculator { + + private int result = 0; + public void add(int x){ + result += x; + } + public void subtract(int x){ + result -=x; + } + + public int getResult(){ + return this.result; + } + public static void main(String[] args){ + Calculator calculator = new Calculator(); + calculator.add(10); + calculator.subtract(5); + System.out.println(calculator.getResult()); + } +} diff --git a/students/313001956/src/main/java/org/v0_my/sample/caculator/CalculatorTuite.java b/students/313001956/src/main/java/org/v0_my/sample/caculator/CalculatorTuite.java new file mode 100644 index 0000000000..9f846339ed --- /dev/null +++ b/students/313001956/src/main/java/org/v0_my/sample/caculator/CalculatorTuite.java @@ -0,0 +1,12 @@ +package org.v0_my.sample.caculator; + +import org.v0_my.Test; +import org.v0_my.TestTuite; + +public class CalculatorTuite { +public static Test tuite() { + TestTuite tuite=new TestTuite("CalculatorTuite"); + tuite.addTestTuite(CaculatorTestCase.class); + return tuite; +} +} diff --git a/students/313001956/src/main/java/org/v0_my/sample/person/PersonTest.java b/students/313001956/src/main/java/org/v0_my/sample/person/PersonTest.java new file mode 100644 index 0000000000..eb8ae4585c --- /dev/null +++ b/students/313001956/src/main/java/org/v0_my/sample/person/PersonTest.java @@ -0,0 +1,38 @@ +package org.v0_my.sample.person; + +import org.v0_my.TestCase; + +public class PersonTest extends TestCase { + + Person p = null; + protected void setUp() { + p = new Person("andy",30); + } + public PersonTest(String name) { + super(name); + } + public void testAge(){ + this.assertEquals(31, p.getAge()); + } + public void testName(){ + this.assertEquals("andy1", p.getName()); + } +} +class Person{ + private String name; + private int age; + + public Person(String name, int age) { + + this.name = name; + this.age = age; + } + public String getName() { + return name; + } + public int getAge() { + return age; + } + + +} diff --git a/students/315863321/ood/ood-assignment/pom.xml b/students/315863321/ood/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/315863321/ood/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java new file mode 100644 index 0000000000..ba80f9de7d --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java @@ -0,0 +1,13 @@ +package com.coderising.ood.ocp; + +/** + * Created by john on 2017/6/20. + */ +public class DateUtil { + + public static String getCurrentDateAsString() { + + return null; + } + +} \ No newline at end of file diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/FormatByDate.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/FormatByDate.java new file mode 100644 index 0000000000..8fcc9464cf --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/FormatByDate.java @@ -0,0 +1,12 @@ +package com.coderising.ood.ocp; + +/** + * Created by john on 2017/6/20. + */ +public class FormatByDate implements FormatLog { + @Override + public String format(String msg) { + String txtDate = DateUtil.getCurrentDateAsString(); + return txtDate + ": " + msg; + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/FormatByRaw.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/FormatByRaw.java new file mode 100644 index 0000000000..7f66cf725f --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/FormatByRaw.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp; + +/** + * Created by john on 2017/6/20. + */ +public class FormatByRaw implements FormatLog { + @Override + public String format(String msg) { + return msg; + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/FormatLog.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/FormatLog.java new file mode 100644 index 0000000000..6349f02b13 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/FormatLog.java @@ -0,0 +1,9 @@ +package com.coderising.ood.ocp; + +/** + * Created by john on 2017/6/20. + */ +public interface FormatLog { + + String format(String msg); +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java new file mode 100644 index 0000000000..e107cfd906 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java @@ -0,0 +1,21 @@ +package com.coderising.ood.ocp; + +/** + * Created by john on 2017/6/20. + */ +public class Logger { + private FormatLog formatLog; + private SendLog sendLog; + + public Logger(FormatLog f, SendLog s) { + this.formatLog = f; + this.sendLog = s; + } + + public void log(String msg) { + + String logMsg = formatLog.format(msg); + sendLog.send(logMsg); + + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java new file mode 100644 index 0000000000..42657a6066 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java @@ -0,0 +1,12 @@ +package com.coderising.ood.ocp; + +/** + * Created by john on 2017/6/20. + */ +public class MailUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/README.md b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/README.md new file mode 100644 index 0000000000..35b2240cbd --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/README.md @@ -0,0 +1,4 @@ +ocp(开闭原则): +一个软件实体如类、模块和函数应该对扩展开放,对修改关闭。 + + diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java new file mode 100644 index 0000000000..3b2add666c --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp; + +/** + * Created by john on 2017/6/20. + */ +public class SMSUtil { + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SendLog.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SendLog.java new file mode 100644 index 0000000000..e9a2ed4c30 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SendLog.java @@ -0,0 +1,8 @@ +package com.coderising.ood.ocp; + +/** + * Created by john on 2017/6/20. + */ +public interface SendLog { + void send(String msg); +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SendLogByMail.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SendLogByMail.java new file mode 100644 index 0000000000..047aab0bd9 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SendLogByMail.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp; + +/** + * Created by john on 2017/6/20. + */ +public class SendLogByMail implements SendLog { + @Override + public void send(String msg) { + MailUtil.send(msg); + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SendLogByPrint.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SendLogByPrint.java new file mode 100644 index 0000000000..86be0bc442 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SendLogByPrint.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp; + +/** + * Created by john on 2017/6/20. + */ +public class SendLogByPrint implements SendLog { + @Override + public void send(String msg) { + System.out.println(msg); + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SendLogBySMS.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SendLogBySMS.java new file mode 100644 index 0000000000..0898cb2f27 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SendLogBySMS.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp; + +/** + * Created by john on 2017/6/20. + */ +public class SendLogBySMS implements SendLog { + @Override + public void send(String msg) { + SMSUtil.send(msg); + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Build.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Build.java new file mode 100644 index 0000000000..e8ea1476cd --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Build.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +/** + * Created by john on 2017/6/14. + */ +public abstract class Build { + Reader reader = null; + + abstract void build(); + + public Reader getReader() { + return reader; + } + + public void setReader(Reader reader) { + this.reader = reader; + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/BuildMail.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/BuildMail.java new file mode 100644 index 0000000000..b1176d9eff --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/BuildMail.java @@ -0,0 +1,59 @@ +package com.coderising.ood.srp; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +/** + * Created by john on 2017/6/14. + */ +public class BuildMail extends Build{ + List mailList; + Product product; + Mail mail; + Configuration config = new Configuration(); + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public BuildMail(List mailList, Product product) { + this.mailList = mailList; + this.product = product; + } + void build() { + List list = reader.read(); + if (list != null) { + Iterator iter = list.iterator(); + while (iter.hasNext()) { + mail = new Mail(); + mail.setSubject(config.getProperty(ConfigurationKeys.SUBJECT)); + mail.setFromAddress(config.getProperty(ConfigurationKeys.EMAIL_ADMIN)); + try { + configureEMail((HashMap) iter.next()); + } catch (IOException e) { + e.printStackTrace(); + } + this.mailList.add(mail); + } + + } + + } + + protected void configureEMail(HashMap userInfo) throws IOException { + mail.setToAddress((String) userInfo.get(EMAIL_KEY)); + if (mail.getToAddress().length() > 0) + setMessage(userInfo); + } + + protected void setMessage(HashMap userInfo) throws IOException { + + String name = (String) userInfo.get(NAME_KEY); + + mail.setMessage("尊敬的 "+name+", 您关注的产品 " + this.product.getProductDesc() + " 降价了,欢迎购买!"); + + + } + +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/BuildMailServer.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/BuildMailServer.java new file mode 100644 index 0000000000..eebc5946c6 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/BuildMailServer.java @@ -0,0 +1,20 @@ +package com.coderising.ood.srp; + +import java.util.List; + +/** + * Created by john on 2017/6/14. + */ +public class BuildMailServer extends Build{ + private MailServer mailServer; + + public BuildMailServer(MailServer mailServer) { + this.mailServer = mailServer; + } + void build() { + List data = reader.read(); + mailServer.setSmtpHost((String) data.get(0)); + mailServer.setAltSmtpHost((String) data.get(1)); + } + +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/BuildProduct.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/BuildProduct.java new file mode 100644 index 0000000000..0c8a66942e --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/BuildProduct.java @@ -0,0 +1,21 @@ +package com.coderising.ood.srp; + +import java.util.List; + +/** + * Created by john on 2017/6/14. + */ +public class BuildProduct extends Build{ + private Product product; + + public BuildProduct(Product product) { + this.product = product; + } + void build() { + List data = reader.read(); + product.setProductID((String) data.get(0)); + product.setProductDesc((String) data.get(1)); + } + + +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..815afc3101 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,34 @@ +package com.coderising.ood.srp; + +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap(); + static final String QUERY = "Select name from subscriptions " + + "where product_id= '" + "%s" +"' " + + "and send_mail=1 "; + + static { + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + configurations.put(ConfigurationKeys.SEND_MAIL_QUERY, QUERY); + configurations.put(ConfigurationKeys.SUBJECT, "您关注的产品降价了"); + + } + + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + + +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..afda0b749f --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,11 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + public static final String SEND_MAIL_QUERY = "email.query"; + public static final String SUBJECT = "email.subject"; + +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java new file mode 100644 index 0000000000..5d8d222aed --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java @@ -0,0 +1,44 @@ +package com.coderising.ood.srp; + +/** + * Created by john on 2017/6/14. + */ + +public class Mail { + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailServer.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailServer.java new file mode 100644 index 0000000000..07a8d588e6 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailServer.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; + +/** + * Created by john on 2017/6/14. + */ +public class MailServer { + protected String smtpHost = null; + protected String altSmtpHost = null; + + public String getSmtpHost() { + return smtpHost; + } + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..3346dfb597 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(Mail mail, MailServer mailServer, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(mail.getFromAddress()).append("\n"); + buffer.append("To:").append(mail.getToAddress()).append("\n"); + buffer.append("Subject:").append(mail.getSubject()).append("\n"); + buffer.append("Content:").append(mail.getMessage()).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..a3027a26cc --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; + +/** + * Created by john on 2017/6/14. + */ +public class Product { + private String productID = null; + private String productDesc = null; + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..93fce8bbbd --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,76 @@ +package com.coderising.ood.srp; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + private Product product = new Product(); + private MailServer mailServer = new MailServer(); + private List mailList = new ArrayList(); + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + public static void main(String[] args) throws Exception { + + File f = new File("/Users/john/Documents/mygit_2/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail promotionMail = new PromotionMail(); + //配置产品 + Build build = new BuildProduct(promotionMail.product); + build.setReader(new ReadFromFile(f)); + build.build(); + + //配置邮件服务器 + build = new BuildMailServer(promotionMail.mailServer); + build.setReader(new ReadFromMap()); + build.build(); + + //配置邮件 + build = new BuildMail(promotionMail.mailList, promotionMail.product); + build.setReader(new ReadFromDatabase(promotionMail.product)); + build.build(); + //发送邮件 + promotionMail.sendEMails(emailDebug, promotionMail.mailList); + + + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + Mail mail = (Mail) iter.next(); + try { + if (mail.getToAddress().length() > 0) { + MailUtil.sendEmail(mail, mailServer, debug); + + } + } catch (Exception e) { + + try { + MailUtil.sendEmail(mail, mailServer, debug); + + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/README.md b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/README.md new file mode 100644 index 0000000000..34afa8edb8 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/README.md @@ -0,0 +1,4 @@ +srp(单一职责原则): +应该有且仅有一个原因引起类的变更,也就是接口或类和职责的关系是一一对应的。 + + diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ReadFromDatabase.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ReadFromDatabase.java new file mode 100644 index 0000000000..e3f6f2bae8 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ReadFromDatabase.java @@ -0,0 +1,21 @@ +package com.coderising.ood.srp; + +import java.util.List; + +/** + * Created by john on 2017/6/14. + */ +public class ReadFromDatabase extends Reader { + Configuration config = new Configuration(); + Product product = null; + + public ReadFromDatabase(Product product) { + this.product = product; + } + + List read() { + System.out.println("loadQuery set"); + return DBUtil.query(config.getProperty(String.format(ConfigurationKeys.SEND_MAIL_QUERY, product.getProductID()))); + + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ReadFromFile.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ReadFromFile.java new file mode 100644 index 0000000000..a3a7eb2d5f --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ReadFromFile.java @@ -0,0 +1,44 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +/** + * Created by john on 2017/6/13. + */ +public class ReadFromFile extends Reader{ + + + public ReadFromFile(File file) { + super(file); + } + + List read() { + BufferedReader br = null; + List data = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + data = Arrays.asList(temp.split(" ")); + } catch (IOException e) { + try { + throw new IOException(e.getMessage()); + } catch (IOException e1) { + e1.printStackTrace(); + } + } finally { + try { + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + System.out.println("产品ID = " + data.get(0) + "\n"); + System.out.println("产品描述 = " + data.get(1) + "\n"); + return data; + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ReadFromMap.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ReadFromMap.java new file mode 100644 index 0000000000..880f297411 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ReadFromMap.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by john on 2017/6/14. + */ +public class ReadFromMap extends Reader{ + Configuration config = new Configuration(); + + List read() { + List list = new ArrayList(); + list.add(config.getProperty(ConfigurationKeys.SMTP_SERVER)); + list.add(config.getProperty((ConfigurationKeys.ALT_SMTP_SERVER))); + return list; + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Reader.java b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Reader.java new file mode 100644 index 0000000000..7e59a0bb68 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Reader.java @@ -0,0 +1,22 @@ +package com.coderising.ood.srp; + +import java.io.File; +import java.util.List; + +/** + * Created by john on 2017/6/14. + */ +public abstract class Reader { + File file; + + public Reader(File file) { + this.file = file; + } + + public Reader() { + + } + + abstract List read(); + +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/extension/RepeatedTest.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/extension/RepeatedTest.java new file mode 100644 index 0000000000..05cc2f3f61 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/extension/RepeatedTest.java @@ -0,0 +1,34 @@ +package org.litejunit.extension; + +import org.litejunit.v2.Test; +import org.litejunit.v2.TestResult; + +/** + * Created by john on 2017/9/2. + */ +public class RepeatedTest extends TestDecorator { + private int fTimesRepeat; + + public RepeatedTest(Test test, int repeat) { + super(test); + if (repeat < 0) + throw new IllegalArgumentException("Repetition count must be > 0"); + fTimesRepeat = repeat; + } + + public int countTestCases() { + return super.countTestCases() * fTimesRepeat; + } + + public void run(TestResult result) { + for (int i = 0; i < fTimesRepeat; i++) { + if (result.shouldStop()) + break; + super.run(result); + } + } + + public String toString() { + return super.toString() + "(repeated)"; + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/extension/TestDecorator.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/extension/TestDecorator.java new file mode 100644 index 0000000000..8feb61e3ab --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/extension/TestDecorator.java @@ -0,0 +1,39 @@ +package org.litejunit.extension; + +import org.litejunit.v2.Assert; +import org.litejunit.v2.Test; +import org.litejunit.v2.TestResult; + +/** + * Created by john on 2017/9/2. + */ +public class TestDecorator extends Assert implements Test { + protected Test test; + + public TestDecorator(Test test) { + this.test = test; + } + + /** + * The basic run behaviour. + */ + public void basicRun(TestResult result) { + test.run(result); + } + + public int countTestCases() { + return test.countTestCases(); + } + + public void run(TestResult result) { + basicRun(result); + } + + public String toString() { + return test.toString(); + } + + public Test getTest() { + return test; + } +} \ No newline at end of file diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/sample/calculator/Calculator.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/sample/calculator/Calculator.java new file mode 100644 index 0000000000..00a31b795b --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/sample/calculator/Calculator.java @@ -0,0 +1,28 @@ +package org.litejunit.sample.calculator; + +/** + * Created by john on 2017/8/29. + */ +public class Calculator { + + private int result = 0; + + public void add(int x) { + result += x; + } + + public void subtract(int x) { + result -= x; + } + + public int getResult() { + return this.result; + } + + public static void main(String[] args) { + Calculator calculator = new Calculator(); + calculator.add(10); + calculator.subtract(5); + System.out.println(calculator.getResult()); + } +} \ No newline at end of file diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/sample/calculator/CalculatorTest.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/sample/calculator/CalculatorTest.java new file mode 100644 index 0000000000..a502082b63 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/sample/calculator/CalculatorTest.java @@ -0,0 +1,55 @@ +package org.litejunit.sample.calculator; + + +import org.litejunit.v1.TestCase; +import org.litejunit.v1.TestResult; +import org.litejunit.v1.TestSuite; + +import static org.litejunit.v1.Assert.assertEquals; + +/** + * Created by john on 2017/8/29. + */ +public class CalculatorTest extends TestCase { + public CalculatorTest(String name) { + super(name); + + } + + Calculator calculator = null; + + public void setUp() { + calculator = new Calculator(); + } + + public void tearDown() { + calculator = null; + } + + public void testAdd() { + + calculator.add(10); +// System.out.println("CalculatorTest.testAdd"); + assertEquals(5,calculator.getResult()); + } + + public void testSubtract() { + calculator.add(10); + calculator.subtract(5); +// System.out.println("CalculatorTest.testSubtract"); +// throw new RuntimeException("this is a test"); + assertEquals(5,calculator.getResult()); + } + + public static void main(String[] args) { +// CalculatorTest c1 = new CalculatorTest("testAdd"); +// CalculatorTest c2 = new CalculatorTest("testSubtract"); +// c1.run(); +// c2.run(); + TestResult tr = new TestResult(); + TestSuite ts = new TestSuite(CalculatorTest.class); + ts.run(tr); + + System.out.println(tr.failures().next().thrownException()); + } +} \ No newline at end of file diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v1/Assert.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v1/Assert.java new file mode 100644 index 0000000000..75fe0457f2 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v1/Assert.java @@ -0,0 +1,164 @@ +package org.litejunit.v1; + + +/** + * Created by john on 2017/9/2. + */ +public class Assert { + protected Assert() { + } + + + public static void assertEquals(byte expected, byte actual) { + assertEquals((String) null, (byte) expected, (byte) actual); + } + + public static void assertEquals(char expected, char actual) { + assertEquals((String) null, (char) expected, (char) actual); + } + + public static void assertEquals(double expected, double actual, double delta) { + assertEquals((String) null, expected, actual, delta); + } + + public static void assertEquals(float expected, float actual, float delta) { + assertEquals((String) null, expected, actual, delta); + } + + public static void assertEquals(int expected, int actual) { + assertEquals((String) null, (int) expected, (int) actual); + } + + public static void assertEquals(long expected, long actual) { + assertEquals((String) null, expected, actual); + } + + public static void assertEquals(Object expected, Object actual) { + assertEquals((String) null, expected, actual); + } + + public static void assertEquals(String message, byte expected, byte actual) { + assertEquals(message, new Byte(expected), new Byte(actual)); + } + + public static void assertEquals(String message, char expected, char actual) { + assertEquals(message, new Character(expected), new Character(actual)); + } + + public static void assertEquals(String message, double expected, double actual, double delta) { + if (Double.isInfinite(expected)) { + if (expected != actual) { + failNotEquals(message, new Double(expected), new Double(actual)); + } + } else if (Math.abs(expected - actual) > delta) { + failNotEquals(message, new Double(expected), new Double(actual)); + } + + } + + public static void assertEquals(String message, float expected, float actual, float delta) { + if (Float.isInfinite(expected)) { + if (expected != actual) { + failNotEquals(message, new Float(expected), new Float(actual)); + } + } else if (Math.abs(expected - actual) > delta) { + failNotEquals(message, new Float(expected), new Float(actual)); + } + + } + + public static void assertEquals(String message, int expected, int actual) { + assertEquals(message, new Integer(expected), new Integer(actual)); + } + + public static void assertEquals(String message, long expected, long actual) { + assertEquals(message, new Long(expected), new Long(actual)); + } + + public static void assertEquals(String message, Object expected, Object actual) { + if (expected != null || actual != null) { + if (expected == null || !expected.equals(actual)) { + failNotEquals(message, expected, actual); + } + } + } + + public static void assertEquals(String message, short expected, short actual) { + assertEquals(message, new Short(expected), new Short(actual)); + } + + public static void assertEquals(String message, boolean expected, boolean actual) { + assertEquals(message, new Boolean(expected), new Boolean(actual)); + } + + public static void assertEquals(short expected, short actual) { + assertEquals((String) null, (short) expected, (short) actual); + } + + public static void assertEquals(boolean expected, boolean actual) { + assertEquals((String) null, expected, actual); + } + + public static void assertNotNull(Object object) { + assertNotNull((String) null, object); + } + + public static void assertNotNull(String message, Object object) { + assertTrue(message, object != null); + } + + public static void assertNull(Object object) { + assertNull((String) null, object); + } + + public static void assertNull(String message, Object object) { + assertTrue(message, object == null); + } + + public static void assertSame(Object expected, Object actual) { + assertSame((String) null, expected, actual); + } + + public static void assertSame(String message, Object expected, Object actual) { + if (expected != actual) { + failNotSame(message, expected, actual); + } + } + + public static void assertTrue(String message, boolean condition) { + if (!condition) { + fail(message); + } + + } + + public static void assertTrue(boolean condition) { + assertTrue((String) null, condition); + } + + public static void fail() { + fail((String) null); + } + + public static void fail(String message) { + throw new AssertionFailedError(message); + } + + private static void failNotEquals(String message, Object expected, Object actual) { + String formatted = ""; + if (message != null) { + formatted = message + " "; + } + + fail(formatted + "expected:<" + expected + "> but was:<" + actual + ">"); + } + + private static void failNotSame(String message, Object expected, Object actual) { + String formatted = ""; + if (message != null) { + formatted = message + " "; + } + + fail(formatted + "expected same"); + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v1/AssertionFailedError.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v1/AssertionFailedError.java new file mode 100644 index 0000000000..86f89c81c5 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v1/AssertionFailedError.java @@ -0,0 +1,14 @@ +package org.litejunit.v1; + +/** + * Created by john on 2017/9/2. + */ +public class AssertionFailedError extends Error{ + public AssertionFailedError() { + + } + + public AssertionFailedError(String message) { + super(message); + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v1/Test.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v1/Test.java new file mode 100644 index 0000000000..f57b8d9e3e --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v1/Test.java @@ -0,0 +1,12 @@ +package org.litejunit.v1; + + +/** + * Created by john on 2017/8/30. + */ + +public interface Test { + int countTestCases(); + + void run(TestResult tr); +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v1/TestCase.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v1/TestCase.java new file mode 100644 index 0000000000..9cf4ac7137 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v1/TestCase.java @@ -0,0 +1,57 @@ +package org.litejunit.v1; + + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * Created by john on 2017/8/30. + */ +public abstract class TestCase implements Test { + private String name; + + TestCase() { + name = null; + } + + public TestCase(String name) { + this.name = name; + } + + @Override + public int countTestCases() { + return 1; + } + + @Override + public void run(TestResult tr) { + tr.run(this); + } + + protected void doRun() throws Throwable{ + setUp(); + try { + runTest(); + } finally { + tearDown(); + } + } + + protected void runTest() throws Throwable { + Method runMethod = getClass().getMethod(name, null); + try { + runMethod.invoke(this, new Class[0]); + } catch (InvocationTargetException e) { + e.fillInStackTrace(); + throw e.getTargetException(); + } + } + + protected void setUp() { + + } + + protected void tearDown() { + + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v1/TestFailure.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v1/TestFailure.java new file mode 100644 index 0000000000..ec4ec484b1 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v1/TestFailure.java @@ -0,0 +1,39 @@ +package org.litejunit.v1; + +/** + * Created by john on 2017/9/2. + */ +public class TestFailure { + + protected Test failedTest; + protected Throwable thrownException; + + /** + * Constructs a TestFailure with the given test and exception. + */ + public TestFailure(Test failedTest, Throwable thrownException) { + this.failedTest= failedTest; + this.thrownException= thrownException; + } + /** + * Gets the failed test. + */ + public Test failedTest() { + return failedTest; + } + /** + * Gets the thrown exception. + */ + public Throwable thrownException() { + return thrownException; + } + /** + * Returns a short description of the failure. + */ + public String toString() { + StringBuffer buffer= new StringBuffer(); + buffer.append(failedTest+": "+thrownException.getMessage()); + return buffer.toString(); + } + +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v1/TestResult.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v1/TestResult.java new file mode 100644 index 0000000000..5126aea9c3 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v1/TestResult.java @@ -0,0 +1,85 @@ +package org.litejunit.v1; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** + * Created by john on 2017/9/2. + */ +public class TestResult { + protected List failures; + protected List errors; + + protected int testCount; + private boolean stop; + + public TestResult() { + failures = new ArrayList<>(); + errors = new ArrayList<>(); + + testCount = 0; + stop = false; + } + + public void addError(Test test, Throwable t) { + errors.add(new TestFailure(test, t)); + } + + public void addFailure(Test test, AssertionFailedError t) { + failures.add(new TestFailure(test, t)); + } + + + public void startTest(Test test) { + int count = test.countTestCases(); + testCount += count; + } + + public void endTest(Test test) { + } + + protected void run(final TestCase test) { + startTest(test); + try { + test.doRun(); + } catch (AssertionFailedError e) { + addFailure(test, e); + } catch (Throwable e) { + addError(test, e); + } + + endTest(test); + } + + public boolean shouldStop() { + return stop; + } + + public void stop() { + stop = true; + } + + public int errorCount() { + return errors.size(); + } + + public Iterator errors() { + return errors.iterator(); + } + + public int failureCount() { + return failures.size(); + } + + public Iterator failures() { + return failures.iterator(); + } + + /** + * Returns whether the entire test was successful or not. + */ + public boolean wasSuccessful() { + return this.failureCount() == 0 && this.errorCount() == 0; + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v1/TestSuite.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v1/TestSuite.java new file mode 100644 index 0000000000..1193692a15 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v1/TestSuite.java @@ -0,0 +1,120 @@ +package org.litejunit.v1; + + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Vector; + +/** + * Created by john on 2017/8/30. + */ +public class TestSuite implements Test { + private List tests = new ArrayList<>(10); + private String name; + + + public TestSuite(final Class theClass) { + this.name = theClass.getName(); + Constructor constructor = null; + try { + constructor = getConstructor(theClass); + } catch (NoSuchMethodException e) { +// addTest(warning("Class " + theClass.getName() + " has no public constructor TestCase(String name)")); + return; + } + + if (!Modifier.isPublic(theClass.getModifiers())) { +// addTest(warning("Class " + theClass.getName() + " is not public")); + return; + } + + Vector names = new Vector<>(); + Method[] methods = theClass.getDeclaredMethods(); + for (int i = 0; i < methods.length; i++) { + addTestMethod(methods[i], names, constructor); + } + + if (tests.size() == 0) { +// addTest(warning("No tests found in " + theClass.getName())); + } + } + + + private Constructor getConstructor(Class theClass) throws NoSuchMethodException { + Class[] args = new Class[]{String.class}; + return theClass.getConstructor(args); + } + + + @Override + public void run(TestResult result) { + for (Iterator e = tests(); e.hasNext(); ) { + if (result.shouldStop()) { + break; + } + Test test = (Test) e.next(); + test.run(result); + } + + } + + public Iterator tests() { + return tests.iterator(); + } + + private void addTestMethod(Method m, Vector names, Constructor constructor) { + String name = m.getName(); + if (names.contains(name)) + return; + if (isPublicTestMethod(m)) { + names.addElement(name); + + Object[] args = new Object[]{name}; + try { + addTest((Test) constructor.newInstance(args)); + } catch (InstantiationException e) { +// addTest(warning("Cannot instantiate test case: "+name+" ("+exceptionToString(e)+")")); + } catch (InvocationTargetException e) { +// addTest(warning("Exception in constructor: "+name+" ("+exceptionToString(e.getTargetException())+")")); + } catch (IllegalAccessException e) { +// addTest(warning("Cannot access test case: "+name+" ("+exceptionToString(e)+")")); + } + + } else { // almost a test method + if (isTestMethod(m)) { +// addTest(warning("Test method isn't public: "+m.getName())); + } + } + } + + private boolean isPublicTestMethod(Method m) { + return isTestMethod(m) && Modifier.isPublic(m.getModifiers()); + } + + private boolean isTestMethod(Method m) { + String name = m.getName(); + Class[] parameters = m.getParameterTypes(); + Class returnType = m.getReturnType(); + return parameters.length == 0 && name.startsWith("test") && returnType.equals(Void.TYPE); + } + + public void addTest(Test test) { + tests.add(test); + } + + @Override + public int countTestCases() { + int count= 0; + + for (Iterator e= tests(); e.hasNext(); ) { + Test test= e.next(); + count= count + test.countTestCases(); + } + return count; + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/Assert.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/Assert.java new file mode 100644 index 0000000000..f66d9076a9 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/Assert.java @@ -0,0 +1,164 @@ +package org.litejunit.v2; + + +/** + * Created by john on 2017/9/2. + */ +public class Assert { + protected Assert() { + } + + + public static void assertEquals(byte expected, byte actual) { + assertEquals((String) null, (byte) expected, (byte) actual); + } + + public static void assertEquals(char expected, char actual) { + assertEquals((String) null, (char) expected, (char) actual); + } + + public static void assertEquals(double expected, double actual, double delta) { + assertEquals((String) null, expected, actual, delta); + } + + public static void assertEquals(float expected, float actual, float delta) { + assertEquals((String) null, expected, actual, delta); + } + + public static void assertEquals(int expected, int actual) { + assertEquals((String) null, (int) expected, (int) actual); + } + + public static void assertEquals(long expected, long actual) { + assertEquals((String) null, expected, actual); + } + + public static void assertEquals(Object expected, Object actual) { + assertEquals((String) null, expected, actual); + } + + public static void assertEquals(String message, byte expected, byte actual) { + assertEquals(message, new Byte(expected), new Byte(actual)); + } + + public static void assertEquals(String message, char expected, char actual) { + assertEquals(message, new Character(expected), new Character(actual)); + } + + public static void assertEquals(String message, double expected, double actual, double delta) { + if (Double.isInfinite(expected)) { + if (expected != actual) { + failNotEquals(message, new Double(expected), new Double(actual)); + } + } else if (Math.abs(expected - actual) > delta) { + failNotEquals(message, new Double(expected), new Double(actual)); + } + + } + + public static void assertEquals(String message, float expected, float actual, float delta) { + if (Float.isInfinite(expected)) { + if (expected != actual) { + failNotEquals(message, new Float(expected), new Float(actual)); + } + } else if (Math.abs(expected - actual) > delta) { + failNotEquals(message, new Float(expected), new Float(actual)); + } + + } + + public static void assertEquals(String message, int expected, int actual) { + assertEquals(message, new Integer(expected), new Integer(actual)); + } + + public static void assertEquals(String message, long expected, long actual) { + assertEquals(message, new Long(expected), new Long(actual)); + } + + public static void assertEquals(String message, Object expected, Object actual) { + if (expected != null || actual != null) { + if (expected == null || !expected.equals(actual)) { + failNotEquals(message, expected, actual); + } + } + } + + public static void assertEquals(String message, short expected, short actual) { + assertEquals(message, new Short(expected), new Short(actual)); + } + + public static void assertEquals(String message, boolean expected, boolean actual) { + assertEquals(message, new Boolean(expected), new Boolean(actual)); + } + + public static void assertEquals(short expected, short actual) { + assertEquals((String) null, (short) expected, (short) actual); + } + + public static void assertEquals(boolean expected, boolean actual) { + assertEquals((String) null, expected, actual); + } + + public static void assertNotNull(Object object) { + assertNotNull((String) null, object); + } + + public static void assertNotNull(String message, Object object) { + assertTrue(message, object != null); + } + + public static void assertNull(Object object) { + assertNull((String) null, object); + } + + public static void assertNull(String message, Object object) { + assertTrue(message, object == null); + } + + public static void assertSame(Object expected, Object actual) { + assertSame((String) null, expected, actual); + } + + public static void assertSame(String message, Object expected, Object actual) { + if (expected != actual) { + failNotSame(message, expected, actual); + } + } + + public static void assertTrue(String message, boolean condition) { + if (!condition) { + fail(message); + } + + } + + public static void assertTrue(boolean condition) { + assertTrue((String) null, condition); + } + + public static void fail() { + fail((String) null); + } + + public static void fail(String message) { + throw new AssertionFailedError(message); + } + + private static void failNotEquals(String message, Object expected, Object actual) { + String formatted = ""; + if (message != null) { + formatted = message + " "; + } + + fail(formatted + "expected:<" + expected + "> but was:<" + actual + ">"); + } + + private static void failNotSame(String message, Object expected, Object actual) { + String formatted = ""; + if (message != null) { + formatted = message + " "; + } + + fail(formatted + "expected same"); + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/AssertionFailedError.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/AssertionFailedError.java new file mode 100644 index 0000000000..7831ffe5f8 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/AssertionFailedError.java @@ -0,0 +1,14 @@ +package org.litejunit.v2; + +/** + * Created by john on 2017/9/2. + */ +public class AssertionFailedError extends Error{ + public AssertionFailedError() { + + } + + public AssertionFailedError(String message) { + super(message); + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/Test.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/Test.java new file mode 100644 index 0000000000..41121e5b64 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/Test.java @@ -0,0 +1,12 @@ +package org.litejunit.v2; + + +/** + * Created by john on 2017/8/30. + */ + +public interface Test { + int countTestCases(); + + void run(TestResult tr); +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/TestCase.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/TestCase.java new file mode 100644 index 0000000000..06441571e7 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/TestCase.java @@ -0,0 +1,57 @@ +package org.litejunit.v2; + + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * Created by john on 2017/8/30. + */ +public abstract class TestCase extends Assert implements Test { + private String name; + + TestCase() { + name = null; + } + + public TestCase(String name) { + this.name = name; + } + + @Override + public int countTestCases() { + return 1; + } + + @Override + public void run(TestResult tr) { + tr.run(this); + } + + protected void doRun() throws Throwable { + setUp(); + try { + runTest(); + } finally { + tearDown(); + } + } + + protected void runTest() throws Throwable { + Method runMethod = getClass().getMethod(name, null); + try { + runMethod.invoke(this, new Class[0]); + } catch (InvocationTargetException e) { + e.fillInStackTrace(); + throw e.getTargetException(); + } + } + + protected void setUp() { + + } + + protected void tearDown() { + + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/TestFailure.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/TestFailure.java new file mode 100644 index 0000000000..4fed21c84a --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/TestFailure.java @@ -0,0 +1,39 @@ +package org.litejunit.v2; + +/** + * Created by john on 2017/9/2. + */ +public class TestFailure { + + protected Test failedTest; + protected Throwable thrownException; + + /** + * Constructs a TestFailure with the given test and exception. + */ + public TestFailure(Test failedTest, Throwable thrownException) { + this.failedTest= failedTest; + this.thrownException= thrownException; + } + /** + * Gets the failed test. + */ + public Test failedTest() { + return failedTest; + } + /** + * Gets the thrown exception. + */ + public Throwable thrownException() { + return thrownException; + } + /** + * Returns a short description of the failure. + */ + public String toString() { + StringBuffer buffer= new StringBuffer(); + buffer.append(failedTest+": "+thrownException.getMessage()); + return buffer.toString(); + } + +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/TestListener.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/TestListener.java new file mode 100644 index 0000000000..6d29b2729a --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/TestListener.java @@ -0,0 +1,16 @@ +package org.litejunit.v2; + +/** + * Created by john on 2017/9/2. + * + */ +public interface TestListener { + + void addError(Test test, Throwable t); + + void addFailure(Test test, AssertionFailedError t); + + void endTest(Test test); + + void startTest(Test test); +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/TestResult.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/TestResult.java new file mode 100644 index 0000000000..e1a06eab1a --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/TestResult.java @@ -0,0 +1,112 @@ +package org.litejunit.v2; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** + * Created by john on 2017/9/2. + */ +public class TestResult { + protected List failures; + protected List errors; + protected List listeners; + + + protected int testCount; + private boolean stop; + + public TestResult() { + failures = new ArrayList<>(); + errors = new ArrayList<>(); + listeners = new ArrayList<>(); + + testCount = 0; + stop = false; + } + + public void addError(Test test, Throwable t) { + errors.add(new TestFailure(test, t)); + for (TestListener listener : listeners) { + listener.addError(test, t); + } + } + + public void addFailure(Test test, AssertionFailedError t) { + failures.add(new TestFailure(test, t)); + for (TestListener listener : listeners) { + listener.addFailure(test, t); + } + } + + + public void startTest(Test test) { + int count = test.countTestCases(); + testCount += count; + for (TestListener listener : listeners) { + listener.startTest(test); + } + } + + public void endTest(Test test) { + for (TestListener listener : listeners) { + listener.endTest(test); + } + } + + protected void run(final TestCase test) { + startTest(test); + try { + test.doRun(); + } catch (AssertionFailedError e) { + addFailure(test, e); + } catch (Throwable e) { + addError(test, e); + } + + endTest(test); + } + + public boolean shouldStop() { + return stop; + } + + public void stop() { + stop = true; + } + + public int errorCount() { + return errors.size(); + } + + public Iterator errors() { + return errors.iterator(); + } + + public int failureCount() { + return failures.size(); + } + + public Iterator failures() { + return failures.iterator(); + } + + /** + * Returns whether the entire test was successful or not. + */ + public boolean wasSuccessful() { + return this.failureCount() == 0 && this.errorCount() == 0; + } + + public void addListener(TestListener listener) { + listeners.add(listener); + } + + public void removeListener(TestListener listener) { + listeners.remove(listener); + } + + public int runCount() { + return testCount; + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/TestSuite.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/TestSuite.java new file mode 100644 index 0000000000..b0e8eb6b41 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/TestSuite.java @@ -0,0 +1,127 @@ +package org.litejunit.v2; + + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Vector; + +/** + * Created by john on 2017/8/30. + */ +public class TestSuite implements Test { + private List tests = new ArrayList<>(10); + private String name; + + public TestSuite(String name) { + this.name = name; + } + + public TestSuite(final Class theClass) { + this.name = theClass.getName(); + Constructor constructor = null; + try { + constructor = getConstructor(theClass); + } catch (NoSuchMethodException e) { +// addTest(warning("Class " + theClass.getName() + " has no public constructor TestCase(String name)")); + return; + } + + if (!Modifier.isPublic(theClass.getModifiers())) { +// addTest(warning("Class " + theClass.getName() + " is not public")); + return; + } + + Vector names = new Vector<>(); + Method[] methods = theClass.getDeclaredMethods(); + for (int i = 0; i < methods.length; i++) { + addTestMethod(methods[i], names, constructor); + } + + if (tests.size() == 0) { +// addTest(warning("No tests found in " + theClass.getName())); + } + } + + + private Constructor getConstructor(Class theClass) throws NoSuchMethodException { + Class[] args = new Class[]{String.class}; + return theClass.getConstructor(args); + } + + + @Override + public void run(TestResult result) { + for (Iterator e = tests(); e.hasNext(); ) { + if (result.shouldStop()) { + break; + } + Test test = (Test) e.next(); + test.run(result); + } + + } + + public Iterator tests() { + return tests.iterator(); + } + + private void addTestMethod(Method m, Vector names, Constructor constructor) { + String name = m.getName(); + if (names.contains(name)) + return; + if (isPublicTestMethod(m)) { + names.addElement(name); + + Object[] args = new Object[]{name}; + try { + addTest((Test) constructor.newInstance(args)); + } catch (InstantiationException e) { +// addTest(warning("Cannot instantiate test case: "+name+" ("+exceptionToString(e)+")")); + } catch (InvocationTargetException e) { +// addTest(warning("Exception in constructor: "+name+" ("+exceptionToString(e.getTargetException())+")")); + } catch (IllegalAccessException e) { +// addTest(warning("Cannot access test case: "+name+" ("+exceptionToString(e)+")")); + } + + } else { // almost a test method + if (isTestMethod(m)) { +// addTest(warning("Test method isn't public: "+m.getName())); + } + } + } + + private boolean isPublicTestMethod(Method m) { + return isTestMethod(m) && Modifier.isPublic(m.getModifiers()); + } + + private boolean isTestMethod(Method m) { + String name = m.getName(); + Class[] parameters = m.getParameterTypes(); + Class returnType = m.getReturnType(); + return parameters.length == 0 && name.startsWith("test") && returnType.equals(Void.TYPE); + } + + public void addTest(Test test) { + tests.add(test); + } + + public void addTestSuite(Class testClass) { + this.addTest(new TestSuite(testClass)); + } + + @Override + public int countTestCases() { + int count= 0; + + for (Iterator e = tests(); e.hasNext(); ) { + Test test= e.next(); + count= count + test.countTestCases(); + } + return count; + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/runner/BaseTestRunner.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/runner/BaseTestRunner.java new file mode 100644 index 0000000000..70ed118850 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/runner/BaseTestRunner.java @@ -0,0 +1,89 @@ +package org.litejunit.v2.runner; + +/** + * Created by john on 2017/9/2. + */ + +import org.litejunit.v2.Test; +import org.litejunit.v2.TestListener; +import org.litejunit.v2.TestSuite; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.text.NumberFormat; + +public abstract class BaseTestRunner implements TestListener { + public static final String SUITE_METHODNAME = "suite"; + + /** + * Returns a filtered stack trace + */ + public static String getFilteredTrace(Throwable t) { + StringWriter stringWriter = new StringWriter(); + PrintWriter writer = new PrintWriter(stringWriter); + t.printStackTrace(writer); + StringBuffer buffer = stringWriter.getBuffer(); + String trace = buffer.toString(); + return trace; + //return BaseTestRunner.filterStack(trace); + } + + public Test getTest(String suiteClassName) { + if (suiteClassName.length() <= 0) { + return null; + } + Class testClass = null; + try { + testClass = loadSuiteClass(suiteClassName); + } catch (ClassNotFoundException e) { + String clazz = e.getMessage(); + if (clazz == null) + clazz = suiteClassName; + runFailed("Class not found \"" + clazz + "\""); + return null; + } catch (Exception e) { + runFailed("Error: " + e.toString()); + return null; + } + Method suiteMethod = null; + try { + suiteMethod = testClass.getMethod(SUITE_METHODNAME, new Class[0]); + } catch (Exception e) { + // try to extract a test suite automatically + //clearStatus(); + return new TestSuite(testClass); + } + Test test = null; + try { + test = (Test) suiteMethod.invoke(null, new Class[0]); // static method + if (test == null) + return test; + } catch (InvocationTargetException e) { + runFailed("Failed to invoke suite():" + e.getTargetException().toString()); + return null; + } catch (IllegalAccessException e) { + runFailed("Failed to invoke suite():" + e.toString()); + return null; + } + + //clearStatus(); + return test; + } + + protected Class loadSuiteClass(String suiteClassName) throws ClassNotFoundException { + + //TODO + return Class.forName(suiteClassName); + + + //return getLoader().load(suiteClassName); + } + + protected abstract void runFailed(String message); + + public String elapsedTimeAsString(long runTime) { + return NumberFormat.getInstance().format((double) runTime / 1000); + } +} \ No newline at end of file diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/textui/TestRunner.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/textui/TestRunner.java new file mode 100644 index 0000000000..ff1bf38027 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v2/textui/TestRunner.java @@ -0,0 +1,194 @@ +package org.litejunit.v2.textui; + + +import org.litejunit.v2.*; +import org.litejunit.v2.runner.BaseTestRunner; + +import java.io.PrintStream; +import java.util.Iterator; + +public class TestRunner extends BaseTestRunner { + PrintStream writer= System.out; + int column= 0; + + /** + * Constructs a TestRunner. + */ + public TestRunner() { + } + + + /** + * Always use the StandardTestSuiteLoader. Overridden from + * BaseTestRunner. + */ + /*public TestSuiteLoader getLoader() { + return new StandardTestSuiteLoader(); + }*/ + + public synchronized void addError(Test test, Throwable t) { + writer().print("E"); + } + + public synchronized void addFailure(Test test, AssertionFailedError t) { + writer().print("F"); + } + + + + public TestResult doRun(Test suite) { + TestResult result= new TestResult(); + result.addListener(this); + long startTime= System.currentTimeMillis(); + suite.run(result); + long endTime= System.currentTimeMillis(); + long runTime= endTime-startTime; + writer().println(); + writer().println("Time: "+elapsedTimeAsString(runTime)); + print(result); + + writer().println(); + + + return result; + } + + + + public synchronized void startTest(Test test) { + writer().print("."); + if (column++ >= 40) { + writer().println(); + column= 0; + } + } + + public void endTest(Test test) { + } + + public static void main(String args[]) { + TestRunner testRunner= new TestRunner(); + try { + TestResult r= testRunner.start(args); + if (!r.wasSuccessful()) + System.exit(-1); + System.exit(0); + } catch(Exception e) { + System.err.println(e.getMessage()); + System.exit(-2); + } + } + /** + * Prints failures to the standard output + */ + public synchronized void print(TestResult result) { + printErrors(result); + printFailures(result); + printHeader(result); + } + /** + * Prints the errors to the standard output + */ + public void printErrors(TestResult result) { + if (result.errorCount() != 0) { + if (result.errorCount() == 1) + writer().println("There was "+result.errorCount()+" error:"); + else + writer().println("There were "+result.errorCount()+" errors:"); + + int i= 1; + for (Iterator e = result.errors(); e.hasNext(); i++) { + TestFailure failure= e.next(); + writer().println(i+") "+failure.failedTest()); + writer().print(getFilteredTrace(failure.thrownException())); + } + } + } + /** + * Prints failures to the standard output + */ + public void printFailures(TestResult result) { + if (result.failureCount() != 0) { + if (result.failureCount() == 1) + writer().println("There was " + result.failureCount() + " failure:"); + else + writer().println("There were " + result.failureCount() + " failures:"); + int i = 1; + for (Iterator e= result.failures(); e.hasNext(); i++) { + TestFailure failure= (TestFailure) e.next(); + writer().print(i + ") " + failure.failedTest()); + Throwable t= failure.thrownException(); + writer().print(getFilteredTrace(failure.thrownException())); + } + } + } + /** + * Prints the header of the report + */ + public void printHeader(TestResult result) { + if (result.wasSuccessful()) { + writer().println(); + writer().print("OK"); + writer().println (" (" + result.runCount() + " tests)"); + + } else { + writer().println(); + writer().println("FAILURES!!!"); + writer().println("Tests run: "+result.runCount()+ + ", Failures: "+result.failureCount()+ + ", Errors: "+result.errorCount()); + } + } + + + /** + * Starts a test run. Analyzes the command line arguments + * and runs the given test suite. + */ + protected TestResult start(String args[]) throws Exception { + if(args.length == 0){ + throw new Exception("Usage: TestRunner testCaseName"); + } + String testCase= args[0]; + + try { + Test suite= getTest(testCase); + return doRun(suite); + } + catch(Exception e) { + throw new Exception("Could not create and run test suite: "+e); + } + } + + protected void runFailed(String message) { + System.err.println(message); + System.exit(-1); + } + + /** + * Runs a suite extracted from a TestCase subclass. + */ + static public void run(Class testClass) { + run(new TestSuite(testClass)); + } + /** + * Runs a single test and collects its results. + * This method can be used to start a test run + * from your program. + *
+     * public static void main (String[] args) {
+     *     test.textui.TestRunner.run(suite());
+     * }
+     * 
+ */ + static public void run(Test suite) { + TestRunner aTestRunner= new TestRunner(); + aTestRunner.doRun(suite); + } + + protected PrintStream writer() { + return writer; + } + + +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/After.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/After.java new file mode 100644 index 0000000000..cef97c4aed --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/After.java @@ -0,0 +1,39 @@ +package org.litejunit.v3; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * If you allocate external resources in a @Before method you need to release them + * after the test runs. Annotating a public void method + * with @After causes that method to be run after the @Test method. All @After + * methods are guaranteed to run even if a @Before or @Test method throws an + * exception. The @After methods declared in superclasses will be run after those of the current + * class. + *

+ * Here is a simple example:
+* + * public class Example {
+ *   File output;
+ *   @Before public void createOutputFile() {
+ *     output= new File(...);
+ *   }
+ *   @Test public void something() {
+ *     ...
+ *   }
+ *   @After public void deleteOutputFile() {
+ *     output.delete();
+ *   }
+ * }
+ *
+ * + * @see Before + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface After { +} + diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/AfterClass.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/AfterClass.java new file mode 100644 index 0000000000..8dc15454be --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/AfterClass.java @@ -0,0 +1,41 @@ +package org.litejunit.v3; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * If you allocate expensive external resources in a @BeforeClass method you need to release them + * after all the tests in the class have run. Annotating a public static void method + * with @AfterClass causes that method to be run after all the tests in the class have been run. All @AfterClass + * methods are guaranteed to run even if a @BeforeClass method throws an + * exception. The @AfterClass methods declared in superclasses will be run after those of the current + * class. + *

+ * Here is a simple example:
+* + * public class Example {
+ *   DatabaseConnection database;
+ *   @BeforeClass public void login() {
+ *     database= ...;
+ *   }
+ *   @Test public void something() {
+ *     ...
+ *   }
+ *   @Test public void somethingElse() {
+ *     ...
+ *   }
+ *   @AfterClass public void logout() {
+ *     database.logout();
+ *   }
+ * }
+ *
+ * + * @see BeforeClass + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface AfterClass { +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/Assert.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/Assert.java new file mode 100644 index 0000000000..6ae8e11544 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/Assert.java @@ -0,0 +1,269 @@ +package org.litejunit.v3; + +/** + * A set of assertion methods useful for writing tests. Only failed assertions are recorded. + * These methods can be used directly: Assert.assertEquals(...), however, they + * read better if they are referenced through static import:
+ * + * import static org.junit.Assert.*;
+ * ...
+ *   assertEquals(...);
+ *
+ */ + +public class Assert { + /** + * Protect constructor since it is a static only class + */ + protected Assert() { + } + + /** + * Asserts that a condition is true. If it isn't it throws an + * AssertionError with the given message. + */ + static public void assertTrue(String message, boolean condition) { + if (!condition) + fail(message); + } + + /** + * Asserts that a condition is true. If it isn't it throws an + * AssertionError. + */ + static public void assertTrue(boolean condition) { + assertTrue(null, condition); + } + + /** + * Asserts that a condition is false. If it isn't it throws an + * AssertionError with the given message. + */ + static public void assertFalse(String message, boolean condition) { + assertTrue(message, !condition); + } + + /** + * Asserts that a condition is false. If it isn't it throws an + * AssertionError. + */ + static public void assertFalse(boolean condition) { + assertFalse(null, condition); + } + + /** + * Fails a test with the given message. + */ + static public void fail(String message) { + throw new AssertionError(message); + } + + /** + * Fails a test with no message. + */ + static public void fail() { + fail(null); + } + + /** + * Asserts that two objects are equal. If they are not, an + * AssertionError is thrown with the given message. + */ + static public void assertEquals(String message, Object expected, Object actual) { + if (expected == null && actual == null) + return; + if (expected != null && expected.equals(actual)) + return; + if (expected instanceof String && actual instanceof String) + throw new ComparisonFailure(message, (String)expected, (String)actual); + else + failNotEquals(message, expected, actual); + } + + /** + * Asserts that two objects are equal. If they are not, an + * AssertionError is thrown. + */ + static public void assertEquals(Object expected, Object actual) { + assertEquals(null, expected, actual); + } + + /** + * Asserts that two object arrays are equal. If they are not, an + * AssertionError is thrown with the given message. + */ + public static void assertEquals(String message, Object[] expecteds, Object[] actuals) { + if (expecteds == actuals) + return; + String header = message == null ? "" : message + ": "; + if (expecteds == null) + fail(header + "expected array was null"); + if (actuals == null) + fail(header + "actual array was null"); + if (actuals.length != expecteds.length) + fail(header + "array lengths differed, expected.length=" + expecteds.length + " actual.length=" + actuals.length); + + for (int i= 0; i < expecteds.length; i++) { + Object o1= expecteds[i]; + Object o2= actuals[i]; + if (o1.getClass().isArray() && o2.getClass().isArray()) { + Object[] expected= (Object[]) o1; + Object[] actual= (Object[]) o2; + assertEquals(header + "arrays first differed at element " + i + ";", expected, actual); + } else + assertEquals(header + "arrays first differed at element [" + i + "];", o1, o2); + } + } + + /** + * Asserts that two object arrays are equal. If they are not, an + * AssertionError is thrown. + */ + public static void assertEquals(Object[] expecteds, Object[] actuals) { + assertEquals(null, expecteds, actuals); + } + + /** + * Asserts that two doubles are equal to within a positive delta. If they + * are not, an AssertionError is thrown with the given message. If the + * expected value is infinity then the delta value is ignored. NaNs are + * considered equal: + * assertEquals(Double.NaN, Double.NaN, *) passes + */ + static public void assertEquals(String message, double expected, double actual, double delta) { + if (Double.compare(expected, actual) == 0) + return; + if (!(Math.abs(expected - actual) <= delta)) + failNotEquals(message, new Double(expected), new Double(actual)); + } + + /** + * Asserts that two doubles are equal to within a positive delta. If they + * are not, an AssertionError is thrown. If the + * expected value is infinity then the delta value is ignored.NaNs are + * considered equal: + * assertEquals(Double.NaN, Double.NaN, *) passes + */ + static public void assertEquals(double expected, double actual, double delta) { + assertEquals(null, expected, actual, delta); + } + + /** + * Asserts that two floats are equal to within a positive delta. If they + * are not, an AssertionError is thrown with the given message. If the + * expected value is infinity then the delta value is ignored.NaNs are + * considered equal: + * assertEquals(Float.NaN, Float.NaN, *) passes + */ + static public void assertEquals(String message, float expected, float actual, float delta) { + if (Float.compare(expected, actual) == 0) + return; + if (!(Math.abs(expected - actual) <= delta)) + failNotEquals(message, new Float(expected), new Float(actual)); + } + + /** + * Asserts that two floats are equal to within a positive delta. If they + * are not, an AssertionError is thrown. If the + * expected value is infinity then the delta value is ignored.NaNs are + * considered equal: + * assertEquals(Float.NaN, Float.NaN, *) passes + */ + static public void assertEquals(float expected, float actual, float delta) { + assertEquals(null, expected, actual, delta); + } + + /** + * Asserts that an object isn't null. If it is an AssertionError is + * thrown with the given message. + */ + static public void assertNotNull(String message, Object object) { + assertTrue(message, object != null); + } + + /** + * Asserts that an object isn't null. If it is an AssertionError is + * thrown. + */ + static public void assertNotNull(Object object) { + assertNotNull(null, object); + } + + /** + * Asserts that an object is null. If it is not, an AssertionError is + * thrown with the given message. + */ + static public void assertNull(String message, Object object) { + assertTrue(message, object == null); + } + + /** + * Asserts that an object is null. If it isn't an AssertionError is + * thrown. + */ + static public void assertNull(Object object) { + assertNull(null, object); + } + + /** + * Asserts that two objects refer to the same object. If they are not, an + * AssertionError is thrown with the given message. + */ + static public void assertSame(String message, Object expected, Object actual) { + if (expected == actual) + return; + failNotSame(message, expected, actual); + } + + /** + * Asserts that two objects refer to the same object. If they are not the + * same, an AssertionError is thrown. + */ + static public void assertSame(Object expected, Object actual) { + assertSame(null, expected, actual); + } + + /** + * Asserts that two objects do not refer to the same object. If they do + * refer to the same object, an AssertionError is thrown with the given + * message. + */ + static public void assertNotSame(String message, Object expected, Object actual) { + if (expected == actual) + failSame(message); + } + + /** + * Asserts that two objects do not refer to the same object. If they do + * refer to the same object, an AssertionError is thrown. + */ + static public void assertNotSame(Object expected, Object actual) { + assertNotSame(null, expected, actual); + } + + static private void failSame(String message) { + String formatted= ""; + if (message != null) + formatted= message + " "; + fail(formatted + "expected not same"); + } + + static private void failNotSame(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message + " "; + fail(formatted + "expected same:<" + expected + "> was not:<" + actual + ">"); + } + + static private void failNotEquals(String message, Object expected, Object actual) { + fail(format(message, expected, actual)); + } + + static String format(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message + " "; + return formatted + "expected:<" + expected + "> but was:<" + actual + ">"; + } + +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/Before.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/Before.java new file mode 100644 index 0000000000..0d66765427 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/Before.java @@ -0,0 +1,37 @@ +package org.litejunit.v3; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * When writing tests, it is common to find that several tests need similar + * objects created before they can run. Annotating a public void method + * with @Before causes that method to be run before the @Test method. + * The @Before methods of superclasses will be run before those of the current class. + *

+ * Here is a simple example: +* + * public class Example {
+ *   List empty;
+ *   @Before public static void initialize() {
+ *     empty= new ArrayList();
+ *   }
+ *   @Test public void size() {
+ *     ...
+ *   }
+ *   @Test public void remove() {
+ *     ...
+ *   }
+ * }
+ *
+ * + * @see BeforeClass + * @see After + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Before { +} + diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/BeforeClass.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/BeforeClass.java new file mode 100644 index 0000000000..d686f45c37 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/BeforeClass.java @@ -0,0 +1,36 @@ +package org.litejunit.v3; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Sometimes several tests need to share computationally expensive setup + * (like logging into a database). While this can compromise the independence of + * tests, sometimes it is a necessary optimization. Annotating a public static void no-arg method + * with @BeforeClass causes it to be run once before any of + * the test methods in the class. The @BeforeClass methods of superclasses + * will be run before those the current class. + *

+ * For example:
+ * + * + * public class Example {
+ *   @BeforeClass public static void onlyOnce() {
+ *     ...
+ *   }
+ *   @Test public void one() {
+ *     ...
+ *   }
+ *   @Test public void two() {
+ *     ...
+ *   }
+ * }
+ *
+ * @see AfterClass + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface BeforeClass { +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/ComparisonFailure.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/ComparisonFailure.java new file mode 100644 index 0000000000..8a71e1f698 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/ComparisonFailure.java @@ -0,0 +1,124 @@ +package org.litejunit.v3; + +/** + * Thrown when an assertEquals(String, String) fails. Create and throw + * a ComparisonFailure manually if you want to show users the difference between two complex + * strings. + * + * Inspired by a patch from Alex Chaffee (alex@purpletech.com) + */ +public class ComparisonFailure extends AssertionError { + private static final int MAX_CONTEXT_LENGTH= 20; + private static final long serialVersionUID= 1L; + + private String fExpected; + private String fActual; + + /** + * Constructs a comparison failure. + * @param message the identifying message or null + * @param expected the expected string value + * @param actual the actual string value + */ + public ComparisonFailure (String message, String expected, String actual) { + super (message); + fExpected= expected; + fActual= actual; + } + + /** + * Returns "..." in place of common prefix and "..." in + * place of common suffix between expected and actual. + * + * @see Throwable#getMessage() + */ + @Override + public String getMessage() { + return new ComparisonCompactor(MAX_CONTEXT_LENGTH, fExpected, fActual).compact(super.getMessage()); + } + + /** + * Returns the actual value + * @return the actual string value + */ + public String getActual() { + return fActual; + } + /** + * Returns the expected value + * @return the expected string value + */ + public String getExpected() { + return fExpected; + } + + private static class ComparisonCompactor { + private static final String ELLIPSIS= "..."; + private static final String DELTA_END= "]"; + private static final String DELTA_START= "["; + + private int fContextLength; + private String fExpected; + private String fActual; + private int fPrefix; + private int fSuffix; + + public ComparisonCompactor(int contextLength, String expected, String actual) { + fContextLength= contextLength; + fExpected= expected; + fActual= actual; + } + + public String compact(String message) { + if (fExpected == null || fActual == null || areStringsEqual()) + return Assert.format(message, fExpected, fActual); + + findCommonPrefix(); + findCommonSuffix(); + String expected= compactString(fExpected); + String actual= compactString(fActual); + return Assert.format(message, expected, actual); + } + + private String compactString(String source) { + String result= DELTA_START + source.substring(fPrefix, source.length() - fSuffix + 1) + DELTA_END; + if (fPrefix > 0) + result= computeCommonPrefix() + result; + if (fSuffix > 0) + result= result + computeCommonSuffix(); + return result; + } + + private void findCommonPrefix() { + fPrefix= 0; + int end= Math.min(fExpected.length(), fActual.length()); + for (; fPrefix < end; fPrefix++) { + if (fExpected.charAt(fPrefix) != fActual.charAt(fPrefix)) + break; + } + } + + private void findCommonSuffix() { + int expectedSuffix= fExpected.length() - 1; + int actualSuffix= fActual.length() - 1; + for (; actualSuffix >= fPrefix && expectedSuffix >= fPrefix; actualSuffix--, expectedSuffix--) { + if (fExpected.charAt(expectedSuffix) != fActual.charAt(actualSuffix)) + break; + } + fSuffix= fExpected.length() - expectedSuffix; + } + + private String computeCommonPrefix() { + return (fPrefix > fContextLength ? ELLIPSIS : "") + fExpected.substring(Math.max(0, fPrefix - fContextLength), fPrefix); + } + + private String computeCommonSuffix() { + int end= Math.min(fExpected.length() - fSuffix + 1 + fContextLength, fExpected.length()); + return fExpected.substring(fExpected.length() - fSuffix + 1, end) + (fExpected.length() - fSuffix + 1 < fExpected.length() - fContextLength ? ELLIPSIS : ""); + } + + private boolean areStringsEqual() { + return fExpected.equals(fActual); + } + } +} \ No newline at end of file diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/Ignore.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/Ignore.java new file mode 100644 index 0000000000..ecf3048b44 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/Ignore.java @@ -0,0 +1,31 @@ +package org.litejunit.v3; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Sometimes you want to temporarily disable a test. Methods annotated with @Test + * that are also annotated with @Ignore will not be executed as tests. Native JUnit 4 test runners + * should report the number of ignored tests along with the number of tests that ran and the + * number of tests that failed. + *

+ * For example:
+ * + *   @Ignore @Test public void something() { ...
+ *
+ * @Ignore takes an optional default parameter if you want to record why a test is being ignored:
+ * + *   @Ignore("not ready yet") @Test public void something() { ...
+ *
+ * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Ignore { + /** + * The optional reason why the test is ignored. + */ + String value() default ""; +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/Test.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/Test.java new file mode 100644 index 0000000000..d3fcacaf57 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/Test.java @@ -0,0 +1,62 @@ +package org.litejunit.v3; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * The Test annotation tells JUnit that the public void method + * to which it is attached can be run as a test case. To run the method, + * JUnit first constructs a fresh instance of the class then invokes the + * annotated method. Any exceptions thrown by the test will be reported + * by JUnit as a failure. If no exceptions are thrown, the test is assumed + * to have succeeded. + *

+ * A simple test looks like this:
+ * + * public class Example {
+ *   @Test public void method() {
+ *     System.out.println("Hello");
+ *   }
+ * } + *
+ *

+ * The Test annotation supports two optional parameters. + * The first, expected, declares that a test method should throw + * an exception. If it doesn't throw an exception or if it throws a different exception + * than the one declared, the test fails. For example, the following test succeeds:
+ * + *   @Test(expected=IndexOutOfBoundsException.class) public void outOfBounds() {
+ *     new ArrayList<Object>().get(1);
+ *   }
+ *
+ *

+ * The second optional parameter, timeout, causes a test to fail if it takes longer than a specified + * amount of clock time (measured in milliseconds). The following test fails:
+ * + *   @Test(timeout=100) public void infinity() {
+ *     for(;;);
+ *   }
+ *
+ */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Test { + static class None extends Throwable { + private static final long serialVersionUID= 1L; + private None() { + } + } + + /** + * Optionally specify expected, a Throwable, to cause a test method to succeed iff + * an exception of the specified class is thrown by the method. + */ + Class expected() default None.class; + + /** + * Optionally specify timeout in milliseconds to cause a test method to fail if it + * takes longer than that number of milliseconds.*/ + long timeout() default 0L; +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/requests/ClassRequest.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/requests/ClassRequest.java new file mode 100644 index 0000000000..4de36b0140 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/requests/ClassRequest.java @@ -0,0 +1,50 @@ +/** + * + */ +package org.litejunit.v3.internal.requests; + + +import org.litejunit.v3.internal.runners.TestClassRunner; +import org.litejunit.v3.runner.Request; +import org.litejunit.v3.runner.RunWith; +import org.litejunit.v3.runner.Runner; + +import java.lang.reflect.Constructor; + +public class ClassRequest extends Request { + private final Class fTestClass; + + public ClassRequest(Class each) { + fTestClass = each; + } + + @Override + public Runner getRunner() { + Class runnerClass = getRunnerClass(fTestClass); + try { + Constructor constructor = runnerClass.getConstructor(Class.class); // TODO good error message if no such constructor + Runner runner = (Runner) constructor + .newInstance(new Object[]{fTestClass}); + return runner; + } catch (Exception e) { + return Request.errorReport(fTestClass, e).getRunner(); + } + } + + Class getRunnerClass(Class testClass) { + RunWith annotation = testClass.getAnnotation(RunWith.class); + if (annotation != null) { + return annotation.value(); + } else if (isPre4Test(testClass)) { + return null; +// return OldTestClassRunner.class; + } else { + return TestClassRunner.class; + } + } + + boolean isPre4Test(Class testClass) { + return false; +// return junit.framework.TestCase.class.isAssignableFrom(testClass); + } +} \ No newline at end of file diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/requests/ClassesRequest.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/requests/ClassesRequest.java new file mode 100644 index 0000000000..6da79c26e6 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/requests/ClassesRequest.java @@ -0,0 +1,30 @@ +/** + * + */ +package org.litejunit.v3.internal.requests; + + +import org.litejunit.v3.internal.runners.CompositeRunner; +import org.litejunit.v3.runner.Request; +import org.litejunit.v3.runner.Runner; + +public class ClassesRequest extends Request { + private final Class[] fClasses; + private final String fName; + + public ClassesRequest(String name, Class... classes) { + fClasses= classes; + fName= name; + } + + @Override + public Runner getRunner() { + CompositeRunner runner= new CompositeRunner(fName); + for (Class each : fClasses) { + Runner childRunner= Request.aClass(each).getRunner(); + if (childRunner != null) + runner.add(childRunner); + } + return runner; + } +} \ No newline at end of file diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/requests/ErrorReportingRequest.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/requests/ErrorReportingRequest.java new file mode 100644 index 0000000000..f7b3396b6e --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/requests/ErrorReportingRequest.java @@ -0,0 +1,45 @@ +package org.litejunit.v3.internal.requests; + + +import org.litejunit.v3.internal.runners.CompositeRunner; +import org.litejunit.v3.internal.runners.ErrorReportingRunner; +import org.litejunit.v3.internal.runners.InitializationError; +import org.litejunit.v3.runner.Description; +import org.litejunit.v3.runner.Request; +import org.litejunit.v3.runner.Runner; + +import java.lang.reflect.InvocationTargetException; +import java.util.Arrays; +import java.util.List; + +public class ErrorReportingRequest extends Request { + + private final Class fClass; + private final Throwable fCause; + + public ErrorReportingRequest(Class klass, Throwable cause) { + fClass= klass; + fCause= cause; + } + + @Override + public Runner getRunner() { + List goofs= getCauses(fCause); + CompositeRunner runner= new CompositeRunner(fClass.getName()); + for (int i= 0; i < goofs.size(); i++) { + final Description description= Description.createTestDescription(fClass, "initializationError" + i); + final Throwable throwable= goofs.get(i); + runner.add(new ErrorReportingRunner(description, throwable)); + } + return runner; + } + + private List getCauses(Throwable cause) { + if (cause instanceof InvocationTargetException) + return getCauses(cause.getCause()); + if (cause instanceof InitializationError) + return ((InitializationError) cause).getCauses(); + // TODO: untested + return Arrays.asList(cause); + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/requests/FilterRequest.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/requests/FilterRequest.java new file mode 100644 index 0000000000..00464f3955 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/requests/FilterRequest.java @@ -0,0 +1,33 @@ +/** + * + */ +package org.litejunit.v3.internal.requests; + + +import org.litejunit.v3.runner.Request; +import org.litejunit.v3.runner.Runner; +import org.litejunit.v3.runner.manipulation.Filter; +import org.litejunit.v3.runner.manipulation.NoTestsRemainException; + +public final class FilterRequest extends Request { + private final Request fRequest; + private final Filter fFilter; + + public FilterRequest(Request classRequest, Filter filter) { + fRequest= classRequest; + fFilter= filter; + } + + @Override + public Runner getRunner() { + try { + Runner runner= fRequest.getRunner(); + fFilter.apply(runner); + return runner; + } catch (NoTestsRemainException e) { + return Request.errorReport(Filter.class, new Exception(String + .format("No tests found matching %s from %s", fFilter + .describe(), fRequest.toString()))).getRunner(); + } + } +} \ No newline at end of file diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/requests/SortingRequest.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/requests/SortingRequest.java new file mode 100644 index 0000000000..512301cc99 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/requests/SortingRequest.java @@ -0,0 +1,26 @@ +package org.litejunit.v3.internal.requests; + + +import org.litejunit.v3.runner.Description; +import org.litejunit.v3.runner.Request; +import org.litejunit.v3.runner.Runner; +import org.litejunit.v3.runner.manipulation.Sorter; + +import java.util.Comparator; + +public class SortingRequest extends Request { + private final Request fRequest; + private final Comparator fComparator; + + public SortingRequest(Request request, Comparator comparator) { + fRequest= request; + fComparator= comparator; + } + + @Override + public Runner getRunner() { + Runner runner= fRequest.getRunner(); + new Sorter(fComparator).apply(runner); + return runner; + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/BeforeAndAfterRunner.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/BeforeAndAfterRunner.java new file mode 100644 index 0000000000..d54e5b4e23 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/BeforeAndAfterRunner.java @@ -0,0 +1,76 @@ +package org.litejunit.v3.internal.runners; + +import java.lang.annotation.Annotation; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; + +public abstract class BeforeAndAfterRunner { + private static class FailedBefore extends Exception { + private static final long serialVersionUID= 1L; + } + + private final Class fBeforeAnnotation; + + private final Class fAfterAnnotation; + + private TestIntrospector fTestIntrospector; + + private Object fTest; + + public BeforeAndAfterRunner(Class testClass, + Class beforeAnnotation, + Class afterAnnotation, + Object test) { + fBeforeAnnotation= beforeAnnotation; + fAfterAnnotation= afterAnnotation; + fTestIntrospector= new TestIntrospector(testClass); + fTest= test; + } + + public void runProtected() { + try { + runBefores(); + runUnprotected(); + } catch (FailedBefore e) { + } finally { + runAfters(); + } + } + + protected abstract void runUnprotected(); + + protected abstract void addFailure(Throwable targetException); + + // Stop after first failed @Before + private void runBefores() throws FailedBefore { + try { + List befores= fTestIntrospector.getTestMethods(fBeforeAnnotation); + for (Method before : befores) + invokeMethod(before); + } catch (InvocationTargetException e) { + addFailure(e.getTargetException()); + throw new FailedBefore(); + } catch (Throwable e) { + addFailure(e); + throw new FailedBefore(); + } + } + + // Try to run all @Afters regardless + private void runAfters() { + List afters= fTestIntrospector.getTestMethods(fAfterAnnotation); + for (Method after : afters) + try { + invokeMethod(after); + } catch (InvocationTargetException e) { + addFailure(e.getTargetException()); + } catch (Throwable e) { + addFailure(e); // Untested, but seems impossible + } + } + + private void invokeMethod(Method method) throws Exception { + method.invoke(fTest); + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/CompositeRunner.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/CompositeRunner.java new file mode 100644 index 0000000000..c19303bba6 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/CompositeRunner.java @@ -0,0 +1,70 @@ +package org.litejunit.v3.internal.runners; + +import org.litejunit.v3.runner.Description; +import org.litejunit.v3.runner.Runner; +import org.litejunit.v3.runner.manipulation.*; +import org.litejunit.v3.runner.notification.RunNotifier; + +import java.util.*; + +public class CompositeRunner extends Runner implements Filterable, Sortable { + private final List fRunners= new ArrayList(); + private final String fName; + + public CompositeRunner(String name) { + fName= name; + } + + @Override + public void run(RunNotifier notifier) { + for (Runner each : fRunners) + each.run(notifier); + } + + @Override + public Description getDescription() { + Description spec= Description.createSuiteDescription(fName); + for (Runner runner : fRunners) { + spec.addChild(runner.getDescription()); + } + return spec; + } + + public List getRunners() { + return fRunners; + } + + public void addAll(List runners) { + fRunners.addAll(runners); + } + + public void add(Runner runner) { + fRunners.add(runner); + } + + public void filter(Filter filter) throws NoTestsRemainException { + for (Iterator iter= fRunners.iterator(); iter.hasNext();) { + Runner runner= (Runner) iter.next(); + if (filter.shouldRun(runner.getDescription())) { + filter.apply(runner); + } else { + iter.remove(); + } + } + } + + protected String getName() { + return fName; + } + + public void sort(final Sorter sorter) { + Collections.sort(fRunners, new Comparator() { + public int compare(Runner o1, Runner o2) { + return sorter.compare(o1.getDescription(), o2.getDescription()); + } + }); + for (Runner each : fRunners) { + sorter.apply(each); + } + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/ErrorReportingRunner.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/ErrorReportingRunner.java new file mode 100644 index 0000000000..51ef6ae20b --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/ErrorReportingRunner.java @@ -0,0 +1,34 @@ +/** + * + */ +package org.litejunit.v3.internal.runners; + + +import org.litejunit.v3.runner.Description; +import org.litejunit.v3.runner.Runner; +import org.litejunit.v3.runner.notification.Failure; +import org.litejunit.v3.runner.notification.RunNotifier; + +public class ErrorReportingRunner extends Runner { + private final Description fDescription; + + private final Throwable fCause; + + public ErrorReportingRunner(Description description, Throwable cause) { + fDescription= description; + fCause= cause; + } + + @Override + public Description getDescription() { + return fDescription; + } + + // TODO: this is duplicated in TestClassMethodsRunner + @Override + public void run(RunNotifier notifier) { + notifier.fireTestStarted(fDescription); + notifier.fireTestFailure(new Failure(fDescription, fCause)); + notifier.fireTestFinished(fDescription); + } +} \ No newline at end of file diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/InitializationError.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/InitializationError.java new file mode 100644 index 0000000000..b3965291d8 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/InitializationError.java @@ -0,0 +1,25 @@ +package org.litejunit.v3.internal.runners; + +import java.util.Arrays; +import java.util.List; + +public class InitializationError extends Exception { + private static final long serialVersionUID= 1L; + private final List fErrors; + + public InitializationError(List errors) { + fErrors= errors; + } + + public InitializationError(Throwable... errors) { + this(Arrays.asList(errors)); + } + + public InitializationError(String string) { + this(new Exception(string)); + } + + public List getCauses() { + return fErrors; + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/MethodValidator.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/MethodValidator.java new file mode 100644 index 0000000000..cd00bbf080 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/MethodValidator.java @@ -0,0 +1,74 @@ +package org.litejunit.v3.internal.runners; + +import org.litejunit.v3.*; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +public class MethodValidator { + private final TestIntrospector fIntrospector; + + private final List fErrors= new ArrayList(); + + private final Class fTestClass; + + public MethodValidator(Class testClass) { + fTestClass= testClass; + fIntrospector= new TestIntrospector(testClass); + } + + public void validateInstanceMethods() { + validateTestMethods(After.class, false); + validateTestMethods(Before.class, false); + validateTestMethods(Test.class, false); + } + + public void validateStaticMethods() { + validateTestMethods(BeforeClass.class, true); + validateTestMethods(AfterClass.class, true); + } + + public List validateAllMethods() { + validateNoArgConstructor(); + validateStaticMethods(); + validateInstanceMethods(); + return fErrors; + } + + public void assertValid() throws InitializationError { + if (!fErrors.isEmpty()) + throw new InitializationError(fErrors); + } + + public void validateNoArgConstructor() { + try { + fTestClass.getConstructor(); + } catch (Exception e) { + fErrors.add(new Exception("Test class should have public zero-argument constructor", e)); + } + } + + private void validateTestMethods(Class annotation, + boolean isStatic) { + List methods= fIntrospector.getTestMethods(annotation); + for (Method each : methods) { + if (Modifier.isStatic(each.getModifiers()) != isStatic) { + String state= isStatic ? "should" : "should not"; + fErrors.add(new Exception("Method " + each.getName() + "() " + + state + " be static")); + } + if (!Modifier.isPublic(each.getModifiers())) + fErrors.add(new Exception("Method " + each.getName() + + " should be public")); + if (each.getReturnType() != Void.TYPE) + fErrors.add(new Exception("Method " + each.getName() + + " should be void")); + if (each.getParameterTypes().length != 0) + fErrors.add(new Exception("Method " + each.getName() + + " should have no parameters")); + } + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/TestClassMethodsRunner.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/TestClassMethodsRunner.java new file mode 100644 index 0000000000..bf9e36b8a8 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/TestClassMethodsRunner.java @@ -0,0 +1,103 @@ +package org.litejunit.v3.internal.runners; + +import org.litejunit.v3.Test; +import org.litejunit.v3.runner.Description; +import org.litejunit.v3.runner.Runner; +import org.litejunit.v3.runner.manipulation.*; +import org.litejunit.v3.runner.notification.Failure; +import org.litejunit.v3.runner.notification.RunNotifier; + +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; + +public class TestClassMethodsRunner extends Runner implements Filterable, Sortable { + private final List fTestMethods; + private final Class fTestClass; + + // This assumes that some containing runner will perform validation of the test methods + public TestClassMethodsRunner(Class klass) { + fTestClass= klass; + fTestMethods= new TestIntrospector(getTestClass()).getTestMethods(Test.class); + } + + @Override + public void run(RunNotifier notifier) { + if (fTestMethods.isEmpty()) + testAborted(notifier, getDescription()); + for (Method method : fTestMethods) + invokeTestMethod(method, notifier); + } + + private void testAborted(RunNotifier notifier, Description description) { + // TODO: duped! + // TODO: envious + notifier.fireTestStarted(description); + notifier.fireTestFailure(new Failure(description, new Exception("No runnable methods"))); + notifier.fireTestFinished(description); + } + + @Override + public Description getDescription() { + Description spec= Description.createSuiteDescription(getName()); + List testMethods= fTestMethods; + for (Method method : testMethods) + spec.addChild(methodDescription(method)); + return spec; + } + + protected String getName() { + return getTestClass().getName(); + } + + protected Object createTest() throws Exception { + return getTestClass().getConstructor().newInstance(); + } + + protected void invokeTestMethod(Method method, RunNotifier notifier) { + Object test; + try { + test= createTest(); + } catch (Exception e) { + testAborted(notifier, methodDescription(method)); + return; + } + createMethodRunner(test, method, notifier).run(); + } + + protected TestMethodRunner createMethodRunner(Object test, Method method, RunNotifier notifier) { + return new TestMethodRunner(test, method, notifier, methodDescription(method)); + } + + protected String testName(Method method) { + return method.getName(); + } + + protected Description methodDescription(Method method) { + return Description.createTestDescription(getTestClass(), testName(method)); + } + + public void filter(Filter filter) throws NoTestsRemainException { + for (Iterator iter= fTestMethods.iterator(); iter.hasNext();) { + Method method= (Method) iter.next(); + if (!filter.shouldRun(methodDescription(method))) + iter.remove(); + } + if (fTestMethods.isEmpty()) + throw new NoTestsRemainException(); + } + + public void sort(final Sorter sorter) { + Collections.sort(fTestMethods, new Comparator() { + public int compare(Method o1, Method o2) { + return sorter.compare(methodDescription(o1), methodDescription(o2)); + } + }); + } + + protected Class getTestClass() { + return fTestClass; + } +} \ No newline at end of file diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/TestClassRunner.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/TestClassRunner.java new file mode 100644 index 0000000000..b2feee7cb1 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/TestClassRunner.java @@ -0,0 +1,70 @@ +package org.litejunit.v3.internal.runners; + +import org.litejunit.v3.AfterClass; +import org.litejunit.v3.BeforeClass; +import org.litejunit.v3.runner.Description; +import org.litejunit.v3.runner.Runner; +import org.litejunit.v3.runner.manipulation.*; +import org.litejunit.v3.runner.notification.Failure; +import org.litejunit.v3.runner.notification.RunNotifier; + +public class TestClassRunner extends Runner implements Filterable, Sortable { + protected final Runner fEnclosedRunner; + private final Class fTestClass; + + public TestClassRunner(Class klass) throws InitializationError { + this(klass, new TestClassMethodsRunner(klass)); + } + + public TestClassRunner(Class klass, Runner runner) throws InitializationError { + fTestClass= klass; + fEnclosedRunner= runner; + MethodValidator methodValidator= new MethodValidator(klass); + validate(methodValidator); + methodValidator.assertValid(); + } + + // TODO: this is parallel to passed-in runner + protected void validate(MethodValidator methodValidator) { + methodValidator.validateAllMethods(); + } + + @Override + public void run(final RunNotifier notifier) { + BeforeAndAfterRunner runner = new BeforeAndAfterRunner(getTestClass(), + BeforeClass.class, AfterClass.class, null) { + @Override + protected void runUnprotected() { + fEnclosedRunner.run(notifier); + } + + // TODO: looks very similar to other method of BeforeAfter, now + @Override + protected void addFailure(Throwable targetException) { + notifier.fireTestFailure(new Failure(getDescription(), targetException)); + } + }; + + runner.runProtected(); + } + + @Override + public Description getDescription() { + return fEnclosedRunner.getDescription(); + } + + // TODO: good behavior when createTest fails + + // TODO: dup? + public void filter(Filter filter) throws NoTestsRemainException { + filter.apply(fEnclosedRunner); + } + + public void sort(Sorter sorter) { + sorter.apply(fEnclosedRunner); + } + + protected Class getTestClass() { + return fTestClass; + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/TestIntrospector.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/TestIntrospector.java new file mode 100644 index 0000000000..8e278282a0 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/TestIntrospector.java @@ -0,0 +1,78 @@ +package org.litejunit.v3.internal.runners; + +import org.litejunit.v3.Before; +import org.litejunit.v3.BeforeClass; +import org.litejunit.v3.Ignore; +import org.litejunit.v3.Test; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + + +public class TestIntrospector { + private final Class< ?> fTestClass; + + public TestIntrospector(Class testClass) { + fTestClass= testClass; + } + + public List getTestMethods(Class annotationClass) { + List results= new ArrayList(); + for (Class eachClass : getSuperClasses(fTestClass)) { + Method[] methods= eachClass.getDeclaredMethods(); + for (Method eachMethod : methods) { + Annotation annotation= eachMethod.getAnnotation(annotationClass); + if (annotation != null && ! isShadowed(eachMethod, results)) + results.add(eachMethod); + } + } + if (runsTopToBottom(annotationClass)) + Collections.reverse(results); + return results; + } + + public boolean isIgnored(Method eachMethod) { + return eachMethod.getAnnotation(Ignore.class) != null; + } + + private boolean runsTopToBottom(Class< ? extends Annotation> annotation) { + return annotation.equals(Before.class) || annotation.equals(BeforeClass.class); + } + + private boolean isShadowed(Method method, List results) { + for (Method each : results) { + if (each.getName().equals(method.getName())) + return true; + } + return false; + } + + private List getSuperClasses(Class< ?> testClass) { + ArrayList results= new ArrayList(); + Class current= testClass; + while (current != null) { + results.add(current); + current= current.getSuperclass(); + } + return results; + } + + long getTimeout(Method method) { + Test annotation= method.getAnnotation(Test.class); + long timeout= annotation.timeout(); + return timeout; + } + + Class expectedException(Method method) { + Test annotation= method.getAnnotation(Test.class); + if (annotation.expected() == Test.None.class) + return null; + else + return annotation.expected(); + } + +} + diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/TestMethodRunner.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/TestMethodRunner.java new file mode 100644 index 0000000000..eded6d6ff6 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/TestMethodRunner.java @@ -0,0 +1,114 @@ +package org.litejunit.v3.internal.runners; + +import org.litejunit.v3.After; +import org.litejunit.v3.Before; +import org.litejunit.v3.runner.Description; +import org.litejunit.v3.runner.notification.Failure; +import org.litejunit.v3.runner.notification.RunNotifier; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.concurrent.*; + +public class TestMethodRunner extends BeforeAndAfterRunner { + private final Object fTest; + private final Method fMethod; + private final RunNotifier fNotifier; + private final TestIntrospector fTestIntrospector; + private final Description fDescription; + + public TestMethodRunner(Object test, Method method, RunNotifier notifier, Description description) { + super(test.getClass(), Before.class, After.class, test); + fTest= test; + fMethod= method; + fNotifier= notifier; + fTestIntrospector= new TestIntrospector(test.getClass()); + fDescription= description; + } + + public void run() { + if (fTestIntrospector.isIgnored(fMethod)) { + fNotifier.fireTestIgnored(fDescription); + return; + } + fNotifier.fireTestStarted(fDescription); + try { + long timeout= fTestIntrospector.getTimeout(fMethod); + if (timeout > 0) + runWithTimeout(timeout); + else + runMethod(); + } finally { + fNotifier.fireTestFinished(fDescription); + } + } + + private void runWithTimeout(long timeout) { + ExecutorService service= Executors.newSingleThreadExecutor(); + Callable callable= new Callable() { + public Object call() throws Exception { + runMethod(); + return null; + } + }; + Future result= service.submit(callable); + service.shutdown(); + try { + boolean terminated= service.awaitTermination(timeout, + TimeUnit.MILLISECONDS); + if (!terminated) + service.shutdownNow(); + result.get(timeout, TimeUnit.MILLISECONDS); // throws the exception if one occurred during the invocation + } catch (TimeoutException e) { + addFailure(new Exception(String.format("test timed out after %d milliseconds", timeout))); + } catch (Exception e) { + addFailure(e); + } + } + + private void runMethod() { + runProtected(); + } + + @Override + protected void runUnprotected() { + try { + executeMethodBody(); + if (expectsException()) + addFailure(new AssertionError("Expected exception: " + expectedException().getName())); + } catch (InvocationTargetException e) { + Throwable actual= e.getTargetException(); + if (!expectsException()) + addFailure(actual); + else if (isUnexpected(actual)) { + String message= "Unexpected exception, expected<" + expectedException().getName() + "> but was<" + + actual.getClass().getName() + ">"; + addFailure(new Exception(message, actual)); + } + } catch (Throwable e) { + addFailure(e); + } + } + + protected void executeMethodBody() throws IllegalAccessException, InvocationTargetException { + fMethod.invoke(fTest); + } + + @Override + protected void addFailure(Throwable e) { + fNotifier.fireTestFailure(new Failure(fDescription, e)); + } + + private boolean expectsException() { + return expectedException() != null; + } + + private Class expectedException() { + return fTestIntrospector.expectedException(fMethod); + } + + private boolean isUnexpected(Throwable exception) { + return ! expectedException().isAssignableFrom(exception.getClass()); + } +} + diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/TextListener.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/TextListener.java new file mode 100644 index 0000000000..5d4d099c97 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/internal/runners/TextListener.java @@ -0,0 +1,105 @@ +package org.litejunit.v3.internal.runners; + + +import org.litejunit.v3.runner.Description; +import org.litejunit.v3.runner.Result; +import org.litejunit.v3.runner.notification.Failure; +import org.litejunit.v3.runner.notification.RunListener; + +import java.io.PrintStream; +import java.text.NumberFormat; + +public class TextListener extends RunListener { + + private final PrintStream fWriter; + + public TextListener() { + this(System.out); + } + + public TextListener(PrintStream writer) { + this.fWriter= writer; + } + + @Override + public void testRunFinished(Result result) { + printHeader(result.getRunTime()); + printFailures(result); + printFooter(result); + } + + @Override + public void testStarted(Description description) { + fWriter.append('.'); + } + + @Override + public void testFailure(Failure failure) { + fWriter.append('E'); + } + + @Override + public void testIgnored(Description description) { + fWriter.append('I'); + } + + /* + * Internal methods + */ + + private PrintStream getWriter() { + return fWriter; + } + + protected void printHeader(long runTime) { + getWriter().println(); + getWriter().println("Time: " + elapsedTimeAsString(runTime)); + } + + protected void printFailures(Result result) { + if (result.getFailureCount() == 0) + return; + if (result.getFailureCount() == 1) + getWriter().println("There was " + result.getFailureCount() + " failure:"); + else + getWriter().println("There were " + result.getFailureCount() + " failures:"); + int i= 1; + for (Failure each : result.getFailures()) + printFailure(each, i++); + } + + protected void printFailure(Failure failure, int count) { + printFailureHeader(failure, count); + printFailureTrace(failure); + } + + protected void printFailureHeader(Failure failure, int count) { + getWriter().println(count + ") " + failure.getTestHeader()); + } + + protected void printFailureTrace(Failure failure) { + getWriter().print(failure.getTrace()); + } + + protected void printFooter(Result result) { + if (result.wasSuccessful()) { + getWriter().println(); + getWriter().print("OK"); + getWriter().println(" (" + result.getRunCount() + " test" + (result.getRunCount() == 1 ? "" : "s") + ")"); + + } else { + getWriter().println(); + getWriter().println("FAILURES!!!"); + getWriter().println("Tests run: " + result.getRunCount() + ", Failures: " + result.getFailureCount()); + } + getWriter().println(); + } + + /** + * Returns the formatted string of the elapsed time. Duplicated from + * BaseTestRunner. Fix it. + */ + protected String elapsedTimeAsString(long runTime) { + return NumberFormat.getInstance().format((double) runTime / 1000); + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Description.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Description.java new file mode 100644 index 0000000000..55f401c2c2 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Description.java @@ -0,0 +1,127 @@ +package org.litejunit.v3.runner; + +import java.util.ArrayList; + +/** + * A Description describes a test which is to be run or has been run. Descriptions can + * be atomic (a single test) or compound (containing children tests). Descriptions are used + * to provide feedback about the tests that are about to run (for example, the tree view + * visible in many IDEs) or tests that have been run (for example, the failures view).

+ * Descriptions are implemented as a single class rather than a Composite because + * they are entirely informational. They contain no logic aside from counting their tests.

+ * In the past, we used the raw junit.framework.TestCases and junit.framework.TestSuites + * to display the tree of tests. This was no longer viable in JUnit 4 because atomic tests no longer have a superclass below Object. + * We needed a way to pass a class and name together. Description emerged from this. + * + * @see Request + * @see Runner + */ +public class Description { + + /** + * Create a Description named name. + * Generally, you will add children to this Description. + * @param name The name of the Description + * @return A Description named name + */ + public static Description createSuiteDescription(String name) { + return new Description(name); + } + + /** + * Create a Description of a single test named name in the class clazz. + * Generally, this will be a leaf Description. + * @param clazz The class of the test + * @param name The name of the test (a method name for test annotated with @Test) + * @return A Description named name + */ + public static Description createTestDescription(Class clazz, String name) { + return new Description(String.format("%s(%s)", name, clazz.getName())); + } + + /** + * Create a generic Description that says there are tests in testClass. + * This is used as a last resort when you cannot precisely describe the individual tests in the class. + * @param testClass A Class containing tests + * @return A Description of testClass + */ + public static Description createSuiteDescription(Class testClass) { + return new Description(testClass.getName()); + } + + public static Description TEST_MECHANISM = new Description("Test mechanism"); + private final ArrayList fChildren= new ArrayList(); + private final String fDisplayName; + + //TODO we seem to be using the static factories exclusively + private Description(final String displayName) { + fDisplayName= displayName; + } + + /** + * @return a user-understandable label + */ + public String getDisplayName() { + return fDisplayName; + } + + /** + * Add description as a child of the receiver. + * @param description The soon-to-be child. + */ + public void addChild(Description description) { + getChildren().add(description); + } + + /** + * @return the receiver's children, if any + */ + public ArrayList getChildren() { + return fChildren; + } + + /** + * @return true if the receiver is a suite + */ + public boolean isSuite() { + return !isTest(); + } + + /** + * @return true if the receiver is an atomic test + */ + public boolean isTest() { + return getChildren().isEmpty(); + } + + /** + * @return the total number of atomic tests in the receiver + */ + public int testCount() { + if (isTest()) + return 1; + int result= 0; + for (Description child : getChildren()) + result+= child.testCount(); + return result; + } + + @Override + public int hashCode() { + return getDisplayName().hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof Description)) + return false; + Description d = (Description) obj; + return getDisplayName().equals(d.getDisplayName()) + && getChildren().equals(d.getChildren()); + } + + @Override + public String toString() { + return getDisplayName(); + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/JUnitCore.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/JUnitCore.java new file mode 100644 index 0000000000..8e99a2c904 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/JUnitCore.java @@ -0,0 +1,152 @@ +package org.litejunit.v3.runner; + +import org.litejunit.v2.Test; +import org.litejunit.v3.internal.runners.TextListener; +import org.litejunit.v3.runner.notification.RunListener; +import org.litejunit.v3.runner.notification.RunNotifier; + +import java.util.ArrayList; +import java.util.List; + +/** + * JUnitCore is a facade for running tests. It supports running JUnit 4 tests, + * JUnit 3.8.2 tests, and mixtures. To run tests from the command line, run java org.junit.runner.JUnitCore TestClass1 TestClass2 .... + * For one-shot test runs, use the static method runClasses(Class... classes) + * . If you want to add special listeners, + * create an instance of JUnitCore first and use it to run the tests. + * + * @see Result + * @see RunListener + * @see Request + */ +public class JUnitCore { + + private RunNotifier fNotifier; + + /** + * Create a new JUnitCore to run tests. + */ + public JUnitCore() { + fNotifier = new RunNotifier(); + } + + /** + * Run the tests contained in the classes named in the args. + * If all tests run successfully, exit with a status of 0. Otherwise exit with a status of 1. + * Write feedback while tests are running and write + * stack traces for all failed tests after the tests all complete. + * + * @param args names of classes in which to find tests to run + */ + public static void main(String... args) { + Result result = new JUnitCore().runMain(args); + killAllThreads(result); + } + + private static void killAllThreads(Result result) { + System.exit(result.wasSuccessful() ? 0 : 1); + } + + /** + * Run the tests contained in classes. Write feedback while the tests + * are running and write stack traces for all failed tests after all tests complete. This is + * similar to main(), but intended to be used programmatically. + * + * @param classes Classes in which to find tests + * @return a Result describing the details of the test run and the failed tests. + */ + public static Result runClasses(Class... classes) { + return new JUnitCore().run(classes); + } + + /** + * Do not use. Testing purposes only. + */ + public Result runMain(String... args) { + System.out.println("JUnit version " + "4.0"); + List classes = new ArrayList(); + for (String each : args) + try { + classes.add(Class.forName(each)); + } catch (ClassNotFoundException e) { + System.out.println("Could not find class: " + each); + } + RunListener listener = new TextListener(); + addListener(listener); + return run(classes.toArray(new Class[0])); + } + + /** + * @return the version number of this release + */ + public String getVersion() { + return "4.0"; + } + + /** + * Run all the tests in classes. + * + * @param classes the classes containing tests + * @return a Result describing the details of the test run and the failed tests. + */ + public Result run(Class... classes) { + return run(Request.classes("All", classes)); + } + + /** + * Run all the tests contained in request. + * + * @param request the request describing tests + * @return a Result describing the details of the test run and the failed tests. + */ + public Result run(Request request) { + return run(request.getRunner()); + } + + /** + * Run all the tests contained in JUnit 3.8.x test. Here for backward compatibility. + * + * @param test the old-style test + * @return a Result describing the details of the test run and the failed tests. + */ + public Result run(Test test) { +// return run(new OldTestClassRunner(test)); + return null; + } + + /** + * Do not use. Testing purposes only. + */ + public Result run(Runner runner) { + Result result = new Result(); + RunListener listener = result.createListener(); + addListener(listener); + try { + fNotifier.fireTestRunStarted(runner.getDescription()); + runner.run(fNotifier); + fNotifier.fireTestRunFinished(result); + } finally { + removeListener(listener); + } + return result; + } + + /** + * Add a listener to be notified as the tests run. + * + * @param listener the listener + * @see RunListener + */ + public void addListener(RunListener listener) { + fNotifier.addListener(listener); + } + + /** + * Remove a listener. + * + * @param listener the listener to remove + */ + public void removeListener(RunListener listener) { + fNotifier.removeListener(listener); + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Request.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Request.java new file mode 100644 index 0000000000..da1019f868 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Request.java @@ -0,0 +1,87 @@ +package org.litejunit.v3.runner; + +import org.litejunit.v3.internal.requests.*; +import org.litejunit.v3.runner.manipulation.Filter; + +import java.util.Comparator; + +/** + * A Request is an abstract description of tests to be run. Older versions of + * JUnit did not need such a concept--tests to be run were described either by classes containing + * tests or a tree of Tests. However, we want to support filtering and sorting, + * so we need a more abstract specification than the tests themselves and a richer + * specification than just the classes. + *

+ * The flow when JUnit runs tests is that a Request specifies some tests to be run -> + * a Runner is created for each class implied by the Request -> the Runner + * returns a detailed Description which is a tree structure of the tests to be run. + */ +public abstract class Request { + /** + * Create a Request that, when processed, will run a single test. + * This is done by filtering out all other tests. This method is used to support rerunning + * single tests. + * @param clazz the class of the test + * @param methodName the name of the test + * @return a Request that will cause a single test be run + */ + public static Request method(Class clazz, String methodName) { + Description method= Description.createTestDescription(clazz, methodName); + return Request.aClass(clazz).filterWith(method); + } + + /** + * Create a Request that, when processed, will run all the tests + * in a class. The odd name is necessary because class is a reserved word. + * @param clazz the class containing the tests + * @return a Request that will cause all tests in the class to be run + */ + public static Request aClass(Class clazz) { + return new ClassRequest(clazz); + } + + /** + * Create a Request that, when processed, will run all the tests + * in a set of classes. + * @param collectionName a name to identify this suite of tests + * @param classes the classes containing the tests + * @return a Request that will cause all tests in the classes to be run + */ + public static Request classes(String collectionName, Class... classes) { + return new ClassesRequest(collectionName, classes); + } + + public static Request errorReport(Class klass, Throwable cause) { + return new ErrorReportingRequest(klass, cause); + } + + public abstract Runner getRunner(); + + public Request filterWith(Filter filter) { + return new FilterRequest(this, filter); + } + + public Request filterWith(final Description desiredDescription) { + return filterWith(new Filter() { + @Override + public boolean shouldRun(Description description) { + // TODO: test for equality even if we have children? + if (description.isTest()) + return desiredDescription.equals(description); + for (Description each : description.getChildren()) + if (shouldRun(each)) + return true; + return false; + } + + @Override + public String describe() { + return String.format("Method %s", desiredDescription.getDisplayName()); + } + }); + } + + public Request sortWith(Comparator comparator) { + return new SortingRequest(this, comparator); + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Result.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Result.java new file mode 100644 index 0000000000..67a92f1b6a --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Result.java @@ -0,0 +1,97 @@ +package org.litejunit.v3.runner; + +import org.litejunit.v3.runner.notification.Failure; +import org.litejunit.v3.runner.notification.RunListener; + +import java.util.ArrayList; +import java.util.List; + +/** + * A Result collects and summarizes information from running multiple + * tests. Since tests are expected to run correctly, successful tests are only noted in + * the count of tests that ran. + */ +public class Result { + private int fCount= 0; + private int fIgnoreCount= 0; + private List fFailures= new ArrayList(); + private long fRunTime= 0; + private long fStartTime; + + /** + * @return the number of tests run + */ + public int getRunCount() { + return fCount; + } + + /** + * @return the number of tests that failed during the run + */ + public int getFailureCount() { + return fFailures.size(); + } + + /** + * @return the number of milliseconds it took to run the entire suite to run + */ + public long getRunTime() { + return fRunTime; + } + + /** + * @return the Failures describing tests that failed and the problems they encountered + */ + public List getFailures() { + return fFailures; + } + + /** + * @return the number of tests ignored during the run + */ + public int getIgnoreCount() { + return fIgnoreCount; + } + + /** + * @return true if all tests succeeded + */ + public boolean wasSuccessful() { + return getFailureCount() == 0; + } + + private class Listener extends RunListener { + @Override + public void testRunStarted(Description description) throws Exception { + fStartTime= System.currentTimeMillis(); + } + + @Override + public void testRunFinished(Result result) throws Exception { + long endTime= System.currentTimeMillis(); + fRunTime+= endTime - fStartTime; + } + + @Override + public void testStarted(Description description) throws Exception { + fCount++; + } + + @Override + public void testFailure(Failure failure) throws Exception { + fFailures.add(failure); + } + + @Override + public void testIgnored(Description description) throws Exception { + fIgnoreCount++; + } + } + + /** + * Internal use only. + */ + public RunListener createListener() { + return new Listener(); + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/RunWith.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/RunWith.java new file mode 100644 index 0000000000..d69d030f20 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/RunWith.java @@ -0,0 +1,25 @@ +package org.litejunit.v3.runner; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +//TODO add simple exampel + +/** + * When you annotate a class with @RunWith, JUnit will invoke + * the class it references to run the tests in that class instead of the runner + * built into JUnit. We added this feature late in development. While it + * seems powerful we expect the runner API to change as we learn how people + * really use it. Some of the classes that are currently internal will likely be refined + * and become public. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface RunWith { + /** + * @return a Runner class (must have a constructor that takes a single Class to run) + */ + Class value(); +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Runner.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Runner.java new file mode 100644 index 0000000000..96f0fc3581 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/Runner.java @@ -0,0 +1,34 @@ +package org.litejunit.v3.runner; + +import org.litejunit.v3.runner.notification.RunNotifier; + +/** + * A Runner runs tests and notifies a RunNotifier + * of significant events as it does so. You will need to subclass Runner + * when using @RunWith to invoke a custom runner. When creating + * a custom runner, in addition to implementing the abstract methods here you must + * also provide a constructor that takes as an argument the Class containing + * the tests. + * + * @see Description + * @see RunWith + */ +public abstract class Runner { + /** + * @return a Description showing the tests to be run by the receiver + */ + public abstract Description getDescription(); + + /** + * Run the tests for this runner. + * @param notifier will be notified of events while tests are being run--tests being started, finishing, and failing + */ + public abstract void run(RunNotifier notifier); + + /** + * @return the number of tests to be run by the receiver + */ + public int testCount() { + return getDescription().testCount(); + } +} \ No newline at end of file diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/manipulation/Filter.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/manipulation/Filter.java new file mode 100644 index 0000000000..eaca8b8c98 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/manipulation/Filter.java @@ -0,0 +1,50 @@ +package org.litejunit.v3.runner.manipulation; + +import org.litejunit.v3.runner.Description; +import org.litejunit.v3.runner.Runner; + +/** + * The canonical case of filtering is when you want to run a single test method in a class. Rather + * than introduce runner API just for that one case, JUnit provides a general filtering mechanism. + * If you want to filter the tests to be run, extend Filter and apply an instance of + * your filter to the Request before running it (see JUnitCore.run(Request request)). + * Alternatively, apply a Filter to a Runner before running + * tests (for example, in conjunction with @RunWith. + */ +public abstract class Filter { + /** + * A null Filter that passes all tests through. + */ + public static Filter ALL= new Filter() { + @Override + public boolean shouldRun(Description description) { + return true; + } + + @Override + public String describe() { + return "all tests"; + } + }; + + /** + * @param description the description of the test to be run + * @return true if the test should be run + */ + public abstract boolean shouldRun(Description description); + + /** + * Invoke with a Runner to cause all tests it intends to run + * to first be checked with the filter. Only those that pass the filter will be run. + * @param runner the runner to be filtered by the receiver + * @throws NoTestsRemainException if the receiver removes all tests + */ + public void apply(Runner runner) throws NoTestsRemainException { + if (runner instanceof Filterable) { + Filterable filterable= (Filterable)runner; + filterable.filter(this); + } + } + + public abstract String describe(); +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/manipulation/Filterable.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/manipulation/Filterable.java new file mode 100644 index 0000000000..a1dbc96b8b --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/manipulation/Filterable.java @@ -0,0 +1,16 @@ +package org.litejunit.v3.runner.manipulation; + +/** + * Runners that allow filtering should implement this interface. Implement filter() + * to remove tests that don't pass the filter. + */ +public interface Filterable { + + /** + * Remove tests that don't pass filter. + * @param filter the filter to apply + * @throws NoTestsRemainException if all tests are filtered out + */ + void filter(Filter filter) throws NoTestsRemainException; + +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/manipulation/NoTestsRemainException.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/manipulation/NoTestsRemainException.java new file mode 100644 index 0000000000..bacf9fffc0 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/manipulation/NoTestsRemainException.java @@ -0,0 +1,8 @@ +package org.litejunit.v3.runner.manipulation; + +/** + * Thrown when a filter removes all tests from a runner. + */ +public class NoTestsRemainException extends Exception { + private static final long serialVersionUID = 1L; +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/manipulation/Sortable.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/manipulation/Sortable.java new file mode 100644 index 0000000000..3c96dcdf7e --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/manipulation/Sortable.java @@ -0,0 +1,13 @@ +package org.litejunit.v3.runner.manipulation; + +/** + * Interface for runners that allow sorting of tests. By sorting tests based on when they last failed, most recently + * failed first, you can reduce the average time to the first test failing. Test sorting should not be used to + * cope with order dependencies between tests. Tests that are isolated from each other are less + * expensive to maintain and can be run individually. + */ +public interface Sortable { + + public void sort(Sorter sorter); + +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/manipulation/Sorter.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/manipulation/Sorter.java new file mode 100644 index 0000000000..e759861060 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/manipulation/Sorter.java @@ -0,0 +1,31 @@ +package org.litejunit.v3.runner.manipulation; + +import org.litejunit.v3.runner.Description; +import org.litejunit.v3.runner.Runner; + +import java.util.Comparator; + +//TODO add an example + +/** + * A Sorter orders tests. In general you will not need + * to use a Sorter directly. Instead, use Request.sortWith(Comparator). + */ +public class Sorter implements Comparator { + private final Comparator fComparator; + + public Sorter(Comparator comparator) { + fComparator= comparator; + } + + public void apply(Runner runner) { + if (runner instanceof Sortable) { + Sortable sortable= (Sortable) runner; + sortable.sort(this); + } + } + + public int compare(Description o1, Description o2) { + return fComparator.compare(o1, o2); + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/notification/Failure.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/notification/Failure.java new file mode 100644 index 0000000000..aaffd9ee39 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/notification/Failure.java @@ -0,0 +1,77 @@ +package org.litejunit.v3.runner.notification; + +import org.litejunit.v3.runner.Description; + +import java.io.PrintWriter; +import java.io.StringWriter; + +/** + * A Failure holds a description of the failed test and the + * exception that was thrown while running it. In most cases the Description + * will be of a single test. However, if problems are encountered while constructing the + * test (for example, if a @BeforeClass method is not static), it may describe + * something other than a single test. + */ +public class Failure { + private final Description fDescription; + private Throwable fThrownException; + + /** + * Constructs a Failure with the given description and exception. + * @param description a Description of the test that failed + * @param thrownException the exception that was thrown while running the test + */ + public Failure(Description description, Throwable thrownException) { + fThrownException = thrownException; + fDescription= description; + } + + /** + * @return a user-understandable label for the test + */ + public String getTestHeader() { + return fDescription.getDisplayName(); + } + + /** + * @return the raw description of the context of the failure. + */ + public Description getDescription() { + return fDescription; + } + + /** + * @return the exception thrown + */ + + public Throwable getException() { + return fThrownException; + } + + @Override + public String toString() { + StringBuffer buffer= new StringBuffer(); + buffer.append(getTestHeader() + ": "+fThrownException.getMessage()); + return buffer.toString(); + } + + /** + * Convenience method + * @return the printed form of the exception + */ + public String getTrace() { + StringWriter stringWriter= new StringWriter(); + PrintWriter writer= new PrintWriter(stringWriter); + getException().printStackTrace(writer); + StringBuffer buffer= stringWriter.getBuffer(); + return buffer.toString(); + } + + /** + * Convenience method + * @return the message of the thrown exception + */ + public String getMessage() { + return getException().getMessage(); + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/notification/RunListener.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/notification/RunListener.java new file mode 100644 index 0000000000..4af71678a1 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/notification/RunListener.java @@ -0,0 +1,79 @@ +package org.litejunit.v3.runner.notification; + +import org.litejunit.v3.runner.Description; +import org.litejunit.v3.runner.JUnitCore; +import org.litejunit.v3.runner.Result; + +/** + * If you need to respond to the events during a test run, extend RunListener + * and override the appropriate methods. If a listener throws an exception while processing a + * test event, it will be removed for the remainder of the test run. + *

+ * For example, suppose you have a Cowbell + * class that you want to make a noise whenever a test fails. You could write:
+ * + * public class RingingListener extends RunListener { + * %nbsp;%nbsp;public void testFailure(Failure failure) { + * %nbsp;%nbsp;%nbsp;%nbsp;Cowbell.ring(); + * %nbsp;%nbsp;} + * } + * + *

+ * To invoke your listener, you need to run your tests through JUnitCore.
+ * + * public void main(String... args) { + * %nbsp;%nbsp;JUnitCore core= new JUnitCore(); + * %nbsp;%nbsp;core.addListener(new RingingListener()); + * %nbsp;%nbsp; + * core.run(MyTestClass.class); + * } + * + * @see JUnitCore + */ +public class RunListener { + + /** + * Called before any tests have been run. + * @param description describes the tests to be run + */ + public void testRunStarted(Description description) throws Exception { + } + + /** + * Called when all tests have finished + * @param result the summary of the test run, including all the tests that failed + */ + public void testRunFinished(Result result) throws Exception { + } + + /** + * Called when an atomic test is about to be started. + * @param description the description of the test that is about to be run (generally a class and method name) + */ + public void testStarted(Description description) throws Exception { + } + + /** + * Called when an atomic test has finished, whether the test succeeds or fails. + * @param description the description of the test that just ran + */ + public void testFinished(Description description) throws Exception { + } + + /** + * Called when an atomic test fails. + * @param failure describes the test that failed and the exception that was thrown + */ + public void testFailure(Failure failure) throws Exception { + } + + /** + * Called when a test will not be run, generally because a test method is annotated with @Ignored. + * @param description describes the test that will not be run + */ + public void testIgnored(Description description) throws Exception { + } + +} + + diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/notification/RunNotifier.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/notification/RunNotifier.java new file mode 100644 index 0000000000..74b6e688b1 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/notification/RunNotifier.java @@ -0,0 +1,137 @@ +package org.litejunit.v3.runner.notification; + +import org.litejunit.v3.runner.Description; +import org.litejunit.v3.runner.Result; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** + * If you write custom runners, you may need to notify JUnit of your progress running tests. + * Do this by invoking the RunNotifier passed to your implementation of + * Runner.run(RunNotifier notifier). Future evolution of this class is likely to + * move fireTestRunStarted() and fireTestRunFinished() + * to a separate class since they should only be called once per run. + */ +public class RunNotifier { + private List fListeners= new ArrayList(); + private boolean fPleaseStop= false; + + /** Internal use only + */ + public void addListener(RunListener listener) { + fListeners.add(listener); + } + + /** Internal use only + */ + public void removeListener(RunListener listener) { + fListeners.remove(listener); + } + + private abstract class SafeNotifier { + void run() { + for (Iterator all= fListeners.iterator(); all.hasNext();) { + try { + notifyListener(all.next()); + } catch (Exception e) { + all.remove(); // Remove the offending listener first to avoid an infinite loop + fireTestFailure(new Failure(Description.TEST_MECHANISM, e)); + } + } + } + + abstract protected void notifyListener(RunListener each) throws Exception; + } + + /** + * Do not invoke. + */ + public void fireTestRunStarted(final Description description) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testRunStarted(description); + }; + }.run(); + } + + /** + * Do not invoke. + */ + public void fireTestRunFinished(final Result result) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testRunFinished(result); + }; + }.run(); + } + + /** + * Invoke to tell listeners that an atomic test is about to start. + * @param description the description of the atomic test (generally a class and method name) + * @throws StoppedByUserException thrown if a user has requested that the test run stop + */ + public void fireTestStarted(final Description description) throws StoppedByUserException { + if (fPleaseStop) + throw new StoppedByUserException(); + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testStarted(description); + }; + }.run(); + } + + /** + * Invoke to tell listeners that an atomic test failed. + * @param failure the description of the test that failed and the exception thrown + */ + public void fireTestFailure(final Failure failure) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testFailure(failure); + }; + }.run(); + } + + /** + * Invoke to tell listeners that an atomic test was ignored. + * @param description the description of the ignored test + */ + public void fireTestIgnored(final Description description) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testIgnored(description); + }; + }.run(); + } + + /** + * Invoke to tell listeners that an atomic test finished. Always invoke fireTestFinished() + * if you invoke fireTestStarted() as listeners are likely to expect them to come in pairs. + * @param description the description of the test that finished + */ + public void fireTestFinished(final Description description) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testFinished(description); + }; + }.run(); + } + + /** + * Ask that the tests run stop before starting the next test. Phrased politely because + * the test currently running will not be interrupted. It seems a little odd to put this + * functionality here, but the RunNotifier is the only object guaranteed + * to be shared amongst the many runners involved. + */ + public void pleaseStop() { + fPleaseStop= true; + } +} \ No newline at end of file diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/notification/StoppedByUserException.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/notification/StoppedByUserException.java new file mode 100644 index 0000000000..f7c0bb3ae2 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runner/notification/StoppedByUserException.java @@ -0,0 +1,11 @@ +package org.litejunit.v3.runner.notification; + +/** + * Thrown when a user has requested that the test run stop. Writers of + * test running GUIs should be prepared to catch a StoppedByUserException. + * + * @see RunNotifier + */ +public class StoppedByUserException extends RuntimeException { + private static final long serialVersionUID= 1L; +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/Parameterized.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/Parameterized.java new file mode 100644 index 0000000000..8305522176 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/Parameterized.java @@ -0,0 +1,146 @@ +package org.litejunit.v3.runners; + + +import org.litejunit.v3.internal.runners.CompositeRunner; +import org.litejunit.v3.internal.runners.MethodValidator; +import org.litejunit.v3.internal.runners.TestClassMethodsRunner; +import org.litejunit.v3.internal.runners.TestClassRunner; + +import java.lang.annotation.*; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import static org.litejunit.v2.Assert.assertEquals; + + +/** The custom runner Parameterized implements parameterized + * tests. When running a parameterized test class, instances are created for the + * cross-product of the test methods and the test data elements.
+ *

+ * For example, to test a Fibonacci function, write: + * + *  
@RunWith(Parameterized.class)
+ * public class FibonacciTest {
+ *   @Parameters
+ *   public static Collection data() {
+ *     return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },
+ *       { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
+ *   }
+ *
+ *   private int fInput;
+ *   private int fExpected;
+ *
+ *   public FibonacciTest(int input, int expected) {
+ *     fInput= input;
+ *     fExpected= expected;
+ *   }
+ *
+ *   @Test public void test() {
+ *     assertEquals(fExpected, Fibonacci.compute(fInput));
+ *   }
+ * }
+ *
+ *

+ * Each instance of FibonacciTest will be constructed using the two-argument + * constructor and the data values in the @Parameters method. + */ +public class Parameterized extends TestClassRunner { + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.METHOD) + public static @interface Parameters { + } + + public static Collection eachOne(Object... params) { + List results= new ArrayList(); + for (Object param : params) + results.add(new Object[] { param }); + return results; + } + + // TODO: single-class this extension + + private static class TestClassRunnerForParameters extends TestClassMethodsRunner { + private final Object[] fParameters; + + private final int fParameterSetNumber; + + private final Constructor fConstructor; + + private TestClassRunnerForParameters(Class klass, Object[] parameters, int i) { + super(klass); + fParameters= parameters; + fParameterSetNumber= i; + fConstructor= getOnlyConstructor(); + } + + @Override + protected Object createTest() throws Exception { + return fConstructor.newInstance(fParameters); + } + + @Override + protected String getName() { + return String.format("[%s]", fParameterSetNumber); + } + + @Override + protected String testName(final Method method) { + return String.format("%s[%s]", method.getName(), fParameterSetNumber); + } + + private Constructor getOnlyConstructor() { + Constructor[] constructors= getTestClass().getConstructors(); + assertEquals(1, constructors.length); + return constructors[0]; + } + } + + // TODO: I think this now eagerly reads parameters, which was never the point. + + public static class RunAllParameterMethods extends CompositeRunner { + private final Class fKlass; + + public RunAllParameterMethods(Class klass) throws Exception { + super(klass.getName()); + fKlass= klass; + int i= 0; + for (final Object[] parameters : getParametersList()) { + super.add(new TestClassRunnerForParameters(klass, parameters, i++)); + } + } + + @SuppressWarnings("unchecked") + private Collection getParametersList() throws IllegalAccessException, InvocationTargetException, Exception { + return (Collection) getParametersMethod().invoke(null); + } + + private Method getParametersMethod() throws Exception { + for (Method each : fKlass.getMethods()) { + if (Modifier.isStatic(each.getModifiers())) { + Annotation[] annotations= each.getAnnotations(); + for (Annotation annotation : annotations) { + if (annotation.annotationType() == Parameters.class) + return each; + } + } + } + throw new Exception("No public static parameters method on class " + + getName()); + } + } + + public Parameterized(final Class klass) throws Exception { + super(klass, new RunAllParameterMethods(klass)); + } + + @Override + protected void validate(MethodValidator methodValidator) { + methodValidator.validateStaticMethods(); + methodValidator.validateInstanceMethods(); + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/Suite.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/Suite.java new file mode 100644 index 0000000000..23869ee08c --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/runners/Suite.java @@ -0,0 +1,50 @@ +package org.litejunit.v3.runners; + +import org.litejunit.v3.internal.runners.InitializationError; +import org.litejunit.v3.internal.runners.TestClassRunner; +import org.litejunit.v3.runner.Request; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Using Suite as a runner allows you to manually + * build a suite containing tests from many classes. It is the JUnit 4 equivalent of the JUnit 3.8.x + * static junit.framework.Test suite() method. To use it, annotate a class + * with @RunWith(Suite.class) and SuiteClasses(TestClass1.class, ...). + * When you run this class, it will run all the tests in all the suite classes. + */ +public class Suite extends TestClassRunner { + /** + * The SuiteClasses annotation specifies the classes to be run when a class + * annotated with @RunWith(Suite.class) is run. + */ + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.TYPE) + public @interface SuiteClasses { + public Class[] value(); + } + + /** + * Internal use only. + */ + public Suite(Class klass) throws InitializationError { + this(klass, getAnnotatedClasses(klass)); + } + + /** + * Internal use only. + */ + public Suite(Class klass, Class[] annotatedClasses) throws InitializationError { + super(klass, Request.classes(klass.getName(), annotatedClasses).getRunner()); + } + + private static Class[] getAnnotatedClasses(Class klass) throws InitializationError { + SuiteClasses annotation= klass.getAnnotation(SuiteClasses.class); + if (annotation == null) + throw new InitializationError(String.format("class '%s' must have a SuiteClasses annotation", klass.getName())); + return annotation.value(); + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/sample/AllTest.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/sample/AllTest.java new file mode 100644 index 0000000000..7b29bbe30a --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/sample/AllTest.java @@ -0,0 +1,40 @@ +package org.litejunit.v3.sample; + + +import org.litejunit.v3.runner.RunWith; +import org.litejunit.v3.runners.Suite; + +/** + * Created by john on 2017/9/2. + */ +@RunWith(Suite.class) +@Suite.SuiteClasses({ + CalculatorTest.class, + PersonTest.class +}) +public class AllTest { +// public static Test suite() { +// +// TestSuite suite = new TestSuite("All Test"); +// suite.addTest(CalculatorSuite.suite()); +// suite.addTestSuite(PersonTest.class); +// return suite; +// +// } + + +// static class OverallTestSetup extends TestSetup { +// +// public OverallTestSetup(Test test) { +// super(test); +// +// } +// protected void setUp() throws Exception { +// System.out.println("this is overall testsetup"); +// } +// protected void tearDown() throws Exception { +// System.out.println("this is overall teardown"); +// } +// +// } +} \ No newline at end of file diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/sample/Calculator.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/sample/Calculator.java new file mode 100644 index 0000000000..9627671885 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/sample/Calculator.java @@ -0,0 +1,25 @@ +package org.litejunit.v3.sample; + +/** + * Created by john on 2017/9/4. + */ +public class Calculator { + + private int result = 0; + public void add(int x){ + result += x; + } + public void subtract(int x){ + result -=x; + } + + public int getResult(){ + return this.result; + } + public static void main(String[] args){ + Calculator calculator = new Calculator(); + calculator.add(10); + calculator.subtract(5); + System.out.println(calculator.getResult()); + } +} \ No newline at end of file diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/sample/CalculatorTest.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/sample/CalculatorTest.java new file mode 100644 index 0000000000..578a3aa844 --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/sample/CalculatorTest.java @@ -0,0 +1,50 @@ +package org.litejunit.v3.sample; + + +import org.litejunit.v3.*; +import org.litejunit.v3.runner.JUnitCore; + +import static org.litejunit.v3.Assert.assertEquals; + +/** + * Created by john on 2017/9/4. + */ +public class CalculatorTest { + + Calculator calculator =null; + @Before + public void prepare(){ + calculator = new Calculator(); + } + @After + public void clean(){ + calculator = null; + } + @Test + public void testAdd(){ + + calculator.add(10); + assertEquals(15,calculator.getResult()); + } + @Test + public void testSubtract(){ + calculator.add(10); + calculator.subtract(5); + assertEquals(5,calculator.getResult()); + } + @BeforeClass + public static void prepareGlobalResouce(){ + System.err.println("prepare global resource"); + } + @AfterClass + public static void cleanGlobalResouce(){ + System.err.println("clean global resource"); + } + + + public static void main(String[] args){ + JUnitCore.main("org.litejunit.v3.sample.CalculatorTest"); +// JUnitCore.runClasses(CalculatorTest.class); + + } +} \ No newline at end of file diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/sample/ParametTestUnit.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/sample/ParametTestUnit.java new file mode 100644 index 0000000000..e7e86aa71e --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/sample/ParametTestUnit.java @@ -0,0 +1,54 @@ +package org.litejunit.v3.sample; + + +import org.litejunit.v3.Test; +import org.litejunit.v3.runner.RunWith; +import org.litejunit.v3.runners.Parameterized; + +import java.util.Arrays; +import java.util.Collection; + +import static org.litejunit.v3.Assert.assertEquals; + + +/** + * Created by john on 2017/9/6. + */ +@RunWith(Parameterized.class)//1.必须 +public class ParametTestUnit { + private int input; + private boolean expected;//expected result + + /** + * 2.public 构造器赋值一组测试数据 + */ + public ParametTestUnit(int input, boolean expected) { + this.input = input; + this.expected = expected; + } + + /** + * 3.由@Parameterized.Parameters修饰一个 + * public static Collection xxx() + */ + @Parameterized.Parameters + public static Collection data() { + return Arrays.asList(new Object[][]{ + {1, true}, + {3, true},// + {6, false}, + {11, true}, + {22, false}, + {23, true} + }); + } + + /** + * 4.JUnit循环地使用各组数据 + */ + @Test + public void testOdd() { + System.out.println("Parameterized Number is : " + input); + assertEquals(expected, input % 2 != 0); + } +} diff --git a/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/sample/PersonTest.java b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/sample/PersonTest.java new file mode 100644 index 0000000000..82ea9a1bbb --- /dev/null +++ b/students/315863321/ood/ood-assignment/src/main/java/org/litejunit/v3/sample/PersonTest.java @@ -0,0 +1,48 @@ +package org.litejunit.v3.sample; + + +import org.litejunit.v3.Before; +import org.litejunit.v3.Test; + +import static org.litejunit.v3.Assert.assertEquals; + +/** + * Created by john on 2017/9/2. + */ +public class PersonTest{ + + Person p = null; + @Before + public void setUp() { + p = new Person("andy",30); + } + + @Test + public void testAge(){ + assertEquals(30, p.getAge()); + } + + @Test + public void testName(){ + assertEquals("andy", p.getName()); + } +} + +class Person{ + private String name; + private int age; + + public Person(String name, int age) { + + this.name = name; + this.age = age; + } + public String getName() { + return name; + } + public int getAge() { + return age; + } + + +} \ No newline at end of file diff --git "a/students/315863321/uml/JUnit3\346\227\266\345\272\217\345\233\276.gliffy" "b/students/315863321/uml/JUnit3\346\227\266\345\272\217\345\233\276.gliffy" new file mode 100644 index 0000000000..52737f00ca --- /dev/null +++ "b/students/315863321/uml/JUnit3\346\227\266\345\272\217\345\233\276.gliffy" @@ -0,0 +1 @@ +{"contentType":"application/gliffy+json","version":"1.1","metadata":{"title":"untitled","revision":0,"exportBorder":false},"embeddedResources":{"index":0,"resources":[]},"stage":{"objects":[{"x":749,"y":860,"rotation":0,"id":142,"uid":"com.gliffy.shape.uml.uml_v1.default.self_message","width":45,"height":23,"lockAspectRatio":false,"lockShape":false,"order":54,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.self_message.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#000000","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[],"linkMap":[]},{"x":617,"y":881,"rotation":0,"id":141,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":53,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-65,-37],[21,-37],[21,-37],[107,-37]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":549,"y":787,"rotation":0,"id":138,"uid":"com.gliffy.shape.uml.uml_v1.default.self_message","width":45,"height":23,"lockAspectRatio":false,"lockShape":false,"order":51,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.self_message.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#000000","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[],"linkMap":[]},{"x":549,"y":740,"rotation":0,"id":135,"uid":"com.gliffy.shape.uml.uml_v1.default.self_message","width":45,"height":23,"lockAspectRatio":false,"lockShape":false,"order":49,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.self_message.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#000000","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[],"linkMap":[]},{"x":549,"y":691,"rotation":0,"id":132,"uid":"com.gliffy.shape.uml.uml_v1.default.self_message","width":45,"height":23,"lockAspectRatio":false,"lockShape":false,"order":47,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.self_message.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#000000","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[],"linkMap":[]},{"x":619,"y":676,"rotation":0,"id":130,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":45,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[106.00520819205587,-34],[-64.04705087092816,-33.999999999999886]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":749,"y":600,"rotation":0,"id":127,"uid":"com.gliffy.shape.uml.uml_v1.default.self_message","width":45,"height":23,"lockAspectRatio":false,"lockShape":false,"order":43,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.self_message.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#000000","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[],"linkMap":[]},{"x":730,"y":600,"rotation":0,"id":125,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":300,"lockAspectRatio":false,"lockShape":false,"order":41,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":137,"y":556,"rotation":0,"id":120,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":37,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

run(TestResult)

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":128,"y":569,"rotation":0,"id":119,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":36,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-6,0],[209.0023923308056,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":340.5,"y":564,"rotation":0,"id":118,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":336,"lockAspectRatio":false,"lockShape":false,"order":35,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":570,"y":520,"rotation":0,"id":117,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":34,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[159,-26],[-146,-26],[-146,-25],[-451,-25]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":135,"y":410,"rotation":0,"id":115,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":33,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

result= new TestResult()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":207.17582417582418,"y":451.1098901098901,"rotation":0,"id":114,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":32,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-84.3973759210142,-23.912087912087884],[474.021978021978,-23.912087912087884]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":204,"y":419,"rotation":0,"id":113,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":31,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[134,-59],[24,-59],[24,-59],[-86,-59]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":185,"y":469,"rotation":0,"id":112,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":30,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[346,-109],[258.5,-109],[258.5,-109],[171,-109]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":338.5,"y":280,"rotation":0,"id":109,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":29,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

new

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":381,"y":302,"rotation":0,"id":108,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":28,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-21.004132160848144,0],[100.00413201974408,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":357.5,"y":238.5,"rotation":0,"id":106,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":27,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

addTest(Test)

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":357.5,"y":234,"rotation":0,"id":104,"uid":"com.gliffy.shape.uml.uml_v1.default.self_message","width":45,"height":23,"lockAspectRatio":false,"lockShape":false,"order":26,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.self_message.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#000000","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[],"linkMap":[]},{"x":147,"y":93,"rotation":0,"id":102,"uid":"com.gliffy.shape.uml.uml_v1.default.association","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":25,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[43,78],[83,-31.5]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":100,"px":0,"py":0.5}}},"linkMap":[]},{"x":230,"y":30,"rotation":0,"id":100,"uid":"com.gliffy.shape.uml.uml_v1.default.note","width":118,"height":63,"lockAspectRatio":false,"lockShape":false,"order":23,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.note.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2.36,"y":0,"rotation":0,"id":103,"uid":null,"width":113.28,"height":14,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

把 class name 传入

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":113,"y":182,"rotation":0,"id":98,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":22,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

new

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":124,"y":196,"rotation":0,"id":97,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":21,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-5,0],[160.0121207669303,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":530,"y":593,"rotation":0,"id":58,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":307,"lockAspectRatio":false,"lockShape":false,"order":20,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":530,"y":330,"rotation":0,"id":45,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":30,"lockAspectRatio":false,"lockShape":false,"order":18,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":338.5,"y":234,"rotation":0,"id":40,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":126,"lockAspectRatio":false,"lockShape":false,"order":17,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":99.5,"y":164,"rotation":0,"id":39,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":736,"lockAspectRatio":false,"lockShape":false,"order":16,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":48,"y":126,"rotation":0,"id":18,"uid":"com.gliffy.shape.uml.uml_v1.default.object_timeline","width":120,"height":878,"lockAspectRatio":false,"lockShape":false,"order":0,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":19,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":20,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

TestRunner

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":20,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":21,"uid":null,"width":120,"height":860,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.object_timeline.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":null,"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":18,"magnitude":1},{"id":19,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":19,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":19,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":285.5,"y":189,"rotation":0,"id":22,"uid":"com.gliffy.shape.uml.uml_v1.default.object_timeline","width":120,"height":810,"lockAspectRatio":false,"lockShape":false,"order":4,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":23,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":24,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

:TestSuite\n

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":24,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":25,"uid":null,"width":120,"height":792,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.object_timeline.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":null,"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":22,"magnitude":1},{"id":23,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":23,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":23,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":480,"y":290,"rotation":0,"id":26,"uid":"com.gliffy.shape.uml.uml_v1.default.object_timeline","width":120,"height":724,"lockAspectRatio":false,"lockShape":false,"order":8,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":27,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":28,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

:TestCase

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":28,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":29,"uid":null,"width":120,"height":706,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.object_timeline.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":null,"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":26,"magnitude":1},{"id":27,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":27,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":27,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":730,"y":454,"rotation":0,"id":49,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":40,"lockAspectRatio":false,"lockShape":false,"order":19,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":680,"y":414,"rotation":0,"id":30,"uid":"com.gliffy.shape.uml.uml_v1.default.object_timeline","width":120,"height":600,"lockAspectRatio":false,"lockShape":false,"order":12,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":31,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":32,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

:TestResult\n

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":32,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":33,"uid":null,"width":120,"height":582,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.object_timeline.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":null,"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":30,"magnitude":1},{"id":31,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":31,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":31,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":359.5,"y":570,"rotation":0,"id":122,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":38,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

run(TestResult)

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":389,"y":600,"rotation":0,"id":123,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":39,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-26,-8],[139.0030302752043,-7.999999999999886]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":597,"y":648,"rotation":0,"id":124,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":40,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-47,-51],[130.10166571774528,-51]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":560,"y":570,"rotation":0,"id":126,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":42,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

run(TestCase)

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":739.5,"y":600,"rotation":0,"id":129,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":44,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

startTest()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":562,"y":623,"rotation":0,"id":131,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":46,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

doRun()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":539.5,"y":691,"rotation":0,"id":134,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":48,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

setUp()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":539.5,"y":740,"rotation":0,"id":137,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":50,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

runTest()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":539.5,"y":791.5,"rotation":0,"id":140,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":52,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

tearDown()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":739.5,"y":860,"rotation":0,"id":144,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":55,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

endTest()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":558,"y":925,"rotation":0,"id":146,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":56,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[164,-28],[79,-28],[79,-28],[-6,-28]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":368,"y":927,"rotation":0,"id":147,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":57,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[164,-28],[79,-28],[79,-28],[-6,-28]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":163,"y":927,"rotation":0,"id":148,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":58,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[175,-28],[66.5,-28],[66.5,-28],[-42,-28]],"lockSegments":{}}},"children":null,"linkMap":[]}],"background":"#FFFFFF","width":888,"height":1014,"maxWidth":5000,"maxHeight":5000,"nodeIndex":149,"autoFit":true,"exportBorder":false,"gridOn":true,"snapToGrid":true,"drawingGuidesOn":true,"pageBreaksOn":false,"printGridOn":false,"printPaper":"LETTER","printShrinkToFit":false,"printPortrait":true,"shapeStyles":{},"lineStyles":{},"textStyles":{},"themeData":null}} \ No newline at end of file diff --git "a/students/315863321/uml/JUnit3\347\261\273\345\233\276.gliffy" "b/students/315863321/uml/JUnit3\347\261\273\345\233\276.gliffy" new file mode 100644 index 0000000000..6497806282 --- /dev/null +++ "b/students/315863321/uml/JUnit3\347\261\273\345\233\276.gliffy" @@ -0,0 +1 @@ +{"contentType":"application/gliffy+json","version":"1.1","metadata":{"title":"untitled","revision":0,"exportBorder":false},"embeddedResources":{"index":0,"resources":[]},"stage":{"objects":[{"x":69.64285714285715,"y":79.39285714285714,"rotation":0,"id":175,"uid":"com.gliffy.shape.uml.uml_v1.default.association","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":175,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":1,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[3.357142857142847,207.60714285714286],[3.357142857142847,92.47362920476345],[70.35714285714288,92.47362920476345]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":168,"px":0.5,"py":0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":60,"px":1.1102230246251563e-16,"py":0.2928932188134525}}},"linkMap":[]},{"x":1019.6923076923077,"y":745,"rotation":0,"id":165,"uid":"com.gliffy.shape.uml.uml_v1.default.note","width":250.30769230769238,"height":170,"lockAspectRatio":false,"lockShape":false,"order":90,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.note.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":5.006153846153847,"y":0,"rotation":0,"id":176,"uid":null,"width":240.29538461538462,"height":98,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

Command模式:表达一个测试用例\n

模板方法模式:实现数据的准备和清理\n

组合模式:屏蔽一个和多个的差别\n

收集参数模式:隔离测试用例和测试结果\n

观察者模式:隔离测试结果和UI层\n

装饰器模式:装饰测试用例使得它可以重复运行\n

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":1051.6071428571427,"y":459.64285714285717,"rotation":0,"id":162,"uid":"com.gliffy.shape.uml.uml_v1.default.generalization","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":89,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":4,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-96.60714285714266,-1.6428571428571672],[-96.60714285714266,-21.154885329441584],[-96.60714285714266,-40.66691351602594],[-96.60714285714266,-60.17894170261036]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":151,"px":0.5,"py":0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":144,"px":0.5,"py":1}}},"linkMap":[]},{"x":1107.3214285714287,"y":310.60714285714283,"rotation":0,"id":161,"uid":"com.gliffy.shape.uml.uml_v1.default.aggregation","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":88,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":1,"endArrow":5,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-515.3214285714287,-248.6401514461339],[-17.32142857142867,-248.6401514461339],[-17.32142857142867,32.6248148629806],[-57.32142857142867,32.6248148629806]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":36,"px":1,"py":0.29289321881345237}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":144,"px":1,"py":0.5}}},"linkMap":[]},{"x":940.3653846153845,"y":229.75549450549448,"rotation":0,"id":160,"uid":"com.gliffy.shape.uml.uml_v1.default.implements","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":87,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":4,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[14.634615384615472,57.24450549450552],[14.634615384615472,-28.755494505494482],[-418.3653846153845,-28.755494505494482],[-418.3653846153845,-114.75549450549448]],"lockSegments":{"1":true}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":144,"px":0.5,"py":0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":36,"px":0.5,"py":1}}},"linkMap":[]},{"x":121,"y":794,"rotation":0,"id":136,"uid":"com.gliffy.shape.uml.uml_v1.default.generalization","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":72,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":4,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[23,66],[23,52.66666666666663],[23,39.33333333333337],[23,26]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":129,"px":0.5,"py":0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":113,"px":0.5,"py":1}}},"linkMap":[]},{"x":147,"y":632,"rotation":0,"id":128,"uid":"com.gliffy.shape.uml.uml_v1.default.implements","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":64,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":4,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-3,38],[-3,10.666666666666629],[-3,-16.66666666666663],[-3,-44]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":113,"px":0.5,"py":0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":94,"px":0.5,"py":1}}},"linkMap":[]},{"x":18,"y":478,"rotation":0,"id":94,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":252,"height":110,"lockAspectRatio":false,"lockShape":false,"order":47,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":95,"uid":null,"width":252,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":96,"uid":null,"width":252,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

TestListener

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":96,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":97,"uid":null,"width":252,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":98,"uid":null,"width":252,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":95,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":98,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":22,"rotation":0,"id":99,"uid":null,"width":252,"height":88,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":100,"uid":null,"width":252,"height":60,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

+ void addError(Test, Throwable)\n

+ void addFailure(Test, AssertionFailedError)\n

+ void endTest(Test)\n

+void startTest(Test)\n

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":94,"magnitude":1},{"id":95,"magnitude":-1},{"id":97,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":97,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":95,"magnitude":1},{"id":97,"magnitude":1},{"id":100,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":265,"y":526,"rotation":0,"id":111,"uid":"com.gliffy.shape.uml.uml_v1.default.association","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":56,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":1,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[4.844931234147168,1],[43.563287489431445,1],[82.28164374471572,1],[121,1]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":94,"px":1,"py":0.5}}},"linkMap":[]},{"x":720,"y":672,"rotation":0,"id":102,"uid":"com.gliffy.shape.uml.uml_v1.default.aggregation","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":55,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":1,"endArrow":5,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[3,23],[-29,23],[-29,-85],[-61,-85]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":76,"px":0,"py":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":69,"px":1,"py":0.5}}},"linkMap":[]},{"x":796,"y":288,"rotation":0,"id":101,"uid":"com.gliffy.shape.uml.uml_v1.default.aggregation","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":54,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":1,"endArrow":5,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-204,-194.96699141100893],[-26,-194.96699141100893],[-26,54],[-66,54]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":36,"px":0.9999999999999998,"py":0.7071067811865475}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":52,"px":1,"py":0.5}}},"linkMap":[]},{"x":194,"y":530,"rotation":0,"id":93,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":46,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[466,-133],[466,-85.5],[328,-85.5],[328,-40]],"lockSegments":{"1":true}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":52,"px":0.5,"py":1}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":69,"px":0.5,"py":0}}},"linkMap":[]},{"x":223,"y":448,"rotation":0,"id":92,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":45,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[187,-37],[187,-3.5],[299,-3.5],[299,42]],"lockSegments":{"1":true}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":43,"px":0.5,"py":1}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":69,"px":0.5,"py":0}}},"linkMap":[]},{"x":723,"y":645,"rotation":0,"id":76,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":160,"height":100,"lockAspectRatio":false,"lockShape":false,"order":38,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":77,"uid":null,"width":160,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":78,"uid":null,"width":160,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

TestFailure

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":78,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":79,"uid":null,"width":160,"height":32,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":80,"uid":null,"width":160,"height":32,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

- Test failedTest\n

- Throwable thrownException

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":77,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":80,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":50,"rotation":0,"id":81,"uid":null,"width":160,"height":50,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":82,"uid":null,"width":160,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":76,"magnitude":1},{"id":77,"magnitude":-1},{"id":79,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":79,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":77,"magnitude":1},{"id":79,"magnitude":1},{"id":82,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":385,"y":490,"rotation":0,"id":69,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":274,"height":194,"lockAspectRatio":false,"lockShape":false,"order":31,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":70,"uid":null,"width":274,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":71,"uid":null,"width":274,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

TestResult

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":71,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":72,"uid":null,"width":274,"height":46,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":73,"uid":null,"width":274,"height":46,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

- List<TestFailure> failures\n

- List<TestFailure> errors\n

- List<TestListener> listeners

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":70,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":73,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":64,"rotation":0,"id":74,"uid":null,"width":274,"height":130,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":75,"uid":null,"width":274,"height":130,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

+ void startTest(Test)\n

+ void endTest(Test)\n

+ void addError(Test, Throwable)\n

+ void addFailure(Test, AssertionFailedError)\n

+ void run(TestCase)\n

+ boolean wasSuccessful()\n

+ int errorCount()\n

+ int failureCount()\n

+ int runCount()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":69,"magnitude":1},{"id":70,"magnitude":-1},{"id":72,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":72,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":70,"magnitude":1},{"id":72,"magnitude":1},{"id":75,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":183,"y":338,"rotation":0,"id":68,"uid":"com.gliffy.shape.uml.uml_v1.default.generalization","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":30,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":4,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[157,11],[37,11],[37,-123]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":43,"px":0,"py":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":60,"px":0.5,"py":1}}},"linkMap":[]},{"x":140,"y":154,"rotation":0,"id":60,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":160,"height":61,"lockAspectRatio":false,"lockShape":false,"order":23,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":61,"uid":null,"width":160,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":62,"uid":null,"width":160,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

Assert

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":62,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":63,"uid":null,"width":160,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":64,"uid":null,"width":160,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":61,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":64,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":22,"rotation":0,"id":65,"uid":null,"width":160,"height":39,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":66,"uid":null,"width":160,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

void assertEquals()\n

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":60,"magnitude":1},{"id":61,"magnitude":-1},{"id":63,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":63,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":61,"magnitude":1},{"id":63,"magnitude":1},{"id":66,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":649,"y":234,"rotation":0,"id":59,"uid":"com.gliffy.shape.uml.uml_v1.default.implements","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":22,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":4,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[11,53],[11,-33],[-127,-33],[-127,-119]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":52,"px":0.5,"py":0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":36,"px":0.5,"py":1}}},"linkMap":[]},{"x":590,"y":287,"rotation":0,"id":52,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":140,"height":110,"lockAspectRatio":false,"lockShape":false,"order":15,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":53,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":54,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

TestSuite

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":54,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":55,"uid":null,"width":140,"height":32,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":56,"uid":null,"width":140,"height":32,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

- String name\n

- List<Test> tests

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":53,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":56,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":50,"rotation":0,"id":57,"uid":null,"width":140,"height":60,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":58,"uid":null,"width":140,"height":60,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

+ void run(TestResult)\n

+ void addTest(Test)\n

+ void addTestSuite(Test)\n

+ int countTestCases()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":52,"magnitude":1},{"id":53,"magnitude":-1},{"id":55,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":55,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":53,"magnitude":1},{"id":55,"magnitude":1},{"id":58,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":455,"y":269,"rotation":0,"id":50,"uid":"com.gliffy.shape.uml.uml_v1.default.implements","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":14,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":4,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-45,18],[-45,-68],[67,-68],[67,-154]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":43,"px":0.5,"py":0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":36,"px":0.5,"py":1}}},"linkMap":[]},{"x":340,"y":287,"rotation":0,"id":43,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":140,"height":124,"lockAspectRatio":false,"lockShape":false,"order":7,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":44,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":45,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

TestCase

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":45,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":46,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":47,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

- String name

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":44,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":47,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":36,"rotation":0,"id":48,"uid":null,"width":140,"height":88,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":49,"uid":null,"width":140,"height":88,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

+ int countTestCases()\n

+ void run(TestResult)\n

# void doRun()\n

# void runTest()\n

# void setUp()\n

# void tearDown()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":43,"magnitude":1},{"id":44,"magnitude":-1},{"id":46,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":46,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":44,"magnitude":1},{"id":46,"magnitude":1},{"id":49,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":452,"y":40,"rotation":0,"id":36,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":140,"height":75,"lockAspectRatio":false,"lockShape":false,"order":0,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":37,"uid":null,"width":140,"height":32,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":38,"uid":null,"width":140,"height":32,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

<<interface>>\n

Test

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":38,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":32,"rotation":0,"id":39,"uid":null,"width":140,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":40,"uid":null,"width":140,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":37,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":40,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":36,"rotation":0,"id":41,"uid":null,"width":140,"height":39,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":42,"uid":null,"width":140,"height":32,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

+ int countTestCases()\n

+ void run(TestResult)

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":36,"magnitude":1},{"id":37,"magnitude":-1},{"id":39,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":39,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":37,"magnitude":1},{"id":39,"magnitude":1},{"id":42,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":32,"y":670,"rotation":0,"id":113,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":224.00000000000003,"height":150,"lockAspectRatio":false,"lockShape":false,"order":57,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":114,"uid":null,"width":224.00000000000003,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":115,"uid":null,"width":224.00000000000003,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

BaseTestRunner

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":115,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":116,"uid":null,"width":224.00000000000003,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":117,"uid":null,"width":224.00000000000003,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":114,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":117,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":22,"rotation":0,"id":118,"uid":null,"width":224.00000000000003,"height":128,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":119,"uid":null,"width":224.00000000000003,"height":46,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

+ Test getTest(String suiteClassName)\n

# Class loadSuiteClass(String suiteClassName)

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":113,"magnitude":1},{"id":114,"magnitude":-1},{"id":116,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":116,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":114,"magnitude":1},{"id":116,"magnitude":1},{"id":119,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":29,"y":860,"rotation":0,"id":129,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":229.99999999999997,"height":152,"lockAspectRatio":false,"lockShape":false,"order":65,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":130,"uid":null,"width":229.99999999999997,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":131,"uid":null,"width":229.99999999999997,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

TestRunner

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":131,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":132,"uid":null,"width":229.99999999999997,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":133,"uid":null,"width":229.99999999999997,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":130,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":133,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":22,"rotation":0,"id":134,"uid":null,"width":229.99999999999997,"height":130,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":135,"uid":null,"width":229.99999999999997,"height":130,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

+ void addError(Test, Throwable)\n

+ void addFailure(Test, AssertionFailedError)\n

+ void endTest(Test)\n

+ void startTest(Test)\n

+ void static main(String args[])\n

# TestResult start(String args[])\n

+ TestResult doRun(Test)\n

........

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":129,"magnitude":1},{"id":130,"magnitude":-1},{"id":132,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":132,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":130,"magnitude":1},{"id":132,"magnitude":1},{"id":135,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":860,"y":287,"rotation":0,"id":144,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":190,"height":112.46391544024681,"lockAspectRatio":false,"lockShape":false,"order":73,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":145,"uid":null,"width":190,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":146,"uid":null,"width":190,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

TestDecorator

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":146,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":147,"uid":null,"width":190,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":148,"uid":null,"width":190,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

# Test

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":145,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":148,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":36,"rotation":0,"id":149,"uid":null,"width":190,"height":76.46391544024681,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":150,"uid":null,"width":190,"height":46,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

+ void basicRun(TestResult)\n

+ void run(TestResult)\n

+ int countTestCases()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":144,"magnitude":1},{"id":145,"magnitude":-1},{"id":147,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":147,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":145,"magnitude":1},{"id":147,"magnitude":1},{"id":150,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":885,"y":458,"rotation":0,"id":151,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":140,"height":61,"lockAspectRatio":false,"lockShape":false,"order":80,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":152,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":153,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

RepeatedTest

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":153,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":154,"uid":null,"width":140,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":155,"uid":null,"width":140,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":152,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":155,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":22,"rotation":0,"id":156,"uid":null,"width":140,"height":39,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":157,"uid":null,"width":140,"height":32,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

+ void run(TestResult)\n

+ int countTestCases()\n

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":151,"magnitude":1},{"id":152,"magnitude":-1},{"id":154,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":154,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":152,"magnitude":1},{"id":154,"magnitude":1},{"id":157,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":3,"y":287,"rotation":0,"id":168,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":140,"height":61,"lockAspectRatio":false,"lockShape":false,"order":97,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":169,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":170,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

AssertionFailedError

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":170,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":171,"uid":null,"width":140,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":172,"uid":null,"width":140,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":169,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":172,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":22,"rotation":0,"id":173,"uid":null,"width":140,"height":39,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":174,"uid":null,"width":140,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":168,"magnitude":1},{"id":169,"magnitude":-1},{"id":171,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":171,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":169,"magnitude":1},{"id":171,"magnitude":1},{"id":174,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]}],"background":"#FFFFFF","width":1270,"height":1014,"maxWidth":5000,"maxHeight":5000,"nodeIndex":177,"autoFit":true,"exportBorder":false,"gridOn":true,"snapToGrid":true,"drawingGuidesOn":true,"pageBreaksOn":false,"printGridOn":false,"printPaper":"LETTER","printShrinkToFit":false,"printPortrait":true,"shapeStyles":{},"lineStyles":{},"textStyles":{},"themeData":null}} \ No newline at end of file diff --git "a/students/315863321/uml/JUnit4\346\227\266\345\272\217\345\233\276.gliffy" "b/students/315863321/uml/JUnit4\346\227\266\345\272\217\345\233\276.gliffy" new file mode 100644 index 0000000000..210f03933c --- /dev/null +++ "b/students/315863321/uml/JUnit4\346\227\266\345\272\217\345\233\276.gliffy" @@ -0,0 +1 @@ +{"contentType":"application/gliffy+json","version":"1.1","metadata":{"title":"untitled","revision":0,"exportBorder":false},"embeddedResources":{"index":0,"resources":[]},"stage":{"objects":[{"x":213,"y":2513,"rotation":0,"id":268,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":131,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-13.017697729161,0],[100,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":409.99999999999994,"y":2420,"rotation":0,"id":261,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":40,"lockAspectRatio":false,"lockShape":false,"order":127,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":404,"y":2373.3333333333335,"rotation":0,"id":259,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":125,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[374.66666666666663,-8],[83.33333333333331,-8],[83.33333333333331,-8],[-208,-8]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":849.3333333333334,"y":2422.6666666666665,"rotation":0,"id":258,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":124,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[129.33333333333326,-53.33333333333303],[39.33333333333326,-53.33333333333303],[39.33333333333326,-53.33333333333303],[-50.66666666666674,-53.33333333333303]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":981.5,"y":2319,"rotation":0,"id":257,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":47.703125,"lockAspectRatio":false,"lockShape":false,"order":123,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":810.6666666666666,"y":2290.6666666666665,"rotation":0,"id":255,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":121,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-2.674508976812035,0],[110.6746985037181,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":216,"y":2262.6666666666665,"rotation":0,"id":249,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":116,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-10.698790518335016,0],[556.014116670961,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":468,"y":2252,"rotation":0,"id":248,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":115,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[308,-28],[24.666666666666686,-28],[24.666666666666686,-29.333333333333485],[-258.66666666666663,-29.333333333333485]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":781.5,"y":2180,"rotation":0,"id":247,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":186.875,"lockAspectRatio":false,"lockShape":false,"order":114,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":266.6666666666667,"y":2056,"rotation":0,"id":245,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":112,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[133.33333333333331,-24],[34.66666666666663,-24],[34.66666666666663,-24],[-64.00000000000003,-24]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":237.33333333333334,"y":2141.3333333333335,"rotation":0,"id":244,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":111,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-33.439957367432555,0],[488.001704678407,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":208,"y":2005.3333333333333,"rotation":0,"id":242,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":109,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-6.6749996745045905,0],[198.66666666666669,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":410,"y":2003,"rotation":0,"id":241,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":30,"lockAspectRatio":false,"lockShape":false,"order":108,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":445.3333333333333,"y":1994.6666666666667,"rotation":0,"id":237,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":107,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[138.66666666666669,-45.333333333333485],[-52.66666666666663,-45.333333333333485],[-52.66666666666663,-45.333333333333485],[-243.99999999999997,-45.333333333333485]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":591.5,"y":1900,"rotation":0,"id":236,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":50,"lockAspectRatio":false,"lockShape":false,"order":106,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":206.66666666666666,"y":1869.3333333333333,"rotation":0,"id":234,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":104,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,0],[334.6693226986238,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":297.3333333333333,"y":1800,"rotation":0,"id":233,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":103,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[105.33333333333337,-26.666666666666742],[7.333333333333371,-26.666666666666742],[7.333333333333371,-26.666666666666742],[-90.66666666666666,-26.666666666666742]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":410,"y":1725,"rotation":0,"id":232,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":50,"lockAspectRatio":false,"lockShape":false,"order":102,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":181.5,"y":1690,"rotation":0,"id":230,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":843.125,"lockAspectRatio":false,"lockShape":false,"order":100,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":225.33333333333334,"y":1698.6666666666667,"rotation":0,"id":229,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":99,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-18.734063258096995,0],[133.35671298164235,2.2737367544323206e-13]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":870,"y":1220,"rotation":0,"id":207,"uid":"com.gliffy.shape.uml.uml_v1.default.self_message","width":45,"height":23,"lockAspectRatio":false,"lockShape":false,"order":78,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.self_message.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#000000","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[],"linkMap":[]},{"x":1193,"y":1125,"rotation":0,"id":205,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":76,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[193,55],[76.5,55],[76.5,55],[-40,55]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":1409,"y":1130,"rotation":0,"id":202,"uid":"com.gliffy.shape.uml.uml_v1.default.self_message","width":45,"height":23,"lockAspectRatio":false,"lockShape":false,"order":74,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.self_message.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#000000","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[],"linkMap":[]},{"x":1409,"y":1080,"rotation":0,"id":199,"uid":"com.gliffy.shape.uml.uml_v1.default.self_message","width":45,"height":23,"lockAspectRatio":false,"lockShape":false,"order":72,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.self_message.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#000000","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[],"linkMap":[]},{"x":1409,"y":1020,"rotation":0,"id":196,"uid":"com.gliffy.shape.uml.uml_v1.default.self_message","width":45,"height":23,"lockAspectRatio":false,"lockShape":false,"order":70,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.self_message.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#000000","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[],"linkMap":[]},{"x":1409,"y":963.2660187604192,"rotation":0,"id":193,"uid":"com.gliffy.shape.uml.uml_v1.default.self_message","width":45,"height":23,"lockAspectRatio":false,"lockShape":false,"order":68,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.self_message.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#000000","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[],"linkMap":[]},{"x":1237,"y":868,"rotation":0,"id":192,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":67,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[149,2],[31,2],[31,1],[-87,1]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":1621.5,"y":830,"rotation":0,"id":191,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":40,"lockAspectRatio":false,"lockShape":false,"order":66,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":1444,"y":946,"rotation":0,"id":190,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":65,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[177,-77],[75,-77],[75,-76],[-27,-76]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":1553,"y":742,"rotation":0,"id":189,"uid":"com.gliffy.shape.uml.uml_v1.default.association","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":64,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-47,37],[28,-37.45227278524749]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":175,"px":0,"py":0.7071067811865475}}},"linkMap":[]},{"x":1425,"y":801,"rotation":0,"id":186,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":62,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-13.0333282076042,1.1368683772161603e-13],[122.00409829181967,1.1368683772161603e-13]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":1581,"y":660,"rotation":0,"id":175,"uid":"com.gliffy.shape.uml.uml_v1.default.note","width":100,"height":63,"lockAspectRatio":false,"lockShape":false,"order":56,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.note.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2,"y":0,"rotation":0,"id":188,"uid":null,"width":96,"height":42,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

传入了Before.class和After.class

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":1166,"y":962,"rotation":0,"id":166,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":54,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-11.004504413109316,0],[220.0021644498181,2.2737367544323206e-13]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":1390,"y":963.2660187604192,"rotation":0,"id":165,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":220.00000000000003,"lockAspectRatio":false,"lockShape":false,"order":53,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":1390,"y":790,"rotation":0,"id":163,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":80,"lockAspectRatio":false,"lockShape":false,"order":52,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":1190,"y":755,"rotation":0,"id":161,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":50,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-38.014491992689045,0],[147,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":1150.5,"y":687,"rotation":0,"id":156,"uid":"com.gliffy.shape.uml.uml_v1.default.self_message","width":45,"height":23,"lockAspectRatio":false,"lockShape":false,"order":48,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.self_message.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#000000","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[],"linkMap":[]},{"x":876,"y":665,"rotation":0,"id":150,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":42,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-6,0],[251.00796800101784,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":873,"y":609,"rotation":0,"id":147,"uid":"com.gliffy.shape.uml.uml_v1.default.self_message","width":45,"height":23,"lockAspectRatio":false,"lockShape":false,"order":40,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.self_message.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#000000","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[],"linkMap":[]},{"x":1131.5,"y":663.2660187604191,"rotation":0,"id":145,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":520,"lockAspectRatio":false,"lockShape":false,"order":39,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":869,"y":547,"rotation":0,"id":135,"uid":"com.gliffy.shape.uml.uml_v1.default.self_message","width":45,"height":23,"lockAspectRatio":false,"lockShape":false,"order":37,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.self_message.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#000000","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[],"linkMap":[]},{"x":643,"y":534,"rotation":0,"id":133,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":35,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-29.034879005639368,0],[204,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":850,"y":520,"rotation":0,"id":131,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":750,"lockAspectRatio":false,"lockShape":false,"order":34,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":680,"y":563,"rotation":0,"id":130,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":33,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[165,-87],[48.5,-87],[48.5,-87],[-68,-87]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":850,"y":460,"rotation":0,"id":129,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":20,"lockAspectRatio":false,"lockShape":false,"order":32,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":663,"y":359,"rotation":0,"id":126,"uid":"com.gliffy.shape.uml.uml_v1.default.association","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":31,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[22,19],[87,-54.45227278524749]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":124,"px":0,"py":0.7071067811865475}}},"linkMap":[]},{"x":750,"y":260,"rotation":0,"id":124,"uid":"com.gliffy.shape.uml.uml_v1.default.note","width":185.5,"height":63,"lockAspectRatio":false,"lockShape":false,"order":29,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.note.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":3.7100000000000004,"y":0,"rotation":0,"id":132,"uid":null,"width":178.08,"height":42,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

1、把BeforeClass.class 和AfterClass.class传入\n

2、重写了runUnprotected方法\n

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":616,"y":420,"rotation":0,"id":122,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":27,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,0],[162.00308639035245,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":388,"y":403,"rotation":0,"id":111,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":17,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-5,0],[204.03864282987297,-5.684341886080802e-14]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":170,"y":365,"rotation":0,"id":109,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":16,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

run(RunNotifier)

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":188,"y":383,"rotation":0,"id":108,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":15,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-15.004347743900524,-5.684341886080802e-14],[168,-5.684341886080802e-14]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":591.5,"y":400,"rotation":0,"id":107,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":870,"lockAspectRatio":false,"lockShape":false,"order":14,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":361.5,"y":379,"rotation":0,"id":106,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":891,"lockAspectRatio":false,"lockShape":false,"order":13,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":151.5,"y":340,"rotation":0,"id":105,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":930,"lockAspectRatio":false,"lockShape":false,"order":12,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":100,"y":130,"rotation":0,"id":93,"uid":"com.gliffy.shape.uml.uml_v1.default.object_timeline","width":120,"height":1250,"lockAspectRatio":false,"lockShape":false,"order":0,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":94,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":95,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

:JUnitCore

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":95,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":96,"uid":null,"width":120,"height":1232,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.object_timeline.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":null,"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":93,"magnitude":1},{"id":94,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":94,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":94,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":310,"y":130,"rotation":0,"id":97,"uid":"com.gliffy.shape.uml.uml_v1.default.object_timeline","width":120,"height":1250,"lockAspectRatio":false,"lockShape":false,"order":4,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":98,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":99,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

:CompositeRunner

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":99,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":100,"uid":null,"width":120,"height":1232,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.object_timeline.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":null,"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":97,"magnitude":1},{"id":98,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":98,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":98,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":540,"y":130,"rotation":0,"id":101,"uid":"com.gliffy.shape.uml.uml_v1.default.object_timeline","width":120,"height":1257,"lockAspectRatio":false,"lockShape":false,"order":8,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":102,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":103,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

:TestClassRunner

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":103,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":104,"uid":null,"width":120,"height":1239,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.object_timeline.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":null,"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":101,"magnitude":1},{"id":102,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":102,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":102,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":390,"y":379,"rotation":0,"id":112,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":18,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

run(RunNotifier)

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":783.5,"y":407,"rotation":0,"id":114,"uid":"com.gliffy.shape.uml.uml_v1.default.object_timeline","width":150,"height":959.9999999999999,"lockAspectRatio":false,"lockShape":false,"order":19,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":115,"uid":null,"width":150,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":116,"uid":null,"width":150,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

:BeforeAndAfterRunner

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":116,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":117,"uid":null,"width":150,"height":941.9999999999999,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.object_timeline.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":null,"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":114,"magnitude":1},{"id":115,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":115,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":115,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":1060,"y":460,"rotation":0,"id":118,"uid":"com.gliffy.shape.uml.uml_v1.default.object_timeline","width":160,"height":894.2660187604192,"lockAspectRatio":false,"lockShape":false,"order":23,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":119,"uid":null,"width":160,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":120,"uid":null,"width":160,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

:TestClassMethodsRunner

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":120,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":121,"uid":null,"width":160,"height":876.2660187604192,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.object_timeline.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":null,"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":118,"magnitude":1},{"id":119,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":119,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":119,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":610.5,"y":393,"rotation":0,"id":123,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":28,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

new

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":630,"y":506,"rotation":0,"id":134,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":36,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

runProtected()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":869,"y":540,"rotation":0,"id":137,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":38,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

runBefores()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":891.5,"y":609,"rotation":0,"id":149,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":41,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

runUnprotected()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":916,"y":643,"rotation":0,"id":151,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":43,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

run(RunNotifier)

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":1340,"y":745.2660187604192,"rotation":0,"id":152,"uid":"com.gliffy.shape.uml.uml_v1.default.object_timeline","width":120,"height":609,"lockAspectRatio":false,"lockShape":false,"order":44,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":153,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":154,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

:TestMethodRunner

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":154,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":155,"uid":null,"width":120,"height":591,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.object_timeline.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":null,"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":152,"magnitude":1},{"id":153,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":153,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":153,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":1173,"y":691.5,"rotation":0,"id":158,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":49,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

invokeTestMethod()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":1161,"y":733,"rotation":0,"id":162,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":51,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

new

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":1173,"y":949.2660187604192,"rotation":0,"id":170,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":55,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

run()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":1550,"y":791.6330093802096,"rotation":0,"id":182,"uid":"com.gliffy.shape.uml.uml_v1.default.object_timeline","width":160,"height":622,"lockAspectRatio":false,"lockShape":false,"order":58,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":183,"uid":null,"width":160,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":184,"uid":null,"width":160,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

:BeforeAndAfterRunner

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":184,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":185,"uid":null,"width":160,"height":604,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.object_timeline.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":null,"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":182,"magnitude":1},{"id":183,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":183,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":183,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":1414,"y":783,"rotation":0,"id":187,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":63,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

super()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":1416,"y":960.7660187604192,"rotation":0,"id":195,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":69,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

runProtected()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":1418,"y":1020,"rotation":0,"id":198,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":71,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

runBefores

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":1420,"y":1080,"rotation":0,"id":201,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":73,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

runUnprotected()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":1414,"y":1129,"rotation":0,"id":204,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":75,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

runAfters

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":923,"y":1124,"rotation":0,"id":206,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":77,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[206,55],[79,55],[79,55],[-48,55]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":870,"y":1220,"rotation":0,"id":209,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":79,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

runAfters

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":668,"y":1155,"rotation":0,"id":210,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":80,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[179,114],[59.5,114],[59.5,114],[-60,114]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":440,"y":1153,"rotation":0,"id":211,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":81,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[151,114],[45.5,114],[45.5,114],[-60,114]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":189,"y":1224,"rotation":0,"id":212,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":82,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[165,46],[73.5,46],[73.5,46],[-18,46]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":130,"y":1620,"rotation":0,"id":213,"uid":"com.gliffy.shape.uml.uml_v1.default.object_timeline","width":120,"height":971,"lockAspectRatio":false,"lockShape":false,"order":83,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":214,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":215,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

:JUnitCore

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":215,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":216,"uid":null,"width":120,"height":953,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.object_timeline.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":null,"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":213,"magnitude":1},{"id":214,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":214,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":214,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":360,"y":1690,"rotation":0,"id":217,"uid":"com.gliffy.shape.uml.uml_v1.default.object_timeline","width":120,"height":840,"lockAspectRatio":false,"lockShape":false,"order":87,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":218,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":219,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

:RunNotifier

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":219,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":220,"uid":null,"width":120,"height":822,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.object_timeline.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":null,"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":217,"magnitude":1},{"id":218,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":218,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":218,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":730,"y":2130,"rotation":0,"id":221,"uid":"com.gliffy.shape.uml.uml_v1.default.object_timeline","width":120,"height":409.99999999999994,"lockAspectRatio":false,"lockShape":false,"order":91,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":222,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":223,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

:Result

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":223,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":224,"uid":null,"width":120,"height":391.99999999999994,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.object_timeline.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":null,"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":221,"magnitude":1},{"id":222,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":222,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":222,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":540,"y":1870,"rotation":0,"id":225,"uid":"com.gliffy.shape.uml.uml_v1.default.object_timeline","width":120,"height":589.9999999999999,"lockAspectRatio":false,"lockShape":false,"order":95,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":226,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":227,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

:TextListener

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":227,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":228,"uid":null,"width":120,"height":571.9999999999999,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.object_timeline.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":null,"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":225,"magnitude":1},{"id":226,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":226,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":226,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":200.5,"y":1675,"rotation":0,"id":231,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":101,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

new

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":252,"y":1856.0000000000002,"rotation":0,"id":235,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":105,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

new

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":234.33333333333331,"y":1981,"rotation":0,"id":243,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":110,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

addListener

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":255.66666666666669,"y":2118.3333333333335,"rotation":0,"id":246,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":113,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

new

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":930,"y":2282.5,"rotation":0,"id":250,"uid":"com.gliffy.shape.uml.uml_v1.default.object_timeline","width":120,"height":273,"lockAspectRatio":false,"lockShape":false,"order":117,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":251,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":252,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

Listener

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":252,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":253,"uid":null,"width":120,"height":255,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.object_timeline.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":null,"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":250,"magnitude":1},{"id":251,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":251,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":251,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":791.0000000000001,"y":2262.5,"rotation":0,"id":256,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":20,"lockAspectRatio":false,"lockShape":false,"order":122,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

new

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":234.33333333333331,"y":2241,"rotation":0,"id":260,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":126,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

createListener

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":216.66666666666669,"y":2430,"rotation":0,"id":262,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":128,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-12.669117632335258,0],[191.33333333333331,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":245,"y":2407.6666666666665,"rotation":0,"id":263,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":129,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

addListener

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":268.6666666666667,"y":2483.3333333333335,"rotation":0,"id":264,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":130,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[133.33333333333331,-24],[33.833333333333314,-24],[33.833333333333314,-24.333333333333485],[-65.66666666666669,-24.333333333333485]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":200,"y":2490,"rotation":0,"id":269,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":132,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

run(RunNotifier)

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]}],"background":"#FFFFFF","width":1712,"height":2591,"maxWidth":5000,"maxHeight":5000,"nodeIndex":270,"autoFit":true,"exportBorder":false,"gridOn":false,"snapToGrid":true,"drawingGuidesOn":true,"pageBreaksOn":false,"printGridOn":false,"printPaper":"LETTER","printShrinkToFit":false,"printPortrait":true,"shapeStyles":{},"lineStyles":{},"textStyles":{},"themeData":null}} \ No newline at end of file diff --git "a/students/315863321/uml/Junit4\347\261\273\345\233\276.gliffy" "b/students/315863321/uml/Junit4\347\261\273\345\233\276.gliffy" new file mode 100644 index 0000000000..e4454a6826 --- /dev/null +++ "b/students/315863321/uml/Junit4\347\261\273\345\233\276.gliffy" @@ -0,0 +1 @@ +{"contentType":"application/gliffy+json","version":"1.1","metadata":{"title":"untitled","revision":0,"exportBorder":false},"embeddedResources":{"index":0,"resources":[]},"stage":{"objects":[{"x":427,"y":720,"rotation":0,"id":218,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":218,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-57,-5],[235,14]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":141,"px":0,"py":0.5}}},"linkMap":[]},{"x":488,"y":704,"rotation":0,"id":217,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":217,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-62.08150064683048,-109.35575679172052],[174,30]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":141,"px":0,"py":0.5}}},"linkMap":[]},{"x":874,"y":472,"rotation":0,"id":216,"uid":"com.gliffy.shape.uml.uml_v1.default.generalization","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":216,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":4,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-3,40.5],[-3,-8.25],[-213,-8.25],[-213,-57]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":209,"px":0.5,"py":0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":169,"px":0.5,"py":1}}},"linkMap":[]},{"x":801,"y":512.5,"rotation":0,"id":209,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":140,"height":75,"lockAspectRatio":false,"lockShape":false,"order":158,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":210,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":211,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

Parameterized

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":211,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":212,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":213,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

Attribute

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":210,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":213,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":36,"rotation":0,"id":214,"uid":null,"width":140,"height":39,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":215,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

Method

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":209,"magnitude":1},{"id":210,"magnitude":-1},{"id":212,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":212,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":210,"magnitude":1},{"id":212,"magnitude":1},{"id":215,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":653,"y":437,"rotation":0,"id":208,"uid":"com.gliffy.shape.uml.uml_v1.default.generalization","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":151,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":4,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-50.125,75.5],[-50.125,26.75],[8,26.75],[8,-22]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":201,"px":0.5,"py":0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":169,"px":0.5,"py":1}}},"linkMap":[]},{"x":474.75,"y":512.5,"rotation":0,"id":201,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":256.25,"height":96,"lockAspectRatio":false,"lockShape":false,"order":144,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":202,"uid":null,"width":256.25,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":203,"uid":null,"width":256.25,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

Suite\n

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":203,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":204,"uid":null,"width":256.25,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":205,"uid":null,"width":256.25,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

Attribute

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":202,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":205,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":36,"rotation":0,"id":206,"uid":null,"width":256.25,"height":60,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":207,"uid":null,"width":256.25,"height":32,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

\n

- static Class[] getAnnotatedClasses(Class)

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":201,"magnitude":1},{"id":202,"magnitude":-1},{"id":204,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":204,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":202,"magnitude":1},{"id":204,"magnitude":1},{"id":207,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":144.00000000000003,"y":564,"rotation":0,"id":200,"uid":"com.gliffy.shape.uml.uml_v1.default.dependency","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":143,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":6,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-20.71978021978022,-131.65109890109898],[-20.71978021978022,168.58073580374355],[56.99999999999997,168.58073580374355]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":156,"px":0,"py":0.7071067811865475}}},"linkMap":[]},{"x":533,"y":440,"rotation":0,"id":197,"uid":"com.gliffy.shape.uml.uml_v1.default.aggregation","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":142,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":1,"endArrow":5,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-43.02468759581859,-75],[-16.016458397212432,-75],[10.99177080139384,-75],[38,-75]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":176,"px":1,"py":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":169,"px":0,"py":0.5}}},"linkMap":[]},{"x":324,"y":231,"rotation":0,"id":196,"uid":"com.gliffy.shape.uml.uml_v1.default.implements","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":141,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":4,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-34,74],[-34,21.5],[463.5,21.5],[463.5,-31]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":176,"px":0.5,"py":0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":95,"px":0.5,"py":1}}},"linkMap":[]},{"x":638,"y":225,"rotation":0,"id":194,"uid":"com.gliffy.shape.uml.uml_v1.default.aggregation","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":140,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":1,"endArrow":5,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[256,-70],[418,-70],[418,140],[378,140]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":95,"px":1,"py":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":102,"px":1,"py":0.5}}},"linkMap":[]},{"x":543,"y":267,"rotation":0,"id":193,"uid":"com.gliffy.shape.uml.uml_v1.default.implements","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":139,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":4,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[365.5,38],[365.5,-14.5],[244.5,-14.5],[244.5,-67]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":102,"px":0.5,"py":0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":95,"px":0.5,"py":1}}},"linkMap":[]},{"x":363,"y":323,"rotation":0,"id":191,"uid":"com.gliffy.shape.uml.uml_v1.default.implements","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":138,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,2.0","startArrow":0,"endArrow":4,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[298,-8],[298,-70.5],[424.5,-70.5],[424.5,-123]],"lockSegments":{"1":true}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":169,"px":0.5,"py":0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":95,"px":0.5,"py":1}}},"linkMap":[]},{"x":89.99999999999997,"y":305,"rotation":0,"id":176,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":400.00000000000006,"height":124,"lockAspectRatio":false,"lockShape":false,"order":131,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":177,"uid":null,"width":400.00000000000006,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":178,"uid":null,"width":400.00000000000006,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

TestClassMethodsRunner

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":178,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":179,"uid":null,"width":400.00000000000006,"height":32,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":180,"uid":null,"width":400.00000000000006,"height":32,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

- List<Method> fTestMethods\n

- Class<?> fTestClass

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":177,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":180,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":50,"rotation":0,"id":181,"uid":null,"width":400.00000000000006,"height":74,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":182,"uid":null,"width":400.00000000000006,"height":74,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

+ void run(RunNotifier notifier)\n

# void invokeTestMethod(Method, RunNotifier)\n

# Object createTest()\n

# TestMethodRunner createMethodRunner(Object, Method, RunNotifier)\n

+ Description getDescription()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":176,"magnitude":1},{"id":177,"magnitude":-1},{"id":179,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":179,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":177,"magnitude":1},{"id":179,"magnitude":1},{"id":182,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":571,"y":315,"rotation":0,"id":169,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":180,"height":100,"lockAspectRatio":false,"lockShape":false,"order":124,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":170,"uid":null,"width":180,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":171,"uid":null,"width":180,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

TestClassRunner

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":171,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":172,"uid":null,"width":180,"height":32,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":173,"uid":null,"width":180,"height":32,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

- Class<?> fTestClass\n

# Runner fEnclosedRunner

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":170,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":173,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":50,"rotation":0,"id":174,"uid":null,"width":180,"height":50,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":175,"uid":null,"width":180,"height":32,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

+ void run(RunNotifier notifier)\n

+ Description getDescription()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":169,"magnitude":1},{"id":170,"magnitude":-1},{"id":172,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":172,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":170,"magnitude":1},{"id":172,"magnitude":1},{"id":175,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":627.5,"y":802,"rotation":0,"id":163,"uid":"com.gliffy.shape.uml.uml_v1.default.generalization","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":123,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":4,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-341.5,-167],[-341.5,-180.5],[-341.5,-194],[-341.5,-207.5]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":156,"px":0.5,"py":0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":149,"px":0.5,"py":1}}},"linkMap":[]},{"x":201,"y":635,"rotation":0,"id":156,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":170,"height":138,"lockAspectRatio":false,"lockShape":false,"order":116,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":157,"uid":null,"width":170,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":158,"uid":null,"width":170,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

TestMethodRunner

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":158,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":159,"uid":null,"width":170,"height":60,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":160,"uid":null,"width":170,"height":60,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

- Object fTest\n

- Method\n

- RunNotifier \n

- TestIntrospector

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":157,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":160,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":78,"rotation":0,"id":161,"uid":null,"width":170,"height":60,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":162,"uid":null,"width":170,"height":60,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

+ void run()\n

· void runMethod()\n

# void runUnprotected()\n

# void executeMethodBody()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":156,"magnitude":1},{"id":157,"magnitude":-1},{"id":159,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":159,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":157,"magnitude":1},{"id":159,"magnitude":1},{"id":162,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":146,"y":442.5,"rotation":0,"id":149,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":280,"height":152,"lockAspectRatio":false,"lockShape":false,"order":109,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":150,"uid":null,"width":280,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":151,"uid":null,"width":280,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

BeforeAndAfterRunner

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":151,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":152,"uid":null,"width":280,"height":60,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":153,"uid":null,"width":280,"height":60,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

- Class<? extends Annotation> fBeforeAnnotation\n

- Class<? extends Annotation> fAfterAnnotation\n

- TestIntrospector\n

- Object fTest

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":150,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":153,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":78,"rotation":0,"id":154,"uid":null,"width":280,"height":74,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":155,"uid":null,"width":280,"height":74,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

+ void runProtected()\n

# abstract void runUnprotected()\n

- void runAfters()\n

- void runBefores()\n

+ abstract void addFailure(Throwable)

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":149,"magnitude":1},{"id":150,"magnitude":-1},{"id":152,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":152,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":150,"magnitude":1},{"id":152,"magnitude":1},{"id":155,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":662,"y":693,"rotation":0,"id":141,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":404,"height":82,"lockAspectRatio":false,"lockShape":false,"order":102,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":142,"uid":null,"width":404,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":143,"uid":null,"width":404,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

TestIntrospector

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":143,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":144,"uid":null,"width":404,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":145,"uid":null,"width":404,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

- Class< ?> fTestClass

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":142,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":145,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":36,"rotation":0,"id":146,"uid":null,"width":404,"height":46,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":147,"uid":null,"width":404,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

+ List<Method> getTestMethods(Class<? extends Annotation>)

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":141,"magnitude":1},{"id":142,"magnitude":-1},{"id":144,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":144,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":142,"magnitude":1},{"id":144,"magnitude":1},{"id":147,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":801,"y":305,"rotation":0,"id":102,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":214.99999999999997,"height":120,"lockAspectRatio":false,"lockShape":false,"order":95,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":103,"uid":null,"width":214.99999999999997,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":104,"uid":null,"width":214.99999999999997,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

CompositeRunner

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":104,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":105,"uid":null,"width":214.99999999999997,"height":32,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":106,"uid":null,"width":214.99999999999997,"height":32,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

- List<Runner> fRunners\n

- String fName

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":103,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":106,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":50,"rotation":0,"id":107,"uid":null,"width":214.99999999999997,"height":70,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":108,"uid":null,"width":214.99999999999997,"height":60,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

+ void run(RunNotifier notifier)\n

+ void add(Runner)\n

+ void addAll(List<? extends Runner>)\n

+ Description getDescription()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":102,"magnitude":1},{"id":103,"magnitude":-1},{"id":105,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":105,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":103,"magnitude":1},{"id":105,"magnitude":1},{"id":108,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":681,"y":110,"rotation":0,"id":95,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":213,"height":90,"lockAspectRatio":false,"lockShape":false,"order":88,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":96,"uid":null,"width":213,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":97,"uid":null,"width":213,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

Runner

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":97,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":98,"uid":null,"width":213,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":99,"uid":null,"width":213,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

Attribute

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":96,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":99,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":36,"rotation":0,"id":100,"uid":null,"width":213,"height":54,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":101,"uid":null,"width":213,"height":32,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

+ abstract void run(RunNotifier notifier)\n

+ abstract Description getDescription()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":95,"magnitude":1},{"id":96,"magnitude":-1},{"id":98,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":98,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":96,"magnitude":1},{"id":98,"magnitude":1},{"id":101,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]}],"background":"#FFFFFF","width":1068,"height":775,"maxWidth":5000,"maxHeight":5000,"nodeIndex":223,"autoFit":true,"exportBorder":false,"gridOn":true,"snapToGrid":true,"drawingGuidesOn":true,"pageBreaksOn":false,"printGridOn":false,"printPaper":"LETTER","printShrinkToFit":false,"printPortrait":true,"shapeStyles":{},"lineStyles":{},"textStyles":{},"themeData":null}} \ No newline at end of file diff --git "a/students/315863321/uml/\350\264\255\347\211\251\347\275\221\347\253\231\347\224\250\344\276\213\345\233\276.gliffy" "b/students/315863321/uml/\350\264\255\347\211\251\347\275\221\347\253\231\347\224\250\344\276\213\345\233\276.gliffy" new file mode 100644 index 0000000000..18e02de5b7 --- /dev/null +++ "b/students/315863321/uml/\350\264\255\347\211\251\347\275\221\347\253\231\347\224\250\344\276\213\345\233\276.gliffy" @@ -0,0 +1 @@ +{"contentType":"application/gliffy+json","version":"1.1","metadata":{"title":"untitled","revision":0,"exportBorder":false},"embeddedResources":{"index":0,"resources":[]},"stage":{"objects":[{"x":610,"y":359,"rotation":0,"id":33,"uid":"com.gliffy.shape.uml.uml_v1.default.use_case","width":115,"height":58,"lockAspectRatio":true,"lockShape":false,"order":25,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2,"y":0,"rotation":0,"id":35,"uid":null,"width":111,"height":14,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

下订单

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":613,"y":210,"rotation":0,"id":29,"uid":"com.gliffy.shape.uml.uml_v1.default.generalization","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":21,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"4.0,4.0","startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[54.5,49],[54.5,22],[54.5,-5],[54.5,-32]],"lockSegments":{}}},"children":[{"x":0,"y":0,"rotation":0,"id":30,"uid":null,"width":64,"height":14,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"both","vposition":"none","hposition":"none","html":"

<<extend>>

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":23,"px":0.5,"py":0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":21,"px":0.5,"py":1}}},"linkMap":[]},{"x":468,"y":187,"rotation":0,"id":25,"uid":"com.gliffy.shape.uml.uml_v1.default.generalization","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":19,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"4.0,4.0","startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[142,-38],[77,-38],[12,-38],[-53,-38]],"lockSegments":{}}},"children":[{"x":0,"y":0,"rotation":0,"id":26,"uid":null,"width":64,"height":14,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"both","vposition":"none","hposition":"none","html":"

<<extend>>

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":21,"px":0,"py":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":2,"px":1,"py":0.5}}},"linkMap":[]},{"x":610,"y":259,"rotation":0,"id":23,"uid":"com.gliffy.shape.uml.uml_v1.default.use_case","width":115,"height":58,"lockAspectRatio":true,"lockShape":false,"order":17,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2,"y":0,"rotation":0,"id":28,"uid":null,"width":111,"height":14,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

加入购物车

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":610,"y":120,"rotation":0,"id":21,"uid":"com.gliffy.shape.uml.uml_v1.default.use_case","width":115,"height":58,"lockAspectRatio":true,"lockShape":false,"order":15,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2,"y":0,"rotation":0,"id":27,"uid":null,"width":111,"height":14,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

查看产品详情

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":306,"y":437,"rotation":0,"id":19,"uid":"com.gliffy.shape.uml.uml_v1.default.generalization","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":13,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"4.0,4.0","startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[51.5,33],[51.5,5.666666666666686],[51.5,-21.666666666666686],[51.5,-49]],"lockSegments":{}}},"children":[{"x":0,"y":0,"rotation":0,"id":20,"uid":null,"width":64,"height":14,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"both","vposition":"none","hposition":"none","html":"

<<extend>>

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":8,"px":0.5,"py":0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":6,"px":0.5,"py":1}}},"linkMap":[]},{"x":171,"y":448,"rotation":0,"id":18,"uid":"com.gliffy.shape.uml.uml_v1.default.association","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":12,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-9,-100],[129,51]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":8,"px":0,"py":0.5}}},"linkMap":[]},{"x":166,"y":321,"rotation":0,"id":17,"uid":"com.gliffy.shape.uml.uml_v1.default.association","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":11,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,0],[134,38]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":6,"px":0,"py":0.5}}},"linkMap":[]},{"x":177,"y":267,"rotation":0,"id":16,"uid":"com.gliffy.shape.uml.uml_v1.default.association","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":10,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-0.06502346320826291,-8],[40.956651024527844,-8],[81.9783255122639,-8],[123,-8]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":4,"px":0,"py":0.5}}},"linkMap":[]},{"x":173,"y":230,"rotation":0,"id":15,"uid":"com.gliffy.shape.uml.uml_v1.default.association","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":9,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-17,7],[127,-81]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":2,"px":0,"py":0.5}}},"linkMap":[]},{"x":300,"y":470,"rotation":0,"id":8,"uid":"com.gliffy.shape.uml.uml_v1.default.use_case","width":115,"height":58,"lockAspectRatio":true,"lockShape":false,"order":7,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2,"y":0,"rotation":0,"id":13,"uid":null,"width":111,"height":14,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

注册

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":300,"y":330,"rotation":0,"id":6,"uid":"com.gliffy.shape.uml.uml_v1.default.use_case","width":115,"height":58,"lockAspectRatio":true,"lockShape":false,"order":5,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2,"y":0,"rotation":0,"id":12,"uid":null,"width":111,"height":14,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

登录

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":300,"y":230,"rotation":0,"id":4,"uid":"com.gliffy.shape.uml.uml_v1.default.use_case","width":115,"height":58,"lockAspectRatio":true,"lockShape":false,"order":3,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2,"y":0,"rotation":0,"id":11,"uid":null,"width":111,"height":14,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

显示购物车

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":300,"y":120,"rotation":0,"id":2,"uid":"com.gliffy.shape.uml.uml_v1.default.use_case","width":115,"height":58,"lockAspectRatio":true,"lockShape":false,"order":1,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2,"y":0,"rotation":0,"id":10,"uid":null,"width":111,"height":14,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

搜索产品

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":90,"y":238,"rotation":0,"id":0,"uid":"com.gliffy.shape.uml.uml_v1.default.actor","width":63,"height":100,"lockAspectRatio":true,"lockShape":false,"order":0,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.actor.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[],"linkMap":[]},{"x":453,"y":174,"rotation":0,"id":31,"uid":"com.gliffy.shape.uml.uml_v1.default.generalization","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":23,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"4.0,4.0","startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[157,114],[-38,-25]],"lockSegments":{}}},"children":[{"x":0,"y":0,"rotation":0,"id":32,"uid":null,"width":64,"height":14,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"both","vposition":"none","hposition":"none","html":"

<<extend>>

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":23,"px":0,"py":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":2,"px":1,"py":0.5}}},"linkMap":[]},{"x":478,"y":291,"rotation":0,"id":36,"uid":"com.gliffy.shape.uml.uml_v1.default.generalization","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":27,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"4.0,4.0","startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[132,97],[-63,-32]],"lockSegments":{}}},"children":[{"x":0,"y":0,"rotation":0,"id":37,"uid":null,"width":64,"height":14,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"both","vposition":"none","hposition":"none","html":"

<<extend>>

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":33,"px":0,"py":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":4,"px":1,"py":0.5}}},"linkMap":[]},{"x":446,"y":356,"rotation":0,"id":38,"uid":"com.gliffy.shape.uml.uml_v1.default.generalization","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":30,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"4.0,4.0","startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[164,32],[-31,3]],"lockSegments":{}}},"children":[{"x":0,"y":0,"rotation":0,"id":39,"uid":null,"width":66,"height":14,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"both","vposition":"none","hposition":"none","html":"

<<include>>

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":33,"px":0,"py":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":6,"px":1,"py":0.5}}},"linkMap":[]}],"background":"#FFFFFF","width":725,"height":528,"maxWidth":5000,"maxHeight":5000,"nodeIndex":40,"autoFit":true,"exportBorder":false,"gridOn":true,"snapToGrid":true,"drawingGuidesOn":true,"pageBreaksOn":false,"printGridOn":false,"printPaper":"LETTER","printShrinkToFit":false,"printPortrait":true,"shapeStyles":{},"lineStyles":{},"textStyles":{},"themeData":null}} \ No newline at end of file diff --git "a/students/315863321/uml/\351\252\260\345\255\220\346\270\270\346\210\217\346\227\266\345\272\217\345\233\276.gliffy" "b/students/315863321/uml/\351\252\260\345\255\220\346\270\270\346\210\217\346\227\266\345\272\217\345\233\276.gliffy" new file mode 100644 index 0000000000..02b057e1e7 --- /dev/null +++ "b/students/315863321/uml/\351\252\260\345\255\220\346\270\270\346\210\217\346\227\266\345\272\217\345\233\276.gliffy" @@ -0,0 +1 @@ +{"contentType":"application/gliffy+json","version":"1.1","metadata":{"title":"untitled","revision":0,"exportBorder":false},"embeddedResources":{"index":0,"resources":[]},"stage":{"objects":[{"x":585,"y":414,"rotation":0,"id":58,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":58,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

showResult

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":413,"y":430,"rotation":0,"id":57,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":57,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-3.0008912634656326,1.1368683772161603e-13],[558.0008960566282,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":228,"y":463,"rotation":0,"id":55,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":55,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":"1.0,1.0","startArrow":1,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-18.002746817932916,-1.1368683772161603e-13],[164.0274367293472,0]],"lockSegments":{}}},"children":[],"linkMap":[]},{"x":971.5,"y":425,"rotation":0,"id":53,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":30,"lockAspectRatio":false,"lockShape":false,"order":53,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":451,"y":320,"rotation":0,"id":52,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":73,"height":14,"lockAspectRatio":false,"lockShape":false,"order":52,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

checkIfWin

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":410.5,"y":320,"rotation":0,"id":50,"uid":"com.gliffy.shape.uml.uml_v1.default.self_message","width":45,"height":23,"lockAspectRatio":false,"lockShape":false,"order":50,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.self_message.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#000000","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[],"linkMap":[]},{"x":410.5,"y":211,"rotation":0,"id":48,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":48,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

v2=roll()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":791.5,"y":225,"rotation":0,"id":47,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":20,"lockAspectRatio":false,"lockShape":false,"order":47,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":444,"y":230,"rotation":0,"id":46,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":46,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-34.00373129133379,2.842170943040401e-14],[350.0013020684737,2.842170943040401e-14]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":424,"y":154,"rotation":0,"id":44,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":44,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

v1=roll()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":432,"y":170,"rotation":0,"id":43,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":43,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-22,0],[162.01086924418348,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":240,"y":169,"rotation":0,"id":42,"uid":"com.gliffy.shape.uml.uml_v1.default.message","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":42,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-29.00276236699139,0],[152.00280890398182,-2.842170943040401e-14]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":591.5,"y":168,"rotation":0,"id":39,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":24,"lockAspectRatio":false,"lockShape":false,"order":39,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":204,"y":148,"rotation":0,"id":37,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":150,"height":14,"lockAspectRatio":false,"lockShape":false,"order":37,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

play

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":391.5,"y":165,"rotation":0,"id":36,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":310,"lockAspectRatio":false,"lockShape":false,"order":36,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":191.5,"y":165,"rotation":0,"id":31,"uid":"com.gliffy.shape.uml.uml_v1.default.activation","width":19,"height":310,"lockAspectRatio":false,"lockShape":false,"order":31,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":null,"linkMap":[]},{"x":140,"y":70,"rotation":0,"id":11,"uid":"com.gliffy.shape.uml.uml_v1.default.object_timeline","width":120,"height":430,"lockAspectRatio":false,"lockShape":false,"order":0,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":12,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":13,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

:Player

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":13,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":14,"uid":null,"width":120,"height":412,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.object_timeline.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":null,"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":11,"magnitude":1},{"id":12,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":12,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":12,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":340,"y":70,"rotation":0,"id":15,"uid":"com.gliffy.shape.uml.uml_v1.default.object_timeline","width":120,"height":429.99999999999994,"lockAspectRatio":false,"lockShape":false,"order":4,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":16,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":17,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

:DiceGame

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":17,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":18,"uid":null,"width":120,"height":411.99999999999994,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.object_timeline.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":null,"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":15,"magnitude":1},{"id":16,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":16,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":16,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":540,"y":70,"rotation":0,"id":19,"uid":"com.gliffy.shape.uml.uml_v1.default.object_timeline","width":120,"height":429.99999999999994,"lockAspectRatio":false,"lockShape":false,"order":8,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":20,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":21,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

dice1:Dice

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":21,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":22,"uid":null,"width":120,"height":411.99999999999994,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.object_timeline.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":null,"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":19,"magnitude":1},{"id":20,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":20,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":20,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":740,"y":70,"rotation":0,"id":23,"uid":"com.gliffy.shape.uml.uml_v1.default.object_timeline","width":120,"height":429.99999999999994,"lockAspectRatio":false,"lockShape":false,"order":12,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":24,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":25,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

dice2:Dice

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":25,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":26,"uid":null,"width":120,"height":411.99999999999994,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.object_timeline.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":null,"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":23,"magnitude":1},{"id":24,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":24,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":24,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":920,"y":70,"rotation":0,"id":27,"uid":"com.gliffy.shape.uml.uml_v1.default.object_timeline","width":120,"height":429.99999999999994,"lockAspectRatio":false,"lockShape":false,"order":19,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":28,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":29,"uid":null,"width":120,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

:Display

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":29,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":30,"uid":null,"width":120,"height":411.99999999999994,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.object_timeline.uml_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":null,"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":27,"magnitude":1},{"id":28,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":28,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":28,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]}],"background":"#FFFFFF","width":1042,"height":500,"maxWidth":5000,"maxHeight":5000,"nodeIndex":60,"autoFit":true,"exportBorder":false,"gridOn":true,"snapToGrid":true,"drawingGuidesOn":true,"pageBreaksOn":false,"printGridOn":false,"printPaper":"LETTER","printShrinkToFit":false,"printPortrait":true,"shapeStyles":{},"lineStyles":{},"textStyles":{},"themeData":null}} \ No newline at end of file diff --git "a/students/315863321/uml/\351\252\260\345\255\220\346\270\270\346\210\217\347\261\273\345\233\276.gliffy" "b/students/315863321/uml/\351\252\260\345\255\220\346\270\270\346\210\217\347\261\273\345\233\276.gliffy" new file mode 100644 index 0000000000..30980d2428 --- /dev/null +++ "b/students/315863321/uml/\351\252\260\345\255\220\346\270\270\346\210\217\347\261\273\345\233\276.gliffy" @@ -0,0 +1 @@ +{"contentType":"application/gliffy+json","version":"1.1","metadata":{"title":"untitled","revision":0,"exportBorder":false},"embeddedResources":{"index":0,"resources":[]},"stage":{"objects":[{"x":330,"y":257,"rotation":0,"id":63,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":30,"height":14,"lockAspectRatio":false,"lockShape":false,"order":34,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

1

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":290,"y":257,"rotation":0,"id":62,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":20,"height":14,"lockAspectRatio":false,"lockShape":false,"order":33,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

1

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":586,"y":257,"rotation":0,"id":60,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":20,"height":14,"lockAspectRatio":false,"lockShape":false,"order":32,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

2

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":548,"y":257,"rotation":0,"id":59,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":80,"height":14,"lockAspectRatio":false,"lockShape":false,"order":31,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

1

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":445,"y":328,"rotation":0,"id":53,"uid":"com.gliffy.shape.uml.uml_v1.default.association","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":30,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[5,-57],[5,-27.666666666666686],[5,1.6666666666666856],[5,31]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":18,"px":0.5,"py":1}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":46,"px":0.5,"py":0}}},"linkMap":[]},{"x":564,"y":243,"rotation":0,"id":45,"uid":"com.gliffy.shape.uml.uml_v1.default.aggregation","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":22,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":5,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-44,-2.5],[-6.333333333333371,-2.5],[31.33333333333337,-2.5],[69,-2.5]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":18,"px":1,"py":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":38,"px":0,"py":0.5}}},"linkMap":[]},{"x":271,"y":246,"rotation":0,"id":25,"uid":"com.gliffy.shape.uml.uml_v1.default.association","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":14,"graphic":{"type":"Line","Line":{"strokeWidth":1,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-1,-5.5],[35.666666666666686,-5.5],[72.33333333333331,-5.5],[109,-5.5]],"lockSegments":{}}},"children":[],"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":0,"px":1,"py":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":18,"px":0,"py":0.5}}},"linkMap":[]},{"x":130,"y":210,"rotation":0,"id":0,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":140,"height":61,"lockAspectRatio":false,"lockShape":false,"order":0,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":1,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":2,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

Player

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":2,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":3,"uid":null,"width":140,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":4,"uid":null,"width":140,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":1,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":4,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":22,"rotation":0,"id":5,"uid":null,"width":140,"height":39,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":6,"uid":null,"width":140,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":0,"magnitude":1},{"id":1,"magnitude":-1},{"id":3,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":3,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":1,"magnitude":1},{"id":3,"magnitude":1},{"id":6,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":380,"y":210,"rotation":0,"id":18,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":140,"height":61,"lockAspectRatio":false,"lockShape":false,"order":7,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":19,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":20,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

DiceGame

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":20,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":21,"uid":null,"width":140,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":22,"uid":null,"width":140,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":19,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":22,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":22,"rotation":0,"id":23,"uid":null,"width":140,"height":39,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":24,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

+play()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":18,"magnitude":1},{"id":19,"magnitude":-1},{"id":21,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":21,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":19,"magnitude":1},{"id":21,"magnitude":1},{"id":24,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":633,"y":203,"rotation":0,"id":38,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":140,"height":75,"lockAspectRatio":false,"lockShape":false,"order":15,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":39,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":40,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

Dice

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":40,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":41,"uid":null,"width":140,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":42,"uid":null,"width":140,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":39,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":42,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":22,"rotation":0,"id":43,"uid":null,"width":140,"height":53,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":44,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

+roll()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":38,"magnitude":1},{"id":39,"magnitude":-1},{"id":41,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":41,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":39,"magnitude":1},{"id":41,"magnitude":1},{"id":44,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":380,"y":359,"rotation":0,"id":46,"uid":"com.gliffy.shape.uml.uml_v1.default.class","width":140,"height":75,"lockAspectRatio":false,"lockShape":false,"order":23,"graphic":null,"children":[{"x":0,"y":0,"rotation":0,"id":47,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":48,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

Display

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":48,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":18,"rotation":0,"id":49,"uid":null,"width":140,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":50,"uid":null,"width":140,"height":4,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"PositionConstraint","PositionConstraint":{"nodeId":47,"px":0,"py":1}},{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":50,"magnitude":1}],"growParent":true,"padding":0}}]}},{"x":0,"y":22,"rotation":0,"id":51,"uid":null,"width":140,"height":53,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2,"strokeColor":"#000000","fillColor":"#FFFFFF","gradient":false,"dropShadow":true,"state":0,"shadowX":4,"shadowY":4,"opacity":1}},"children":[{"x":0,"y":0,"rotation":0,"id":52,"uid":null,"width":140,"height":18,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"top","overflow":"none","vposition":"none","hposition":"none","html":"

+showResult()

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":false,"heightInfo":[{"id":46,"magnitude":1},{"id":47,"magnitude":-1},{"id":49,"magnitude":-1}],"growParent":false,"padding":0}},{"type":"PositionConstraint","PositionConstraint":{"nodeId":49,"px":0,"py":1}}]}}],"constraints":{"constraints":[{"type":"HeightConstraint","HeightConstraint":{"isMin":true,"heightInfo":[{"id":47,"magnitude":1},{"id":49,"magnitude":1},{"id":52,"magnitude":1}],"growParent":false,"padding":0}}]},"linkMap":[]},{"x":470,"y":290,"rotation":0,"id":64,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":20,"height":14,"lockAspectRatio":false,"lockShape":false,"order":35,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

1

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":472,"y":330,"rotation":0,"id":65,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":20,"height":14,"lockAspectRatio":false,"lockShape":false,"order":36,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

1

","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]}],"background":"#FFFFFF","width":775,"height":434,"maxWidth":5000,"maxHeight":5000,"nodeIndex":66,"autoFit":true,"exportBorder":false,"gridOn":true,"snapToGrid":true,"drawingGuidesOn":true,"pageBreaksOn":false,"printGridOn":false,"printPaper":"LETTER","printShrinkToFit":false,"printPortrait":true,"shapeStyles":{},"lineStyles":{},"textStyles":{},"themeData":null}} \ No newline at end of file diff --git a/students/329866097/.gitignore b/students/329866097/.gitignore new file mode 100644 index 0000000000..bf58d0a162 --- /dev/null +++ b/students/329866097/.gitignore @@ -0,0 +1,80 @@ +###################### +# 解决java产生文件 +###################### +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +###################### +# 解决maven产生的文件 +###################### + +target/ +**/target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties + +###################### +# 解决各类编辑器自动产生的文件 +###################### + +*.iml + +## Directory-based project format: +.idea/ +# if you remove the above rule, at least ignore the following: + +# User-specific stuff: +# .idea/workspace.xml +# .idea/tasks.xml +# .idea/dictionaries + +# Sensitive or high-churn files: +# .idea/dataSources.ids +# .idea/dataSources.xml +# .idea/sqlDataSources.xml +# .idea/dynamic.xml +# .idea/uiDesigner.xml + +# Gradle: +# .idea/gradle.xml +# .idea/libraries + +# Mongo Explorer plugin: +# .idea/mongoSettings.xml + +## File-based project format: +*.ipr +*.iws + +## Plugin-specific files: + +# IntelliJ +/out/ +/target/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties diff --git a/students/329866097/README.md b/students/329866097/README.md new file mode 100644 index 0000000000..87f2e553da --- /dev/null +++ b/students/329866097/README.md @@ -0,0 +1 @@ +Mr.Who 作业提交 \ No newline at end of file diff --git a/students/329866097/pom.xml b/students/329866097/pom.xml new file mode 100644 index 0000000000..b1b8d4d410 --- /dev/null +++ b/students/329866097/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + + com.coderising + ood-assignment-txh + 1.0-SNAPSHOT + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + \ No newline at end of file diff --git a/students/329866097/src/main/java/com/coderising/ood/srp/Configuration.java b/students/329866097/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/329866097/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/329866097/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/329866097/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/329866097/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/329866097/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/329866097/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..2c5d9dd968 --- /dev/null +++ b/students/329866097/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,22 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList<>(); + for (int i = 1; i <= 3; i++) { + User user = new User("User" + i, "aa@bb.com"); + userList.add(user); + } + return userList; + } +} diff --git a/students/329866097/src/main/java/com/coderising/ood/srp/Email.java b/students/329866097/src/main/java/com/coderising/ood/srp/Email.java new file mode 100644 index 0000000000..ced66562d2 --- /dev/null +++ b/students/329866097/src/main/java/com/coderising/ood/srp/Email.java @@ -0,0 +1,49 @@ +package com.coderising.ood.srp; + +/** + * Created by tianxianhu on 2017/6/18. + */ +public class Email { + + private static String smtpHost; + private static String altSmtpHost; + private static String fromAddress; + + private static Configuration config; + + static { + config = new Configuration(); + setDefaultConfig(config); + } + + private static void setDefaultConfig(Configuration config) { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + public void send(User user, String product, String host) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + + if(user.getEmail().length() > 0) { + String name = user.getName(); + String subject = "您关注的产品降价了"; + String message = "尊敬的 " + name + ", 您关注的产品 " + product + " 降价了,欢迎购买!"; + + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(user.getEmail()).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + } + } + + public String getSmtpHost() { + return smtpHost; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } +} diff --git a/students/329866097/src/main/java/com/coderising/ood/srp/FileUtil.java b/students/329866097/src/main/java/com/coderising/ood/srp/FileUtil.java new file mode 100644 index 0000000000..e8cdb97e9a --- /dev/null +++ b/students/329866097/src/main/java/com/coderising/ood/srp/FileUtil.java @@ -0,0 +1,36 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public class FileUtil { + + public static Map readFile(String filePath) throws IOException { + File file = new File(filePath); + BufferedReader br = null; + Map productMap = new HashMap<>(); + try { + br = new BufferedReader(new FileReader(file)); + String content; + while((content = br.readLine()) != null) { + String[] data = content.split(" "); + String productId = data[0]; + String productDesc = data[1]; + productMap.put(productId, productDesc); + System.out.println("产品ID = " + productId + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + } + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + + return productMap; + } +} diff --git a/students/329866097/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/329866097/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..1273603cb8 --- /dev/null +++ b/students/329866097/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,44 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.*; +import java.util.stream.Collectors; + +public class PromotionMail { + + public static void main(String[] args) throws Exception { + Email email = new Email(); + + Map productMap = FileUtil.readFile( "src/main/resources/product_promotion.txt"); + for (Map.Entry entry : productMap.entrySet()) { + String productId = entry.getKey(); + String productDesc = entry.getValue(); + List userList = DBUtil.query(setLoadQuery(productId)); + for(User user : userList) { + try { + email.send(user, productDesc, email.getSmtpHost()); + } catch (Exception e) { + try { + email.send(user, productDesc, email.getAltSmtpHost()); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + } + } + + private static String setLoadQuery(String productID) throws Exception { + + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + System.out.println("loadQuery set"); + + return sendMailQuery; + } +} diff --git a/students/329866097/src/main/java/com/coderising/ood/srp/User.java b/students/329866097/src/main/java/com/coderising/ood/srp/User.java new file mode 100644 index 0000000000..c1df43bc45 --- /dev/null +++ b/students/329866097/src/main/java/com/coderising/ood/srp/User.java @@ -0,0 +1,31 @@ +package com.coderising.ood.srp; + +/** + * Created by tianxianhu on 2017/6/18. + */ +public class User { + + private String name; + private String email; + + public User(String name, String email) { + this.name = name; + this.email = email; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/students/329866097/src/main/resources/product_promotion.txt b/students/329866097/src/main/resources/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/329866097/src/main/resources/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/335402763/pom.xml b/students/335402763/pom.xml new file mode 100644 index 0000000000..d73cd62750 --- /dev/null +++ b/students/335402763/pom.xml @@ -0,0 +1,6 @@ + + 4.0.0 + com.coderising + 335402763Learning + 0.0.1-SNAPSHOT + \ No newline at end of file diff --git a/students/335402763/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/335402763/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..4e777b5cd0 --- /dev/null +++ b/students/335402763/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,21 @@ +package com.coderising.ood.srp; + +import java.io.File; + +import com.coderising.ood.srp.service.PromotionMailService; +import com.coderising.ood.srp.service.impl.PromotionMailServiceImpl; + + +public class PromotionMail { + + + public static void main(String[] args) throws Exception { + + File f = new File("D:\\Program Files\\mygit\\coding2017\\students\\335402763\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMailService promotionMailService = new PromotionMailServiceImpl(); + promotionMailService.sendPromotionMail(f, emailDebug); + } + +} diff --git a/students/335402763/src/main/java/com/coderising/ood/srp/dao/PromotionMailDao.java b/students/335402763/src/main/java/com/coderising/ood/srp/dao/PromotionMailDao.java new file mode 100644 index 0000000000..21f143ff11 --- /dev/null +++ b/students/335402763/src/main/java/com/coderising/ood/srp/dao/PromotionMailDao.java @@ -0,0 +1,12 @@ +package com.coderising.ood.srp.dao; + +import java.util.List; + +public interface PromotionMailDao { + + /** + * 读取用户信息 + */ + List loadMailingList(String productID); + +} diff --git a/students/335402763/src/main/java/com/coderising/ood/srp/dao/impl/PromotionMailDaoImpl.java b/students/335402763/src/main/java/com/coderising/ood/srp/dao/impl/PromotionMailDaoImpl.java new file mode 100644 index 0000000000..339f5b648e --- /dev/null +++ b/students/335402763/src/main/java/com/coderising/ood/srp/dao/impl/PromotionMailDaoImpl.java @@ -0,0 +1,35 @@ +package com.coderising.ood.srp.dao.impl; + +import java.util.List; + +import com.coderising.ood.srp.dao.PromotionMailDao; +import com.coderising.ood.srp.utils.DBUtil; + +public class PromotionMailDaoImpl implements PromotionMailDao { + + protected String productID = null; + protected String sendMailQuery = null; + + /** + * 读取用户信息 + */ + @Override + public List loadMailingList(String productID) { + try { + setLoadQuery(productID); + + } catch (Exception e) { + e.printStackTrace(); + } + return DBUtil.query(this.sendMailQuery); + + } + + protected void setLoadQuery(String productID) throws Exception { + + sendMailQuery = "Select name from subscriptions " + "where product_id= '" + productID + "' " + + "and send_mail=1 "; + + System.out.println("loadQuery set"); + } +} diff --git a/students/335402763/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/335402763/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/335402763/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/335402763/src/main/java/com/coderising/ood/srp/service/PromotionMailService.java b/students/335402763/src/main/java/com/coderising/ood/srp/service/PromotionMailService.java new file mode 100644 index 0000000000..9d1db0cd71 --- /dev/null +++ b/students/335402763/src/main/java/com/coderising/ood/srp/service/PromotionMailService.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp.service; + +import java.io.File; + +public interface PromotionMailService { + + void sendPromotionMail(File file, boolean mailDebug) throws Exception; + +} diff --git a/students/335402763/src/main/java/com/coderising/ood/srp/service/impl/PromotionMailServiceImpl.java b/students/335402763/src/main/java/com/coderising/ood/srp/service/impl/PromotionMailServiceImpl.java new file mode 100644 index 0000000000..2d1e8b491a --- /dev/null +++ b/students/335402763/src/main/java/com/coderising/ood/srp/service/impl/PromotionMailServiceImpl.java @@ -0,0 +1,86 @@ +package com.coderising.ood.srp.service.impl; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import com.coderising.ood.srp.dao.PromotionMailDao; +import com.coderising.ood.srp.dao.impl.PromotionMailDaoImpl; +import com.coderising.ood.srp.service.PromotionMailService; +import com.coderising.ood.srp.utils.FileUtil; +import com.coderising.ood.srp.utils.MailUtil; +import com.coderising.ood.srp.utils.PropertiesUtils; + +public class PromotionMailServiceImpl implements PromotionMailService { + + private PromotionMailDao promotionMailDao = new PromotionMailDaoImpl(); + + protected String smtpHost = (String) PropertiesUtils.get(PropertiesUtils.SMTP_SERVER);; + protected String altSmtpHost = (String) PropertiesUtils.get(PropertiesUtils.ALT_SMTP_SERVER);; + protected String fromAddress = (String) PropertiesUtils.get(PropertiesUtils.EMAIL_ADMIN); + + @Override + public void sendPromotionMail(File file, boolean mailDebug) throws Exception { + + // 读取商品信息 + String[] productData = FileUtil.readFile(file); + String productID = productData[0]; + String productDesc = productData[1]; + + List mailingList = promotionMailDao.loadMailingList(productID); + + sendEMails(mailDebug, mailingList, productDesc); + + } + + + /** + * 发送邮件 + * @param debug + * @param mailingList + * @param productDesc + * @throws IOException + */ + protected void sendEMails(boolean debug, List mailingList, String productDesc) throws IOException { + + System.out.println("开始发送邮件"); + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + + HashMap usrInfo = (HashMap) iter.next(); + + HashMap eMailInfo = MailUtil.configureEMail(usrInfo, productDesc); + String toAddress = (String) eMailInfo.get("toAddress"); + String subject = (String) eMailInfo.get("subject"); + String message = (String) eMailInfo.get("message"); + + try { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } catch (Exception e) { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + } + + else { + System.out.println("没有邮件发送"); + + } + } + + + + +} diff --git a/students/335402763/src/main/java/com/coderising/ood/srp/utils/DBUtil.java b/students/335402763/src/main/java/com/coderising/ood/srp/utils/DBUtil.java new file mode 100644 index 0000000000..2a7002dede --- /dev/null +++ b/students/335402763/src/main/java/com/coderising/ood/srp/utils/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp.utils; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/335402763/src/main/java/com/coderising/ood/srp/utils/FileUtil.java b/students/335402763/src/main/java/com/coderising/ood/srp/utils/FileUtil.java new file mode 100644 index 0000000000..d0a53ec6ae --- /dev/null +++ b/students/335402763/src/main/java/com/coderising/ood/srp/utils/FileUtil.java @@ -0,0 +1,28 @@ +package com.coderising.ood.srp.utils; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; + +public class FileUtil { + + public static String[] readFile(File file) throws IOException // @02C + { + HashMap map = new HashMap(); + BufferedReader br = null; + String[] data = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + data = temp.split(" "); + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + return data; + } + +} diff --git a/students/335402763/src/main/java/com/coderising/ood/srp/utils/MailUtil.java b/students/335402763/src/main/java/com/coderising/ood/srp/utils/MailUtil.java new file mode 100644 index 0000000000..5e72b2e163 --- /dev/null +++ b/students/335402763/src/main/java/com/coderising/ood/srp/utils/MailUtil.java @@ -0,0 +1,55 @@ +package com.coderising.ood.srp.utils; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; + +public class MailUtil { + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + //配置发送地址及内容 + public static HashMap configureEMail(HashMap userInfo , String productDesc) throws IOException { + HashMap map = new HashMap(); + String toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) { + map = setMessage(userInfo,productDesc); + } + map.put("toAddress", toAddress); + return map; + } + + //设置信息内容 + public static HashMap setMessage(HashMap userInfo , String productDesc) throws IOException + { + HashMap map = new HashMap(); + String name = (String) userInfo.get(NAME_KEY); + + String subject = "您关注的产品降价了"; + String message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + + map.put("subject", subject); + map.put("message", message); + + return map; + + } + + + +} diff --git a/students/335402763/src/main/java/com/coderising/ood/srp/utils/PropertiesUtils.java b/students/335402763/src/main/java/com/coderising/ood/srp/utils/PropertiesUtils.java new file mode 100644 index 0000000000..e8b94b20e7 --- /dev/null +++ b/students/335402763/src/main/java/com/coderising/ood/srp/utils/PropertiesUtils.java @@ -0,0 +1,40 @@ +package com.coderising.ood.srp.utils; + +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +public class PropertiesUtils { + + private static Map props=new HashMap(); + private static Properties properties=new Properties(); + + public static final String SMTP_SERVER = "SMTP_SERVER"; + public static final String ALT_SMTP_SERVER = "ALT_SMTP_SERVER"; + public static final String EMAIL_ADMIN = "EMAIL_ADMIN"; + static{ + try { + InputStream inStream=PropertiesUtils.class.getClassLoader().getResourceAsStream("configurationKeys.properties"); + properties.load(inStream); + + props.put(SMTP_SERVER, properties.get(SMTP_SERVER)); + props.put(ALT_SMTP_SERVER, properties.get(ALT_SMTP_SERVER)); + props.put(EMAIL_ADMIN, properties.get(EMAIL_ADMIN)); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + + public static Object get(String key){ + return props.get(key); + } + + public static void set(String key,Object obj){ + props.put(key, obj); + } + +} diff --git a/students/335402763/src/main/resources/configurationKeys.properties b/students/335402763/src/main/resources/configurationKeys.properties new file mode 100644 index 0000000000..acde908d1c --- /dev/null +++ b/students/335402763/src/main/resources/configurationKeys.properties @@ -0,0 +1,3 @@ +SMTP_SERVER=smtp.server +ALT_SMTP_SERVER=alt.smtp.server +EMAIL_ADMIN=email.admin \ No newline at end of file diff --git a/students/34594980/ood/ood-assignment/pom.xml b/students/34594980/ood/ood-assignment/pom.xml new file mode 100644 index 0000000000..a7e5041647 --- /dev/null +++ b/students/34594980/ood/ood-assignment/pom.xml @@ -0,0 +1,44 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + diff --git a/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..b40eb53476 --- /dev/null +++ b/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,34 @@ +package com.coderising.ood.srp; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * + * @param sql + * @return + */ + public static List> query(String sql) { + + List> userList = new ArrayList<>(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap<>(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + return userList; + } + + public static List> loadMailingList(Product product) { + + String sendMailQuery = "Select name from subscriptions " + "where product_id= '" + + product.getId() + "' " + "and send_mail=1 "; + System.out.println("loadQuery set"); + return DBUtil.query(sendMailQuery); + } +} diff --git a/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Email.java b/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Email.java new file mode 100644 index 0000000000..e5e6a29076 --- /dev/null +++ b/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Email.java @@ -0,0 +1,49 @@ +package com.coderising.ood.srp; + +public class Email { + + private String smtpHost ; + private String altSmtpHost ; + private String fromAddress ; + private String toAddress ; + private String subject ; + private String message ; + + + public String getSmtpHost() { + return smtpHost; + } + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + public String getAltSmtpHost() { + return altSmtpHost; + } + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + public String getFromAddress() { + return fromAddress; + } + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + public String getToAddress() { + return toAddress; + } + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + public String getSubject() { + return subject; + } + public void setSubject(String subject) { + this.subject = subject; + } + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } +} diff --git a/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtil.java b/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtil.java new file mode 100644 index 0000000000..6abdc05ebd --- /dev/null +++ b/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtil.java @@ -0,0 +1,36 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +public class FileUtil { + + private static final String FILENAME="product_promotion.txt"; + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + public static Product readFile()// @02C + { + Product product = null; + BufferedReader br = null; + try { + String filePath = FileUtil.class.getResource(FILENAME).getPath(); + File file = new File(filePath); + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + product = new Product(data[0], data[1]); + + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return product; + } +} diff --git a/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..ef1eb60c5b --- /dev/null +++ b/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,77 @@ +package com.coderising.ood.srp; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class MailUtil { + + + private static Configuration config; + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void sendEMails(boolean debug) + { + + Product product = FileUtil.readFile(); + System.out.println(product.toString()); + + System.out.println("开始发送邮件"); + + List> mailingList = DBUtil.loadMailingList(product); + + if (mailingList == null){ + System.out.println("没有邮件发送"); + return ; + } + + Iterator> iter = mailingList.iterator(); + while (iter.hasNext()) { + HashMap userInfo = iter.next(); + Email email = MailUtil.configureEMail(userInfo,product); + try { + sendEmail(email.getToAddress(),email.getFromAddress(),email.getSubject(),email.getMessage(),email.getSmtpHost(),debug); + } catch (Exception e1) { + try { + sendEmail(email.getToAddress(),email.getFromAddress(),email.getSubject(),email.getMessage(),email.getAltSmtpHost(),debug); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + } + + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost,boolean debug) { + + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + public static Email configureEMail(HashMap userInfo,Product product){ + + Email email = new Email(); + config = new Configuration(); + email.setSmtpHost(config.getProperty(ConfigurationKeys.SMTP_SERVER)); + email.setAltSmtpHost(config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER)); + email.setFromAddress(config.getProperty(ConfigurationKeys.EMAIL_ADMIN)); + email.setSubject("您关注的产品降价了"); + String toAddress = (String) userInfo.get(EMAIL_KEY); + email.setToAddress(toAddress); + String name = (String) userInfo.get(NAME_KEY); + email.setMessage("尊敬的 "+name+", 您关注的产品 " + product.getDesc() + " 降价了,欢迎购买!"); + + return email; + + } +} diff --git a/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java b/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..e96809d498 --- /dev/null +++ b/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,32 @@ +package com.coderising.ood.srp; + +public class Product { + + private String id; //产品ID + private String desc; //产品描述 + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public String getDesc() { + return desc; + } + public void setDesc(String desc) { + this.desc = desc; + } + + + public Product() { + } + public Product(String id, String desc) { + this.id = id; + this.desc = desc; + } + @Override + public String toString() { + return "产品ID=" + id + "\n产品描述 = " + desc; + } + +} diff --git a/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..cf5b0879a0 --- /dev/null +++ b/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,16 @@ +package com.coderising.ood.srp; + + +public class PromotionMail { + + + public static void main(String[] args) { + + boolean emailDebug = false; + + MailUtil.sendEMails(emailDebug); + + } + + +} diff --git a/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/34594980/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/346154295/ood-assignment/pom.xml b/students/346154295/ood-assignment/pom.xml new file mode 100644 index 0000000000..0853e4c187 --- /dev/null +++ b/students/346154295/ood-assignment/pom.xml @@ -0,0 +1,46 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 1.7 + 1.7 + UTF-8 + + + + + diff --git a/students/346154295/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/346154295/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/346154295/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/346154295/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/346154295/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/346154295/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/346154295/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/346154295/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..ad72a12c22 --- /dev/null +++ b/students/346154295/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,28 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param productID + * @return + */ + public static List> loadMailingList(String productID){ + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID + "' " + + "and send_mail=1 "; + System.out.println("loadQuery set"); + List> userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/346154295/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/346154295/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..f9627d307e --- /dev/null +++ b/students/346154295/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,40 @@ +package com.coderising.ood.srp; + +public class MailUtil { + private static String smtpHost; + private static String altSmtpHost; + private static String fromAddress; + + public static void init() { + Configuration config = new Configuration(); + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + private static void sendEmail(String toAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + public static void sendEmail(String toAddress, String subject, String message, boolean debug) { + if(toAddress == null || toAddress.length() == 0) { + return; + } + try { + sendEmail(toAddress,subject,message,smtpHost,debug); + } catch (Exception e) { + try { + sendEmail(toAddress, subject, message, altSmtpHost, debug); + } catch (Exception e2){ + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } +} diff --git a/students/346154295/ood-assignment/src/main/java/com/coderising/ood/srp/ProductInfo.java b/students/346154295/ood-assignment/src/main/java/com/coderising/ood/srp/ProductInfo.java new file mode 100644 index 0000000000..e3719a503d --- /dev/null +++ b/students/346154295/ood-assignment/src/main/java/com/coderising/ood/srp/ProductInfo.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; + +/** + * Created by xiaoyj on 2017/6/15. + */ +public class ProductInfo { + private String productID; + private String productDesc; + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git a/students/346154295/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/346154295/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..e7530dbc55 --- /dev/null +++ b/students/346154295/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,73 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; + +public class PromotionMail { + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + boolean emailDebug = false; + File file = new File("src/main/resource/product_promotion.txt"); + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + ProductInfo productInfo = getProductInfo(file); + List> mailingList = DBUtil.loadMailingList(productInfo.getProductID()); + sendEMails(emailDebug, mailingList, productInfo); + + } + + private static String getMessage(HashMap userInfo, ProductInfo productInfo) throws IOException + { + String name = userInfo.get(NAME_KEY); + return "尊敬的 "+name+", 您关注的产品 " + productInfo.getProductDesc() + " 降价了,欢迎购买!" ; + } + private static String getSubject() { + return "您关注的产品降价了"; + } + + protected static void sendEMails(boolean debug, List> mailingList, ProductInfo productInfo) throws IOException { + System.out.println("开始发送邮件"); + MailUtil.init(); + if (mailingList != null) { + for (HashMap userInfo : mailingList) { + String toAddress = userInfo.get(EMAIL_KEY); + if (toAddress == null || toAddress.length() == 0) { + continue; + } + String subject = getSubject(); + String message =getMessage(userInfo, productInfo); + MailUtil.sendEmail(toAddress, subject, message, debug); + } + + } else { + System.out.println("没有邮件发送"); + + } + } + private static ProductInfo getProductInfo(File file) throws IOException { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + ProductInfo productInfo = new ProductInfo(); + productInfo.setProductID(data[0]); + productInfo.setProductDesc(data[1]); + + System.out.println("产品ID = " + productInfo.getProductID() + "\n"); + System.out.println("产品描述 = " + productInfo.getProductDesc() + "\n"); + return productInfo; + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } +} diff --git a/students/346154295/ood-assignment/src/main/resource/product_promotion.txt b/students/346154295/ood-assignment/src/main/resource/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/346154295/ood-assignment/src/main/resource/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/349166103/ood/ood-assignment/pom.xml b/students/349166103/ood/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/349166103/ood/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/349166103/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/349166103/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..80d83d3a81 --- /dev/null +++ b/students/349166103/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,67 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + private String smtpHost = null; + private String altSmtpHost = null; + private String fromAddress = null; + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + + public Configuration(){ + setSMTPHost(); + setAltSMTPHost(); + setFromAddress(); + } + + + private void setSMTPHost() + { + smtpHost = ConfigurationKeys.SMTP_SERVER; + } + + private void setAltSMTPHost() + { + altSmtpHost = ConfigurationKeys.ALT_SMTP_SERVER; + + } + + private void setFromAddress() + { + fromAddress = ConfigurationKeys.EMAIL_ADMIN; + } + + public String getFromAddress() + { + return fromAddress; + } + + public String getSMTPHost() + { + return smtpHost; + } + + public String getAltSMTPHost() + { + return altSmtpHost; + } + + + +} diff --git a/students/349166103/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/349166103/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/349166103/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/349166103/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/349166103/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..1c9afcdfb2 --- /dev/null +++ b/students/349166103/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,93 @@ +package com.coderising.ood.srp; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + private String sendMailQuery = null; + private String productID = null; + private String productDesc = null; + private File f = null; + + DBUtil(File f){ + try { + readFile(f); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } + + public List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + private void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + getProductID() +"' " + + "and send_mail=1 "; + System.out.println("loadQuery set"); + } + + + private void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + private void setProductDesc(String desc) { + this.productDesc = desc; + } + + protected void setProductID(String productID) + { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public String getProductID() { + return productID; + } +} diff --git a/students/349166103/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailContent.java b/students/349166103/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailContent.java new file mode 100644 index 0000000000..e1abf927f4 --- /dev/null +++ b/students/349166103/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailContent.java @@ -0,0 +1,54 @@ +package com.coderising.ood.srp; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; + +public class MailContent { + + private String subject = null; + private String message = null; + private String toAddress = null; + private final String NAME_KEY = "NAME"; + private final String EMAIL_KEY = "EMAIL"; + + public MailContent(File f, HashMap userInfo, String prodInfo){ + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + try { + configureEMail(userInfo, prodInfo); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + + private void setMessage(HashMap userInfo, String prodInfo) throws IOException + { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + prodInfo + " 降价了,欢迎购买!" ; + + } + + protected void configureEMail(HashMap userInfo, String prodInfo) throws IOException + { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo, prodInfo); + } + + public String getToAddress() { + return toAddress; + } + + public String getSubject() { + return subject; + } + + public String getMessage() { + return message; + } +} diff --git a/students/349166103/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/349166103/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..f676fd5fdb --- /dev/null +++ b/students/349166103/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,52 @@ +package com.coderising.ood.srp; + +import java.io.File; +import java.util.HashMap; + +public class MailUtil { + + private MailContent mc = null; + private String toAddress = null; + private String fromAddress = null; + private String subject = null; + private String message = null; + private String smtpHost = null; + private String altSmtpHost = null; + + public MailUtil(Configuration config, File f, HashMap userInfo, String prodInfo){ + mc = new MailContent(f, userInfo, prodInfo); + toAddress = mc.getToAddress(); + subject = mc.getSubject(); + message = mc.getMessage(); + fromAddress = config.getFromAddress(); + smtpHost = config.getSMTPHost(); + altSmtpHost = config.getAltSMTPHost(); + } + public void sendEmail(boolean debug) { + try + { + if (toAddress.length() > 0) + sendEmail(smtpHost); + } + catch (Exception e) + { + try { + sendEmail(altSmtpHost); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + private void sendEmail(String server){ + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + } +} diff --git a/students/349166103/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/349166103/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..86e5abaa0d --- /dev/null +++ b/students/349166103/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,33 @@ +package com.coderising.ood.srp; + +import java.io.File; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + public static void main(String[] args) throws Exception { + File f = new File(System.getProperty("user.dir")+"/src/main/java/com/coderising/ood/srp/product_promotion.txt"); + boolean emailDebug = false; + PromotionMail pe = new PromotionMail(emailDebug, f); + } + + public PromotionMail(boolean debug, File f) throws Exception + { + Configuration config = new Configuration(); + DBUtil dbu = new DBUtil(f); + List mailingList = dbu.loadMailingList(); + System.out.println("开始发送邮件"); + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + MailUtil mu = new MailUtil(config, f, (HashMap)iter.next(), dbu.getProductDesc()); + mu.sendEmail(debug); + } + } + else { + System.out.println("没有邮件发送"); + } + } +} diff --git a/students/349166103/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/349166103/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/349166103/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/349184132/ood/ood-assignment/pom.xml b/students/349184132/ood/ood-assignment/pom.xml new file mode 100644 index 0000000000..e5f19f00ee --- /dev/null +++ b/students/349184132/ood/ood-assignment/pom.xml @@ -0,0 +1,44 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.7 + 1.7 + + + + + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/logtype/LogType.java b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/logtype/LogType.java new file mode 100644 index 0000000000..e776ffaf22 --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/logtype/LogType.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp.logtype; + +/** + * Created by wang on 2017/6/19. + */ +public interface LogType { + + + void Send(String msglog); +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/logtype/MailLogTypeImp.java b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/logtype/MailLogTypeImp.java new file mode 100644 index 0000000000..0252b9d911 --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/logtype/MailLogTypeImp.java @@ -0,0 +1,13 @@ +package com.coderising.ood.ocp.logtype; + +import com.coderising.ood.ocp.util.MailUtil; + +/** + * Created by wang on 2017/6/19. + */ +public class MailLogTypeImp implements LogType { + @Override + public void Send(String msglog) { + MailUtil.send(msglog); + } +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/logtype/PrintLogTypeImp.java b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/logtype/PrintLogTypeImp.java new file mode 100644 index 0000000000..44f69f9d79 --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/logtype/PrintLogTypeImp.java @@ -0,0 +1,13 @@ +package com.coderising.ood.ocp.logtype; + +import com.coderising.ood.ocp.util.SMSUtil; + +/** + * Created by wang on 2017/6/19. + */ +public class PrintLogTypeImp implements LogType{ + @Override + public void Send(String msglog) { + SMSUtil.send(msglog); + } +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/logtype/SmsLogTypeImp.java b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/logtype/SmsLogTypeImp.java new file mode 100644 index 0000000000..2613a28f3f --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/logtype/SmsLogTypeImp.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp.logtype; + +/** + * Created by wang on 2017/6/19. + */ +public class SmsLogTypeImp implements LogType { + @Override + public void Send(String msglog) { + System.out.println(msglog); + } +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/newb/Logger.java b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/newb/Logger.java new file mode 100644 index 0000000000..d444796597 --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/newb/Logger.java @@ -0,0 +1,27 @@ +package com.coderising.ood.ocp.newb; + +import com.coderising.ood.ocp.log.Log; +import com.coderising.ood.ocp.logtype.LogType; + +/** + * Created by wang on 2017/6/19. + */ +public class Logger { + + private Log log ; + + private LogType logType; + + public Logger(Log log, LogType logType) { + this.log = log; + this.logType = logType; + } + + public void log(String msg){ + + String msglog = log.setMsgLog(msg); + + logType.Send(msglog); + + } +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/util/DateUtil.java b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/util/DateUtil.java new file mode 100644 index 0000000000..ca7b21a6dd --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/util/DateUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp.util; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return null; + } + +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/util/MailUtil.java b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/util/MailUtil.java new file mode 100644 index 0000000000..9191303993 --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/util/MailUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp.util; + +public class MailUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/util/SMSUtil.java b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/util/SMSUtil.java new file mode 100644 index 0000000000..9fab3d9430 --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/util/SMSUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp.util; + +public class SMSUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailContent.java b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailContent.java new file mode 100644 index 0000000000..ebc3788355 --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailContent.java @@ -0,0 +1,64 @@ +package com.coderising.ood.srp; + +/** + * Created by wang on 2017/6/17. + */ +public class MailContent { + + private Configuration config = new Configuration(); + + private String smtpHost; + + private String altSmtpHost; + + private String fromAddress; + + private String subject; + + private String message; + + + + public String getSmtpHost() { + return smtpHost; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public String getFromAddress() { + return fromAddress; + } + + public String getSubject() { + return subject; + } + + public String getMessage() { + return message; + } + + public void setSMTPHost() { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + + } + + public void setAltSMTPHost() { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + } + + + public void setFromAddress() { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + + public void setMessage(String uName, String productDesc){ + + + subject = "您关注的产品降价了"; + message = "尊敬的 "+uName+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + + } +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..75a52080ad --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,74 @@ +package com.coderising.ood.srp; + +import com.coderising.ood.srp.bean.ProductInfo; +import com.coderising.ood.srp.bean.UserInfo; +import com.coderising.ood.srp.util.MailUtil; + +import java.util.List; + +/** + * Created by wang on 2017/6/17. + */ + +/** + * 发送邮件类 + */ +public class PromotionMail { + + private List proInfo; + private List userInfo; + private MailContent mailContent; + + public PromotionMail(){ + + } + + + + public PromotionMail(List proInfo, List userInfo, MailContent mailContent) { + this.proInfo = proInfo; + this.userInfo = userInfo; + this.mailContent = mailContent; + } + + public void sendEMail(){ + + sendEMail(false); + + } + + public void sendEMail(boolean debug){ + + String productDesc = proInfo.get(0).getProductDesc(); + + System.out.println("开始发送邮件:"); + for(UserInfo u : userInfo) { + + String name = u.getName(); + + setEmailContent(productDesc, name); + + String toAddress = u.getEmail(); + String fromAddress = mailContent.getFromAddress(); + String subject = mailContent.getSubject(); + String message = mailContent.getMessage(); + String smtpHost = mailContent.getSmtpHost(); + String altSmtpHost = mailContent.getAltSmtpHost(); + + if(message == "" && message == null){ + return ; + } + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, altSmtpHost, debug); + + } + System.out.println("邮件发送完毕!"); + } + + private void setEmailContent(String productDesc, String name) { + mailContent.setFromAddress(); + mailContent.setSMTPHost(); + mailContent.setAltSMTPHost(); + mailContent.setMessage(name,productDesc); + } + +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/bean/ProductInfo.java b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/bean/ProductInfo.java new file mode 100644 index 0000000000..1d18216e7c --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/bean/ProductInfo.java @@ -0,0 +1,33 @@ +package com.coderising.ood.srp.bean; + +/** + * Created by wang on 2017/6/17. + */ + +/** + * 产品信息 + */ +public class ProductInfo { + + private String ProductID; + private String ProductDesc; + + public String getProductID() { + return ProductID; + } + + public String getProductDesc() { + return ProductDesc; + } + + public void setProductID(String productID) { + ProductID = productID; + } + + public void setProductDesc(String productDesc) { + ProductDesc = productDesc; + } + + + +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/bean/UserInfo.java b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/bean/UserInfo.java new file mode 100644 index 0000000000..d8966fa49d --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/bean/UserInfo.java @@ -0,0 +1,28 @@ +package com.coderising.ood.srp.bean; + +/**用户信息类 + * Created by wang on 2017/6/17. + */ + + +public class UserInfo { + + private String name; + private String email; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dao/ProductInfoDAO.java b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dao/ProductInfoDAO.java new file mode 100644 index 0000000000..fd4cbcf6d0 --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dao/ProductInfoDAO.java @@ -0,0 +1,48 @@ +package com.coderising.ood.srp.dao; + +import com.coderising.ood.srp.bean.ProductInfo; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; + +/**产品信息数据访问类 + * Created by wang on 2017/6/17. + */ +public class ProductInfoDAO { + + private List productList = new ArrayList<>(); + + + public void readFile(File file) { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String newLine = br.readLine(); + + while(newLine!=null && newLine!=" ") { + String temp = newLine; + String[] datas = temp.split(" "); + + addProductInfo(datas); + newLine = br.readLine(); + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private void addProductInfo(String[] datas) { + + ProductInfo product = new ProductInfo(); + product.setProductID(datas[0]); + product.setProductDesc(datas[1]); + this.productList.add(product); + } + + public List getProductList(){ + return this.productList; + } +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dao/UserInfoDAO.java b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dao/UserInfoDAO.java new file mode 100644 index 0000000000..30293b62b6 --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dao/UserInfoDAO.java @@ -0,0 +1,58 @@ +package com.coderising.ood.srp.dao; + +import com.coderising.ood.srp.util.DBUtil; +import com.coderising.ood.srp.bean.UserInfo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * Created by wang on 2017/6/17. + */ +public class UserInfoDAO { + + private String sendMailQuery; + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + private List infos = new ArrayList<>(); + + public UserInfoDAO() {} + + + /** + * 查询用户信息,封装UserInfo对象 然后返回 List + * @param productID + * @return + */ + public List queryUserInfo(String productID){ + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + return getUserInfos(); + } + + + private List loadMailingList(){ + return DBUtil.query(sendMailQuery); + } + + private List getUserInfos(){ + List datas = this.loadMailingList(); + + for (HashMap users: datas) { + UserInfo u = new UserInfo(); + u.setName(users.get(NAME_KEY)); + u.setEmail(users.get(EMAIL_KEY)); + infos.add(u); + } + return infos; + } + +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/test/MainTest.java b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/test/MainTest.java new file mode 100644 index 0000000000..e70cdbe80a --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/test/MainTest.java @@ -0,0 +1,60 @@ +package com.coderising.ood.srp.test; + +import com.coderising.ood.srp.*; +import com.coderising.ood.srp.bean.ProductInfo; +import com.coderising.ood.srp.bean.UserInfo; +import com.coderising.ood.srp.dao.ProductInfoDAO; +import com.coderising.ood.srp.dao.UserInfoDAO; +import org.junit.Assert; +import org.junit.Test; + +import java.io.File; +import java.util.List; + +/** + * Created by wang on 2017/6/17. + */ +public class MainTest { + + @Test + public void testReadFile() { + File f = new File("C:\\Users\\wang\\Documents\\ood\\coding2017\\students\\349184132\\ood\\ood-assignment\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"); + ProductInfoDAO pDAO = new ProductInfoDAO(); + pDAO.readFile(f); + Assert.assertEquals("P8756", pDAO.getProductList().get(0).getProductID()); + Assert.assertEquals("iPhone8", pDAO.getProductList().get(0).getProductDesc()); + + Assert.assertEquals("P4955", pDAO.getProductList().get(3).getProductID()); + } + + @Test + public void testUserInfo(){ + File f = new File("C:\\Users\\wang\\Documents\\ood\\coding2017\\students\\349184132\\ood\\ood-assignment\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"); + ProductInfoDAO pDAO = new ProductInfoDAO(); + pDAO.readFile(f); + + List pInfo = pDAO.getProductList(); + + UserInfoDAO uDAO = new UserInfoDAO(); + List userInfos = uDAO.queryUserInfo(pInfo.get(0).getProductID()); + Assert.assertEquals("User1",userInfos.get(0).getName()); + + } + + @Test + public void testSendMail(){ + File f = new File("C:\\Users\\wang\\Documents\\ood\\coding2017\\students\\349184132\\ood\\ood-assignment\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"); + ProductInfoDAO pDAO = new ProductInfoDAO(); + pDAO.readFile(f); + + List pInfo = pDAO.getProductList(); + + UserInfoDAO uDAO = new UserInfoDAO(); + List userInfos = uDAO.queryUserInfo(pInfo.get(0).getProductID()); + + MailContent mCont = new MailContent(); + PromotionMail pMail = new PromotionMail(pInfo,userInfos,mCont); + pMail.sendEMail(); + } + +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/DBUtil.java b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/DBUtil.java new file mode 100644 index 0000000000..a23198fcea --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp.util; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java new file mode 100644 index 0000000000..bd8dcba4f2 --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java @@ -0,0 +1,33 @@ +package com.coderising.ood.srp.util; + +public class MailUtil { + + + + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + public static void sendEmail(String toAddress, String fromAddress, String subjuect, String message, String smtpHost, String altSmtpHost, boolean debug){ + try{ + sendEmail(toAddress, fromAddress, subjuect, message, smtpHost, debug); + }catch (Exception e){ + try{ + sendEmail(toAddress, fromAddress, subjuect, message, altSmtpHost ,debug); + }catch (Exception e1){ + System.out.println("发送邮件失败!"); + } + } + } + + +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/srp/Configuration.java b/students/349184132/ood/ood-assignment/src/main/java/srp/Configuration.java new file mode 100644 index 0000000000..3a17cdd457 --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/srp/Configuration.java @@ -0,0 +1,23 @@ +package srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/srp/ConfigurationKeys.java b/students/349184132/ood/ood-assignment/src/main/java/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..ef3a07a354 --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/srp/DBUtil.java b/students/349184132/ood/ood-assignment/src/main/java/srp/DBUtil.java new file mode 100644 index 0000000000..912bebf080 --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/srp/DBUtil.java @@ -0,0 +1,25 @@ +package srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/srp/MailUtil.java b/students/349184132/ood/ood-assignment/src/main/java/srp/MailUtil.java new file mode 100644 index 0000000000..556976f5c9 --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/srp/MailUtil.java @@ -0,0 +1,18 @@ +package srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/srp/PromotionMail.java b/students/349184132/ood/ood-assignment/src/main/java/srp/PromotionMail.java new file mode 100644 index 0000000000..19aae203dc --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/srp/PromotionMail.java @@ -0,0 +1,192 @@ +package srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery = null; + + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected String productID = null; + protected String productDesc = null; + + private static Configuration config; + + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + File f = new File("C:\\Users\\wang\\Documents\\ood\\coding2017\\students\\349184132\\ood\\ood-assignment\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); // 读取产品信息 + + + config = new Configuration(); // 封装的邮件地址 + + + setSMTPHost(); // 通过Config 对象来设置 host + setAltSMTPHost(); // 设置备用host // 不应该暴露出来 封装在 setSMTPHost 中 + + + setFromAddress(); // 设置 源地址 + + + setLoadQuery(); // 向数据库中查询 目标地址 + + sendEMails(mailDebug, loadMailingList()); // 发送邮件 + + + } + + + + + protected void setProductID(String productID) + { + this.productID = productID; + + } + + protected String getproductID() + { + return productID; + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected void setSMTPHost() + { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() + { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + protected void setFromAddress() + { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setMessage(HashMap userInfo) throws IOException + { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + + + + } + + + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + private void setProductDesc(String desc) { + this.productDesc = desc; + } + + + protected void configureEMail(HashMap userInfo) throws IOException + { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList == null) { + System.out.println("没有邮件发送"); + }else { + + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } catch (Exception e) { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + } + + + } +} diff --git a/students/349184132/ood/ood-assignment/src/main/java/srp/product_promotion.txt b/students/349184132/ood/ood-assignment/src/main/java/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/349184132/ood/ood-assignment/src/main/java/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/360682644/ood-assignment/pom.xml b/students/360682644/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/360682644/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..e17b664d48 --- /dev/null +++ b/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + public static final String EMAIL_ADMIN = "email.admin"; + private Map configurations = new HashMap(); + private static Configuration configuration = new Configuration(); + { + configurations.put(EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + return configurations.get(key); + } + + public static Configuration getInstance(){ + return configuration; + } +} diff --git a/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..e6f0ca21cb --- /dev/null +++ b/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,24 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql, Product product){ + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + MailReceiver receiver = new MailReceiver(); + receiver.setName("User" + i); + receiver.setEmail("aa@bb.com"); + receiver.setMessage(product); + receiver.setSubject(product); + userList.add(receiver); + } + return userList; + } +} diff --git a/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/IMailable.java b/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/IMailable.java new file mode 100644 index 0000000000..019a96394e --- /dev/null +++ b/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/IMailable.java @@ -0,0 +1,10 @@ +package com.coderising.ood.srp; + +/** + * Created by 360682644 on 2017/6/13. + */ +public interface IMailable { + + String toEmailText(String... params); + String toEmailSubject(String... params); +} diff --git a/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/MailHosts.java b/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/MailHosts.java new file mode 100644 index 0000000000..72a39d0601 --- /dev/null +++ b/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/MailHosts.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by 360682644 on 2017/6/13. + */ +public class MailHosts { + + private List hosts = new ArrayList(); + { + hosts.add("smtp.163.com"); + hosts.add("smtp1.163.com"); + } + + public List getHosts() { + return hosts; + } + public void setHosts(List hosts) { + this.hosts = hosts; + } +} diff --git a/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/MailReceiver.java b/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/MailReceiver.java new file mode 100644 index 0000000000..250f594a89 --- /dev/null +++ b/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/MailReceiver.java @@ -0,0 +1,38 @@ +package com.coderising.ood.srp; + +/** + * Created by 360682644 on 2017/6/13. + */ +public class MailReceiver { + private String name; + private String email; + private String message; + private String subject; + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + public String getMessage() { + return message; + } + public void setMessage(IMailable IMailable) { + message = IMailable.toEmailText(name); + } + public void setSubject(IMailable IMailable) { + subject = IMailable.toEmailSubject(null); + } + public void setMessage(String message) { + this.message = message; + } + public String getSubject() { + return subject; + } +} diff --git a/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/MailSender.java b/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/MailSender.java new file mode 100644 index 0000000000..4d22aff9c5 --- /dev/null +++ b/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/MailSender.java @@ -0,0 +1,87 @@ +package com.coderising.ood.srp; + +import org.junit.Assert; + +import java.io.*; +import java.util.*; + +public class MailSender { + + protected MailHosts hosts = null; + protected String fromAddress = null; + protected InputStream is = null; + protected List receivers = null; + private Configuration config = Configuration.getInstance(); + + public void init() throws Exception { + setSMTPHost(); + setFromAddress(); + } + + protected MailSender setEmailInput(InputStream is) throws IOException { + this.is = is; + return this; + } + + protected MailSender setReceiver() throws IOException { + Assert.assertNotNull("is cannot be null", is); + List products = read(is); + receivers = new ArrayList(); + for (Product product : products) { + receivers.addAll(ReceiverService.getInstance().loadMailingList(product)); + } + return this; + } + + protected void setSMTPHost() { + hosts = new MailHosts(); + } + + protected void setFromAddress() { + fromAddress = config.getProperty(Configuration.EMAIL_ADMIN); + } + + protected List read(InputStream is) throws IOException { + BufferedReader br = null; + List products = new ArrayList(); + try { + br = new BufferedReader(new InputStreamReader(is)); + String temp; + while ((temp = br.readLine()) != null) { + String[] data = temp.split(" "); + Product product = new Product(); + product.setProductID(data[0]); + product.setProductDesc(data[1]); + products.add(product); + System.out.println("产品ID = " + product.getProductID() + "\n"); + System.out.println("产品描述 = " + product.getProductDesc() + "\n"); + } + } catch (IOException e) { + throw e; + } finally { + br.close(); + } + return products; + } + + protected void send() throws IOException { + System.out.println("开始发送邮件"); + if (receivers == null || receivers.isEmpty()) { + System.out.println("没有邮件发送"); + return; + } + for (MailReceiver receiver : receivers) { + MailUtil.sendEmail(receiver.getEmail(), fromAddress, receiver.getSubject(), receiver.getMessage(), hosts); + } + } + + public static void main(String[] args) throws Exception { + + File f = new File("D:\\coding2017\\students\\360682644\\ood-assignment\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"); + MailSender pe = new MailSender(); + pe.init(); + pe.setEmailInput(new FileInputStream(f)) + .setReceiver() + .send(); + } +} diff --git a/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..2d4545cf06 --- /dev/null +++ b/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,21 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, MailHosts smtpHosts) { + for(String hosts : smtpHosts.getHosts()) { + try { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + break; + } catch (Exception e) { + System.err.println(String.format("通过SMTP服务器(%s)发送邮件失败: %s", hosts,e.getMessage())); + } + } + } +} diff --git a/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java b/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..51dc9ea460 --- /dev/null +++ b/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,28 @@ +package com.coderising.ood.srp; + +/** + * Created by 360682644 on 2017/6/13. + */ +public class Product implements IMailable { + private String productID = null; + private String productDesc = null; + + public String getProductID() { + return productID; + } + public void setProductID(String productID) { + this.productID = productID; + } + public String getProductDesc() { + return productDesc; + } + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + public String toEmailText(String... params) { + return "尊敬的 "+ params[0] +", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + } + public String toEmailSubject(String... params) { + return "您关注的产品降价了"; + } +} diff --git a/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/ReceiverService.java b/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/ReceiverService.java new file mode 100644 index 0000000000..f5ea863389 --- /dev/null +++ b/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/ReceiverService.java @@ -0,0 +1,24 @@ +package com.coderising.ood.srp; + +import java.util.List; + +/** + * Created by 360682644 on 2017/6/13. + */ +public class ReceiverService { + + private final static ReceiverService service = new ReceiverService(); + public static ReceiverService getInstance(){return service;} + + public List loadMailingList(Product product){ + return DBUtil.query(getLoadQuery(), product); + } + + public String getLoadQuery(){ + String query = "Select name from subscriptions " + + "where product_id= ? " + + "and send_mail=1 "; + System.out.println("loadQuery set"); + return query; + } +} diff --git a/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/360682644/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/370677080/ood-assignment/pom.xml b/students/370677080/ood-assignment/pom.xml new file mode 100644 index 0000000000..d1ed73a0bf --- /dev/null +++ b/students/370677080/ood-assignment/pom.xml @@ -0,0 +1,37 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + org.jetbrains + annotations-java5 + RELEASE + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/370677080/ood-assignment/src/main/java/com/coderising/ood/srp/DO/ProductDetail.java b/students/370677080/ood-assignment/src/main/java/com/coderising/ood/srp/DO/ProductDetail.java new file mode 100644 index 0000000000..7b3041a000 --- /dev/null +++ b/students/370677080/ood-assignment/src/main/java/com/coderising/ood/srp/DO/ProductDetail.java @@ -0,0 +1,26 @@ +package com.coderising.ood.srp.DO; + +/** + * 产品信息数据类。 + * @since 06.18.2017 + */ +public class ProductDetail { + private String id; + private String description; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } +} diff --git a/students/370677080/ood-assignment/src/main/java/com/coderising/ood/srp/DO/UserInfo.java b/students/370677080/ood-assignment/src/main/java/com/coderising/ood/srp/DO/UserInfo.java new file mode 100644 index 0000000000..14eff3c68a --- /dev/null +++ b/students/370677080/ood-assignment/src/main/java/com/coderising/ood/srp/DO/UserInfo.java @@ -0,0 +1,29 @@ +package com.coderising.ood.srp.DO; + +/** + * 用户数据类。 + * @since 06.18.2017 + */ +public class UserInfo { + private String name; + private String email; + private String productDesc; + + public UserInfo(String name, String email, String productDesc){ + this.name = name; + this.email = email; + this.productDesc = productDesc; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + public String getProductDesc() { + return productDesc; + } +} diff --git a/students/370677080/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/370677080/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..2ec66a4d47 --- /dev/null +++ b/students/370677080/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,43 @@ +package com.coderising.ood.srp; + +import com.coderising.ood.srp.DO.ProductDetail; +import com.coderising.ood.srp.DO.UserInfo; +import com.coderising.ood.srp.util.DBUtil; +import com.coderising.ood.srp.util.FileUtil; +import com.coderising.ood.srp.util.MailUtil; + +import java.io.FileNotFoundException; +import java.util.List; + +/** + * 程序入口点。 + * @since 06.19.2017 + */ +public class PromotionMail { + + public static void main(String[] args){ + final String FILE_PATH = "test.txt"; + FileUtil fileUtil; + + //尝试打开促销文件 + try { + fileUtil = new FileUtil(FILE_PATH); + } catch (FileNotFoundException e){ + System.out.println("促销文件打开失败,请确认文件路径!"); + return; + } + + sendAllEMails(fileUtil); + + fileUtil.close(); + } + + + private static void sendAllEMails(FileUtil fileUtil){ + while (fileUtil.hasNext()) { + ProductDetail productDetail = fileUtil.getNextProduct(); + List usersList = DBUtil.query(productDetail); + MailUtil.sendEmails(usersList); + } + } +} diff --git a/students/370677080/ood-assignment/src/main/java/com/coderising/ood/srp/util/DBUtil.java b/students/370677080/ood-assignment/src/main/java/com/coderising/ood/srp/util/DBUtil.java new file mode 100644 index 0000000000..e1e0012855 --- /dev/null +++ b/students/370677080/ood-assignment/src/main/java/com/coderising/ood/srp/util/DBUtil.java @@ -0,0 +1,38 @@ +package com.coderising.ood.srp.util; +import com.coderising.ood.srp.DO.ProductDetail; +import com.coderising.ood.srp.DO.UserInfo; + +import java.util.*; + +/** + * 数据库操作类。 + * 管理数据库连接,查询等操作。 + * @since 06.19.2017 + */ +public class DBUtil { + + //TODO 此处添加数据库连接信息 + + + /** + * 应该从数据库读, 但是简化为直接生成。 + * 给一个产品详情,返回一个Array List记载所有订阅该产品的用户信息(名字,邮箱,订阅的产品名称)。 + * @param productDetail 传产品详情。产品id用来查询数据库。产品名称用于和用户信息绑定 + * @return 返回数据库中所有的查询到的结果。 + */ + public static List query(ProductDetail productDetail){ + if (productDetail == null || productDetail.getId() == null) + return new ArrayList<>(); + + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productDetail.getId() +"' " + + "and send_mail=1 "; + //假装用sendMilQuery查了数据库,生成了userList作为查询结果 + List userList = new ArrayList<>(); + for (int i = 1; i <= 3; i++) { + UserInfo newInfo = new UserInfo("User" + i,"aa@bb.com", productDetail.getDescription()); + userList.add(newInfo); + } + return userList; + } +} diff --git a/students/370677080/ood-assignment/src/main/java/com/coderising/ood/srp/util/FileUtil.java b/students/370677080/ood-assignment/src/main/java/com/coderising/ood/srp/util/FileUtil.java new file mode 100644 index 0000000000..991f81a537 --- /dev/null +++ b/students/370677080/ood-assignment/src/main/java/com/coderising/ood/srp/util/FileUtil.java @@ -0,0 +1,49 @@ +package com.coderising.ood.srp.util; + + +import com.coderising.ood.srp.DO.ProductDetail; + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.Scanner; + +/** + * 文件操作类。 + * 负责文件句柄的维护。 + * 此类会打开促销文件,促销文件默认按照: + * "id" 空格 "产品名称" + * 进行存储,每行一条促销信息。 + * @since 06.19.2017 + */ +public class FileUtil { + private Scanner scanner; + + + public FileUtil(String filePath) throws FileNotFoundException { + scanner = new Scanner(new File(filePath)); + } + + public ProductDetail getNextProduct(){ + String wholeInfo; + ProductDetail nextProduct = new ProductDetail(); + wholeInfo = scanner.nextLine(); + + String[] splitInfo = wholeInfo.split(" "); + if (splitInfo.length < 2) + return nextProduct; + + //促销文件按照 - "id" 空格 "产品名称" 进行记录的 + nextProduct.setId(splitInfo[0]); + nextProduct.setDescription(splitInfo[1]); + + return nextProduct; + } + + public boolean hasNext(){ + return scanner.hasNextLine(); + } + + public void close(){ + scanner.close(); + } +} diff --git a/students/370677080/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java b/students/370677080/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java new file mode 100644 index 0000000000..065286d4f9 --- /dev/null +++ b/students/370677080/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java @@ -0,0 +1,97 @@ +package com.coderising.ood.srp.util; + +import com.coderising.ood.srp.DO.UserInfo; + +import java.util.List; + + +/** + * 邮件发送类。 + * 管理邮箱连接,发送等操作。 + * @since 06.19.2017 + */ +public class MailUtil { + + /** + * SMTP连接失败异常。 + * 可用getMessage()获得异常内容。 + */ + public static class SMTPConnectionFailedException extends Throwable{ + public SMTPConnectionFailedException(String message){ + super(message); + } + } + + /** + * 主SMTP服务器地址 + */ + public static final String SMTP_SERVER = "smtp.163.com"; + + /** + * 备用SMTP服务器地址 + */ + public static final String ALT_SMTP_SERVER = "smtp1.163.com"; + + /** + * 以哪个邮箱地址发送给用户 + */ + public static final String EMAIL_ADMIN = "admin@company.com"; + + + /** + * 邮件发送操作。 + * 将降价促销邮件逐个发送给用户信息表中对应的用户。 + * 捕获SMTPConnectionFailedException。提示手动发送。并继续发送下一封邮件。 + * @param usersList 用户信息表。包含用户姓名,邮箱和订阅产品名称。 + */ + public static void sendEmails(List usersList){ + if (usersList == null) { + System.out.println("没有邮件发送"); + return; + } + + for (UserInfo info : usersList){ + if (!info.getEmail().isEmpty()) { + String emailInfo = generatePromotionEmail(info); + try { + sendPromotionEmail(emailInfo); + } catch (SMTPConnectionFailedException e){ + System.out.println("SMTP主副服务器连接失败,请手动发送以下邮件: \n"); + System.out.println(e.getMessage()); + } + } + } + } + + /** + * 假装在发邮件。默认使用主SMTP发送,若发送失败则使用备用SMTP发送。 + * 仍然失败,则抛出SMTPConnectFailException异常。 + * @param emailInfo 要发送的邮件内容 + * @throws SMTPConnectionFailedException 若主副SMTP服务器均连接失败,抛出异常。异常中包含完整的发送失败的邮件内容。可通过getMessage()方法获得邮件内容。 + */ + private static void sendPromotionEmail(String emailInfo) throws SMTPConnectionFailedException{ + //默认以SMTP_SERVER 发送 + //如果发送失败以ALT_SMTP_SERVER 重新发送 + //如果还失败,throw new SMTPConnectionFailedException(emailInfo). + } + + /** + * 根据用户信息生成促销邮件内容。 + * @param userInfo 用户信息。 + * @return 返回生成的邮件。 + */ + private static String generatePromotionEmail(UserInfo userInfo){ + StringBuilder buffer = new StringBuilder(); + + buffer.append("From:").append(EMAIL_ADMIN).append("\n"); + buffer.append("To:").append(userInfo.getEmail()).append("\n"); + buffer.append("Subject:").append("您关注的产品降价了").append("\n"); + buffer.append("Content:").append("尊敬的").append(userInfo.getName()); + buffer.append(", 您关注的产品 ").append(userInfo.getProductDesc()); + buffer.append(" 降价了,欢迎购买!").append("\n"); + + System.out.println(buffer.toString()); + + return buffer.toString(); + } +} diff --git a/students/370677080/ood-assignment/test.txt b/students/370677080/ood-assignment/test.txt new file mode 100644 index 0000000000..cb2d21edc4 --- /dev/null +++ b/students/370677080/ood-assignment/test.txt @@ -0,0 +1,5 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 +p123 diff --git a/students/382266293/src/ood/srp/MailSender.java b/students/382266293/src/ood/srp/MailSender.java new file mode 100644 index 0000000000..83e3fbef85 --- /dev/null +++ b/students/382266293/src/ood/srp/MailSender.java @@ -0,0 +1,52 @@ +package ood.srp; + +import ood.srp.bean.Mail; +import ood.srp.bean.Product; +import ood.srp.config.Configuration; +import ood.srp.config.ServerConfig; +import ood.srp.dao.MailDAO; +import ood.srp.dao.ProductDAO; +import ood.srp.util.MailUtil; + +import java.io.File; +import java.util.List; + +/** + * Created by onlyLYJ on 2017/6/12. + */ +public abstract class MailSender { + + protected static ServerConfig sc = new Configuration().config().getServerConfig(); + protected static MailDAO mailDAO = new MailDAO(); + protected static ProductDAO productDAO = new ProductDAO(); + protected boolean debug; + + protected List prepareMails(File productFile) throws Exception { + + List products = productDAO.list(productFile); + List mailingList = mailDAO.loadMailingList(products); + setMailContext(mailingList); + + return mailingList; + } + + protected abstract void setMailContext(List mailingList); + + protected void setDebug(boolean debug) { + this.debug = debug; + } + + protected void sendEMails(List mailingList) { + + if (mailDAO.isValide(mailingList)) { + System.out.println("开始发送邮件"); + + for (Mail mail : mailingList) { + MailUtil.send(mail, sc); + } + } + + } + + +} diff --git a/students/382266293/src/ood/srp/PromotionMail.java b/students/382266293/src/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..c3d6520a67 --- /dev/null +++ b/students/382266293/src/ood/srp/PromotionMail.java @@ -0,0 +1,40 @@ +package ood.srp; + +import ood.srp.bean.Mail; + +import java.io.File; +import java.util.List; + +public class PromotionMail extends MailSender { + + private static final String EMAIL_ADMIN = "email.admin"; + + public static void main(String[] args) throws Exception { + + File f = new File("E:\\git\\coding2017\\students\\382266293\\src\\com\\coderising\\ood\\srp\\data\\product_promotion.txt"); + MailSender pm = new PromotionMail(); + pm.setDebug(false); + List mailList = pm.prepareMails(f); + pm.sendEMails(mailList); + + } + + @Override + protected void setMailContext(List mailingList) { + + String subject = "您关注的产品降价了"; + + for (Mail mail : mailingList) { + mail.setFromAddress(EMAIL_ADMIN); + mail.setSubject(subject); + String name = mail.getSubscriber().getName(); + String productDesc = mail.getProduct().getProductDesc(); + String message = "尊敬的 " + name + ", 您关注的产品 " + productDesc + " 降价了,欢迎购买!"; + mail.setSubject(subject); + mail.setMessage(message); + } + + } + + +} diff --git a/students/382266293/src/ood/srp/bean/Mail.java b/students/382266293/src/ood/srp/bean/Mail.java new file mode 100644 index 0000000000..91e1363140 --- /dev/null +++ b/students/382266293/src/ood/srp/bean/Mail.java @@ -0,0 +1,53 @@ +package ood.srp.bean; + +/** + * Created by onlyLYJ on 2017/6/12. + */ +public class Mail { + + private String fromAddress; + private String subject; + private String message; + private Product product; + private Subscriber subscriber; + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public Product getProduct() { + return product; + } + + public void setProduct(Product product) { + this.product = product; + } + + public Subscriber getSubscriber() { + return subscriber; + } + + public void setSubscriber(Subscriber subscriber) { + this.subscriber = subscriber; + } +} diff --git a/students/382266293/src/ood/srp/bean/Product.java b/students/382266293/src/ood/srp/bean/Product.java new file mode 100644 index 0000000000..3b879b274f --- /dev/null +++ b/students/382266293/src/ood/srp/bean/Product.java @@ -0,0 +1,38 @@ +package ood.srp.bean; + +import java.util.List; + +/** + * Created by onlyLYJ on 2017/6/12. + */ +public class Product { + + private String productID; + private String productDesc; + private List subscribers; + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + + public List getSubscribers() { + return subscribers; + } + + public void setSubscribers(List subscribers) { + this.subscribers = subscribers; + } + +} diff --git a/students/382266293/src/ood/srp/bean/Subscriber.java b/students/382266293/src/ood/srp/bean/Subscriber.java new file mode 100644 index 0000000000..a2a2641622 --- /dev/null +++ b/students/382266293/src/ood/srp/bean/Subscriber.java @@ -0,0 +1,27 @@ +package ood.srp.bean; + +/** + * Created by onlyLYJ on 2017/6/12. + */ +public class Subscriber { + + private String name; + private String mailAddress; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getMailAddress() { + return mailAddress; + } + + public void setMailAddress(String mailAddress) { + this.mailAddress = mailAddress; + } + +} diff --git a/students/382266293/src/ood/srp/config/Configuration.java b/students/382266293/src/ood/srp/config/Configuration.java new file mode 100644 index 0000000000..59bf7bfbd1 --- /dev/null +++ b/students/382266293/src/ood/srp/config/Configuration.java @@ -0,0 +1,37 @@ +package ood.srp.config; + +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + private static final String SMTP_SERVER = "smtp.server"; + private static final String ALT_SMTP_SERVER = "alt.smtp.server"; + + + private static Map configurations = null; + + public Configuration config() { + + configurations = new HashMap<>(); + configurations.put(SMTP_SERVER, "smtp.163.com"); + configurations.put(ALT_SMTP_SERVER, "smtp1.163.com"); + + return this; + } + + public ServerConfig getServerConfig() { + + ServerConfig sc = new ServerConfig(); + + sc.setSmtpHost(getProperty(SMTP_SERVER)); + sc.setAltSmtpHost(getProperty(ALT_SMTP_SERVER)); + + return sc; + } + + private String getProperty(String key) { + return configurations.get(key); + } + +} diff --git a/students/382266293/src/ood/srp/config/ServerConfig.java b/students/382266293/src/ood/srp/config/ServerConfig.java new file mode 100644 index 0000000000..2c8c52a79a --- /dev/null +++ b/students/382266293/src/ood/srp/config/ServerConfig.java @@ -0,0 +1,32 @@ +package ood.srp.config; + +/** + * Created by onlyLYJ on 2017/6/12. + */ +public class ServerConfig { + + private String smtpHost; + private String altSmtpHost; + + public String getSmtpHost() { + return smtpHost; + } + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + + +} + + + + diff --git a/students/382266293/src/ood/srp/dao/MailDAO.java b/students/382266293/src/ood/srp/dao/MailDAO.java new file mode 100644 index 0000000000..c80eb7f7bc --- /dev/null +++ b/students/382266293/src/ood/srp/dao/MailDAO.java @@ -0,0 +1,39 @@ +package ood.srp.dao; + +import ood.srp.bean.Mail; +import ood.srp.bean.Product; +import ood.srp.bean.Subscriber; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by onlyLYJ on 2017/6/12. + */ +public class MailDAO { + + public List loadMailingList(List products) throws Exception { + + List mails = new ArrayList<>(); + + for (Product p : products) { + List subscribers = new UserDAO().list(p); + + for (Subscriber s : subscribers) { + Mail mail = new Mail(); + mail.setProduct(p); + mail.setSubscriber(s); + mails.add(mail); + } + } + return mails; + } + + public boolean isValide(List mailingList) { + if (null == mailingList || mailingList.isEmpty()) { + throw new RuntimeException("没有邮件发送"); + } + return true; + } + +} diff --git a/students/382266293/src/ood/srp/dao/ProductDAO.java b/students/382266293/src/ood/srp/dao/ProductDAO.java new file mode 100644 index 0000000000..39312cf24a --- /dev/null +++ b/students/382266293/src/ood/srp/dao/ProductDAO.java @@ -0,0 +1,49 @@ +package ood.srp.dao; + +import ood.srp.bean.Product; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Created by onlyLYJ on 2017/6/12. + */ +public class ProductDAO { + + public List list(File productFile) throws IOException // @02C + { + + System.out.println(productFile); + List products = new ArrayList<>(); + + System.out.println("开始导入产品清单"); + try (BufferedReader br = new BufferedReader(new FileReader(productFile))) { + String temp = null; + while (null != (temp = br.readLine())) { + String[] data = temp.split(" "); + + String productID = data[0]; + String productDesc = data[1]; + + Product p = new Product(); + p.setProductID(productID); + p.setProductDesc(productDesc); + System.out.println("产品ID = " + productID); + System.out.println("产品描述 = " + productDesc + "\r\n"); + + products.add(p); + } + } catch (IOException e) { + throw new IOException(e.getMessage()); + } + + + return products; + } + + +} diff --git a/students/382266293/src/ood/srp/dao/UserDAO.java b/students/382266293/src/ood/srp/dao/UserDAO.java new file mode 100644 index 0000000000..91ebd5cd23 --- /dev/null +++ b/students/382266293/src/ood/srp/dao/UserDAO.java @@ -0,0 +1,31 @@ +package ood.srp.dao; + +import ood.srp.bean.Product; +import ood.srp.bean.Subscriber; +import ood.srp.util.DBUtil; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by onlyLYJ on 2017/6/12. + */ +public class UserDAO { + + public List list(Product p) throws Exception { + + DBUtil.setLoadQuery(p); + + List subscribers = new ArrayList<>(); + for (int i = 1; i <= 3; i++) { + Subscriber s = new Subscriber(); + s.setName("user" + i); + s.setMailAddress(s.getName() + "@amazon.com"); + subscribers.add(s); + + } + return subscribers; + + } + +} diff --git a/students/382266293/src/ood/srp/data/product_promotion.txt b/students/382266293/src/ood/srp/data/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/382266293/src/ood/srp/data/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/382266293/src/ood/srp/util/DBUtil.java b/students/382266293/src/ood/srp/util/DBUtil.java new file mode 100644 index 0000000000..9d14f02cba --- /dev/null +++ b/students/382266293/src/ood/srp/util/DBUtil.java @@ -0,0 +1,16 @@ +package ood.srp.util; + +import ood.srp.bean.Product; + +public class DBUtil { + + public static void setLoadQuery(Product p) { + + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + p.getProductID() + "' " + + "and send_mail=1 "; + + System.out.println("loadQuery set"); + } + +} diff --git a/students/382266293/src/ood/srp/util/MailUtil.java b/students/382266293/src/ood/srp/util/MailUtil.java new file mode 100644 index 0000000000..d41af6667e --- /dev/null +++ b/students/382266293/src/ood/srp/util/MailUtil.java @@ -0,0 +1,32 @@ +package ood.srp.util; + +import ood.srp.bean.Mail; +import ood.srp.config.ServerConfig; + +public class MailUtil { + + public static void send(Mail mail, ServerConfig sc) { + try { + sendEmail(mail, sc.getSmtpHost()); + } catch (Exception e) { + try { + sendEmail(mail, sc.getAltSmtpHost()); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + public static void sendEmail(Mail mail, String SmtpHost) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(mail.getFromAddress()).append("\n"); + buffer.append("To:").append(mail.getSubscriber().getMailAddress()).append("\n"); + buffer.append("Subject:").append(mail.getSubject()).append("\n"); + buffer.append("Content:").append(mail.getMessage()).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/382266293/src/pom.xml b/students/382266293/src/pom.xml new file mode 100644 index 0000000000..2bf55e64c9 --- /dev/null +++ b/students/382266293/src/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/382266293/src/src/main/java/com/coderising/ood/srp/Configuration.java b/students/382266293/src/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..db20a8a5d5 --- /dev/null +++ b/students/382266293/src/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,27 @@ +package src.main.java.com.coderising.ood.srp; + +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + + static { + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/382266293/src/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/382266293/src/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..4946f09f38 --- /dev/null +++ b/students/382266293/src/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package src.main.java.com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/382266293/src/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/382266293/src/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..6edf953e19 --- /dev/null +++ b/students/382266293/src/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,27 @@ +package src.main.java.com.coderising.ood.srp; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * + * @param sql + * @return + */ + public static List query(String sql) { + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/382266293/src/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/382266293/src/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..3b6716de70 --- /dev/null +++ b/students/382266293/src/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package src.main.java.com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/382266293/src/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/382266293/src/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..e23638c4b2 --- /dev/null +++ b/students/382266293/src/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,172 @@ +package src.main.java.com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + private static Configuration config; + protected String sendMailQuery = null; + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + protected String productID = null; + protected String productDesc = null; + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + + + config = new Configuration(); + + setSMTPHost(); + setAltSMTPHost(); + + + setFromAddress(); + + + setLoadQuery(); + + sendEMails(mailDebug, loadMailingList()); + + + } + + public static void main(String[] args) throws Exception { + + File f = new File("E:\\git\\coding2017\\students\\382266293\\src\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + protected void setProductID(String productID) { + this.productID = productID; + + } + + protected String getproductID() { + return productID; + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID + "' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected void setSMTPHost() { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + protected void setFromAddress() { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setMessage(HashMap userInfo) throws IOException { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 " + name + ", 您关注的产品 " + productDesc + " 降价了,欢迎购买!"; + + + } + + + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + private void setProductDesc(String desc) { + this.productDesc = desc; + } + + + protected void configureEMail(HashMap userInfo) throws IOException { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } catch (Exception e) { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/382266293/src/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/382266293/src/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/382266293/src/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/382266293/src/test.java b/students/382266293/src/test.java new file mode 100644 index 0000000000..56d4d4396e --- /dev/null +++ b/students/382266293/src/test.java @@ -0,0 +1,9 @@ +/** + * Created by onlyLYJ on 2017/6/11. + */ + + +public class test { + + +} diff --git a/students/395135865/ood/ood-assignment/pom.xml b/students/395135865/ood/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/395135865/ood/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/395135865/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/395135865/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..d2205cdbe7 --- /dev/null +++ b/students/395135865/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,22 @@ +package com.coderising.ood.srp; + +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + + static { + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + */ + public String getProperty(String key) { + return configurations.get(key); + } +} diff --git a/students/395135865/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/395135865/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/395135865/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/395135865/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/395135865/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/395135865/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/395135865/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/395135865/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..9f9e749af7 --- /dev/null +++ b/students/395135865/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/395135865/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/395135865/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..781587a846 --- /dev/null +++ b/students/395135865/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,199 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery = null; + + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected String productID = null; + protected String productDesc = null; + + private static Configuration config; + + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + + + config = new Configuration(); + + setSMTPHost(); + setAltSMTPHost(); + + + setFromAddress(); + + + setLoadQuery(); + + sendEMails(mailDebug, loadMailingList()); + + + } + + + + + protected void setProductID(String productID) + { + this.productID = productID; + + } + + protected String getproductID() + { + return productID; + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected void setSMTPHost() + { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() + { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + protected void setFromAddress() + { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setMessage(HashMap userInfo) throws IOException + { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + + + + } + + + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + private void setProductDesc(String desc) { + this.productDesc = desc; + } + + + protected void configureEMail(HashMap userInfo) throws IOException + { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try + { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } + + else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/Email.java b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/Email.java new file mode 100644 index 0000000000..7943a5581a --- /dev/null +++ b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/Email.java @@ -0,0 +1,56 @@ +package com.thomsom.coderising.ood.srp; + +/** + * the email message entity class. + * + * @author Thomson Tang + * @version Created: 23/06/2017. + */ +public class Email { + private String fromAddress; + private String toAddress; + private String subject; + private String content; + + public Email() { + } + + public Email(String fromAddress, String toAddress, String subject, String content) { + this.fromAddress = fromAddress; + this.toAddress = toAddress; + this.subject = subject; + this.content = content; + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } +} diff --git a/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/Product.java b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..9fca6b61db --- /dev/null +++ b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/Product.java @@ -0,0 +1,44 @@ +package com.thomsom.coderising.ood.srp; + +/** + * Product entity class. + * + * @author Thomson Tang + * @version Created: 23/06/2017. + */ +public class Product { + private String productId; + private String productName; + + private Product() { + } + + private Product(String productId, String productName) { + this.productId = productId; + this.productName = productName; + } + + public static Product newInstance(String productId, String productName) { + return new Product(productId, productName); + } + + public static Product newInstance() { + return new Product(); + } + + public String getProductId() { + return productId; + } + + public void setProductId(String productId) { + this.productId = productId; + } + + public String getProductName() { + return productName; + } + + public void setProductName(String productName) { + this.productName = productName; + } +} diff --git a/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/PromotionTask.java b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/PromotionTask.java new file mode 100644 index 0000000000..91fd78926a --- /dev/null +++ b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/PromotionTask.java @@ -0,0 +1,24 @@ +package com.thomsom.coderising.ood.srp; + +import com.thomsom.coderising.ood.srp.service.EmailService; +import com.thomsom.coderising.ood.srp.service.impl.EmailServiceImpl; + +import java.util.List; + +/** + * 应用场景类: 促销任务 + * + * @author Thomson Tang + * @version Created: 02/07/2017. + */ +public class PromotionTask { + public static void main(String[] args) { + try { + EmailService emailService = new EmailServiceImpl(); + List emails = emailService.createEmails(); + emailService.sendEmails(emails); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/UserInfo.java b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/UserInfo.java new file mode 100644 index 0000000000..bf653eb20d --- /dev/null +++ b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/UserInfo.java @@ -0,0 +1,59 @@ +package com.thomsom.coderising.ood.srp; + +import java.util.ArrayList; +import java.util.List; + +/** + * the user info entity class. + * + * @author Thomson Tang + * @version Created: 23/06/2017. + */ +public class UserInfo { + private String userId; + private String userName; + private String email; + + List products = new ArrayList<>(); + + public UserInfo() { + } + + public UserInfo(String userId, String userName, String email) { + this.userId = userId; + this.userName = userName; + this.email = email; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public List getProducts() { + return products; + } + + public void setProducts(List products) { + this.products = products; + } +} diff --git a/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/EmailService.java b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/EmailService.java new file mode 100644 index 0000000000..d922b9fe0f --- /dev/null +++ b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/EmailService.java @@ -0,0 +1,28 @@ +package com.thomsom.coderising.ood.srp.service; + +import com.thomsom.coderising.ood.srp.Email; + +import java.util.List; + +/** + * 邮件服务 + * + * @author Thomson Tang + * @version Created: 29/06/2017. + */ +public interface EmailService { + /** + * 创建要发送的邮件,相当于写邮件 + * + * @return 返回若干邮件 + * @throws Exception if error + */ + List createEmails() throws Exception; + + /** + * 发送邮件 + * @param emails 要发送的邮件 + * @throws Exception if error occurs + */ + void sendEmails(List emails) throws Exception; +} diff --git a/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/MailSender.java b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/MailSender.java new file mode 100644 index 0000000000..163db708e7 --- /dev/null +++ b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/MailSender.java @@ -0,0 +1,20 @@ +package com.thomsom.coderising.ood.srp.service; + +import com.thomsom.coderising.ood.srp.Email; + +import java.util.List; + +/** + * 邮件发送服务 + * + * @author Thomson Tang + * @version Created: 30/06/2017. + */ +public interface MailSender { + + String getSenderAddress(); + + String getSmtpHost(); + + void sendMail(List emails); +} diff --git a/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/ProductService.java b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/ProductService.java new file mode 100644 index 0000000000..da39ee967e --- /dev/null +++ b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/ProductService.java @@ -0,0 +1,29 @@ +package com.thomsom.coderising.ood.srp.service; + +import com.thomsom.coderising.ood.srp.Product; + +import java.util.List; + +/** + * 商品业务逻辑接口 + * + * @author Thomson Tang + * @version Created: 23/06/2017. + */ +public interface ProductService { + /** + * 查询所有的商品 + * + * @return 商品列表 + * @throws Exception if error + */ + List listProduct() throws Exception; + + /** + * 根据用户查询该用户关注的商品 + * + * @param userId 用户标示符 + * @return 用户关注的商品 + */ + List listSubscriptProduct(String userId); +} diff --git a/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/UserService.java b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/UserService.java new file mode 100644 index 0000000000..5e9716ae6d --- /dev/null +++ b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/UserService.java @@ -0,0 +1,15 @@ +package com.thomsom.coderising.ood.srp.service; + +import com.thomsom.coderising.ood.srp.UserInfo; + +import java.util.List; + +/** + * the user service + * + * @author Thomson Tang + * @version Created: 29/06/2017. + */ +public interface UserService { + List listUser() throws Exception; +} diff --git a/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/impl/EmailServiceImpl.java b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/impl/EmailServiceImpl.java new file mode 100644 index 0000000000..4906b714e3 --- /dev/null +++ b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/impl/EmailServiceImpl.java @@ -0,0 +1,53 @@ +package com.thomsom.coderising.ood.srp.service.impl; + +import com.thomsom.coderising.ood.srp.Email; +import com.thomsom.coderising.ood.srp.Product; +import com.thomsom.coderising.ood.srp.UserInfo; +import com.thomsom.coderising.ood.srp.service.MailSender; +import com.thomsom.coderising.ood.srp.service.EmailService; +import com.thomsom.coderising.ood.srp.service.ProductService; +import com.thomsom.coderising.ood.srp.service.UserService; + +import java.util.ArrayList; +import java.util.List; + +/** + * 邮件服务的实现类 + * + * @author Thomson Tang + * @version Created: 29/06/2017. + */ +public class EmailServiceImpl implements EmailService { + + private UserService userService; + private ProductService productService; + private MailSender mailSender; + + @Override + public List createEmails() throws Exception { + List emailList = new ArrayList<>(); + List userInfoList = userService.listUser(); + userInfoList.forEach(userInfo -> { + Email email = new Email(); + email.setToAddress(userInfo.getEmail()); + email.setSubject("您关注的产品降价了..."); + productService.listSubscriptProduct(userInfo.getUserId()); + email.setContent(buildContent(userInfo)); + emailList.add(email); + }); + + return emailList; + } + + @Override + public void sendEmails(List emails) throws Exception { + mailSender.sendMail(emails); + } + + private String buildContent(UserInfo userInfo) { + List products = productService.listSubscriptProduct(userInfo.getUserId()); + StringBuilder allProduct = new StringBuilder(); + products.stream().forEach(product -> allProduct.append(product).append(",")); + return String.format("尊敬的%s,您关注的产品%s降价了,欢迎购买!", userInfo.getUserName(), allProduct.toString()); + } +} diff --git a/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/impl/MailSenderImpl.java b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/impl/MailSenderImpl.java new file mode 100644 index 0000000000..741f4e2b08 --- /dev/null +++ b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/impl/MailSenderImpl.java @@ -0,0 +1,35 @@ +package com.thomsom.coderising.ood.srp.service.impl; + +import com.coderising.ood.srp.Configuration; +import com.coderising.ood.srp.ConfigurationKeys; +import com.thomsom.coderising.ood.srp.Email; +import com.thomsom.coderising.ood.srp.service.MailSender; + +import java.util.List; + +/** + * 发送邮件的实现类 + * + * @author Thomson Tang + * @version Created: 01/07/2017. + */ +public class MailSenderImpl implements MailSender { + + private Configuration configuration; + + @Override + public String getSenderAddress() { + return configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + @Override + public String getSmtpHost() { + return configuration.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + @Override + public void sendMail(List emails) { + //模拟发送邮件 + emails.forEach(email -> email.setFromAddress(getSenderAddress())); + } +} diff --git a/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/impl/ProductFileServiceImpl.java b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/impl/ProductFileServiceImpl.java new file mode 100644 index 0000000000..1434d92967 --- /dev/null +++ b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/impl/ProductFileServiceImpl.java @@ -0,0 +1,55 @@ +package com.thomsom.coderising.ood.srp.service.impl; + +import com.thomsom.coderising.ood.srp.Product; +import com.thomsom.coderising.ood.srp.service.ProductService; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; + +/** + * the implementation of product service which listing the products by reading from a file. + * + * @author Thomson Tang + * @version Created: 24/06/2017. + */ +public class ProductFileServiceImpl implements ProductService { + private String fileName; + + public ProductFileServiceImpl(String fileName) { + this.fileName = fileName; + } + + @Override + public List listProduct() throws Exception { + List products = new ArrayList<>(); + Path path = Paths.get(getClass().getResource(fileName).toURI()); + Stream lines = Files.lines(path); + lines.forEach(line -> products.add(resolveProduct(line))); + return products; + } + + @Override + public List listSubscriptProduct(String userId) { + return null; + } + + private Product resolveProduct(String line) { + String[] items = line.split(" "); + if (items.length > 2) { + return Product.newInstance(items[0], items[1]); + } + return Product.newInstance(); + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } +} diff --git a/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/impl/UserServiceImpl.java b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/impl/UserServiceImpl.java new file mode 100644 index 0000000000..56bcb3be6e --- /dev/null +++ b/students/395135865/ood/ood-assignment/src/main/java/com/thomsom/coderising/ood/srp/service/impl/UserServiceImpl.java @@ -0,0 +1,26 @@ +package com.thomsom.coderising.ood.srp.service.impl; + +import com.thomsom.coderising.ood.srp.UserInfo; +import com.thomsom.coderising.ood.srp.service.UserService; + +import java.util.ArrayList; +import java.util.List; + +/** + * the implementation of user service. + * + * @author Thomson Tang + * @version Created: 29/06/2017. + */ +public class UserServiceImpl implements UserService { + + @Override + public List listUser() throws Exception { + List userInfos = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + UserInfo userInfo = new UserInfo(String.valueOf(i), "user" + i, String.format("user%d@qq.com", i)); + userInfos.add(userInfo); + } + return userInfos; + } +} diff --git a/students/395135865/ood/ood-assignment/src/main/resources/com/coderising/ood/srp/product_promotion.txt b/students/395135865/ood/ood-assignment/src/main/resources/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/395135865/ood/ood-assignment/src/main/resources/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/395860968/OCP/AbstractNotifier.java b/students/395860968/OCP/AbstractNotifier.java new file mode 100644 index 0000000000..4aaffa4dc3 --- /dev/null +++ b/students/395860968/OCP/AbstractNotifier.java @@ -0,0 +1,10 @@ +package com.company; + +/** + * Created by kenhuang on 2017/6/20. + */ +public abstract class AbstractNotifier { + public void send(String logMsg) { + + } +} diff --git a/students/395860968/OCP/ConsoleUtil.java b/students/395860968/OCP/ConsoleUtil.java new file mode 100644 index 0000000000..e7a1e5e0ad --- /dev/null +++ b/students/395860968/OCP/ConsoleUtil.java @@ -0,0 +1,11 @@ +package com.company; + +/** + * Created by kenhuang on 2017/6/20. + */ +public class ConsoleUtil extends AbstractNotifier { + public void send(String logMsg) { + // TODO Auto-generated method stub + System.out.println("Console send: " + logMsg); + } +} diff --git a/students/395860968/OCP/DateFormatter.java b/students/395860968/OCP/DateFormatter.java new file mode 100644 index 0000000000..37719ae800 --- /dev/null +++ b/students/395860968/OCP/DateFormatter.java @@ -0,0 +1,13 @@ +package com.company; + +/** + * Created by kenhuang on 2017/6/20. + */ +public class DateFormatter extends Formatter { + @Override + public String formatMessage(String msg) { + String txtDate = DateUtil.getCurrentDateAsString(); + return txtDate + " : " + msg; + + } +} diff --git a/students/395860968/OCP/DateUtil.java b/students/395860968/OCP/DateUtil.java new file mode 100644 index 0000000000..5d0e77a475 --- /dev/null +++ b/students/395860968/OCP/DateUtil.java @@ -0,0 +1,10 @@ +package com.company; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return "20170101"; + } + +} diff --git a/students/395860968/OCP/Formatter.java b/students/395860968/OCP/Formatter.java new file mode 100644 index 0000000000..453d2a98d9 --- /dev/null +++ b/students/395860968/OCP/Formatter.java @@ -0,0 +1,10 @@ +package com.company; + +/** + * Created by kenhuang on 2017/6/20. + */ +public class Formatter { + public String formatMessage(String msg) { + return msg; + } +} diff --git a/students/395860968/OCP/Logger.java b/students/395860968/OCP/Logger.java new file mode 100644 index 0000000000..29b4396cb4 --- /dev/null +++ b/students/395860968/OCP/Logger.java @@ -0,0 +1,15 @@ +package com.company; + +public class Logger { + private AbstractNotifier notifier; + private Formatter formatter; + public Logger(Formatter formatter, AbstractNotifier notifier){ + this.formatter = formatter; + this.notifier = notifier; + } + public void log(String msg){ + String logMsg = this.formatter.formatMessage(msg); + notifier.send(logMsg); + } +} + diff --git a/students/395860968/OCP/MailUtil.java b/students/395860968/OCP/MailUtil.java new file mode 100644 index 0000000000..3b38eb1630 --- /dev/null +++ b/students/395860968/OCP/MailUtil.java @@ -0,0 +1,11 @@ +package com.company; + +public class MailUtil extends AbstractNotifier { + + @Override + public void send(String logMsg) { + // TODO Auto-generated method stub + System.out.println("Mail send: " + logMsg); + } + +} diff --git a/students/395860968/OCP/Main.java b/students/395860968/OCP/Main.java new file mode 100644 index 0000000000..cee3424004 --- /dev/null +++ b/students/395860968/OCP/Main.java @@ -0,0 +1,17 @@ +package com.company; + +public class Main { + + public static void main(String[] args) { + // write your code here + ConsoleUtil consoleUtil = new ConsoleUtil(); + Formatter formatter = new Formatter(); + Logger logger = new Logger(formatter,consoleUtil); + logger.log("abc"); + MailUtil mailUtil = new MailUtil(); + DateFormatter dateformatter = new DateFormatter(); + Logger logger2 = new Logger(dateformatter,mailUtil); + logger2.log("efg"); + + } +} diff --git a/students/395860968/OCP/SMSUtil.java b/students/395860968/OCP/SMSUtil.java new file mode 100644 index 0000000000..1bd29a0613 --- /dev/null +++ b/students/395860968/OCP/SMSUtil.java @@ -0,0 +1,10 @@ +package com.company; + +public class SMSUtil extends AbstractNotifier { + + public void send(String logMsg) { + // TODO Auto-generated method stub + System.out.println("SMS send: " + logMsg); + } + +} diff --git a/students/395860968/SRP/Configuration.java b/students/395860968/SRP/Configuration.java new file mode 100644 index 0000000000..44c566fcaa --- /dev/null +++ b/students/395860968/SRP/Configuration.java @@ -0,0 +1,24 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/395860968/SRP/ConfigurationKeys.java b/students/395860968/SRP/ConfigurationKeys.java new file mode 100644 index 0000000000..868a03ff83 --- /dev/null +++ b/students/395860968/SRP/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/395860968/SRP/DBUtil.java b/students/395860968/SRP/DBUtil.java new file mode 100644 index 0000000000..65383e4dba --- /dev/null +++ b/students/395860968/SRP/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/395860968/SRP/FileUtil.java b/students/395860968/SRP/FileUtil.java new file mode 100644 index 0000000000..9a1a468c10 --- /dev/null +++ b/students/395860968/SRP/FileUtil.java @@ -0,0 +1,33 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +/** + * Created by kenhuang on 2017/6/15. + */ +public class FileUtil { + private static final String FILE_PATH="/Users/kenhuang/Desktop/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt"; + private static File f = new File(FileUtil.FILE_PATH); + protected static Product readFile() throws IOException // @02C + { + BufferedReader br = null; + Product resultProduct; + try { + br = new BufferedReader(new FileReader(f)); + String temp = br.readLine(); + String[] data = temp.split(" "); + resultProduct = new Product(data[0],data[1]); + System.out.println("产品ID = " + resultProduct.productID + "\n"); + System.out.println("产品描述 = " + resultProduct.productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + return resultProduct; + } +} diff --git a/students/395860968/SRP/MailUtil.java b/students/395860968/SRP/MailUtil.java new file mode 100644 index 0000000000..e62f40ead8 --- /dev/null +++ b/students/395860968/SRP/MailUtil.java @@ -0,0 +1,52 @@ +package com.coderising.ood.srp; + +import java.io.IOException; + + +public class MailUtil { + protected String smtpHost = null; + protected String altSmtpHost = null; + public MailUtil(String smtpHost, String altSmtpHost) { + this.smtpHost = smtpHost; + this.altSmtpHost = altSmtpHost; + } + private static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + public void sendPromotionMail(boolean debug, PromotionMail mail) throws IOException { + System.out.println("开始发送邮件"); + String toAddress; + String message; + if (mail.toAddressList != null) { + while (mail.hasNextToAddress()) { + toAddress = mail.getNextToAddress(); + if (toAddress.length() > 0){ + message = mail.generateMessageToCurrentToAddress(); + try { + MailUtil.sendEmail(toAddress, mail.fromAddress, mail.subject, message, this.smtpHost, debug); + } + catch (Exception e) { + try { + MailUtil.sendEmail(toAddress, mail.fromAddress, mail.subject, message, this.altSmtpHost, debug); + + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + }else { + System.out.println("目标地址为空"); + } + } + } else { + System.out.println("没有邮件发送"); + } + } +} diff --git a/students/395860968/SRP/Product.java b/students/395860968/SRP/Product.java new file mode 100644 index 0000000000..27ce7b0ef1 --- /dev/null +++ b/students/395860968/SRP/Product.java @@ -0,0 +1,21 @@ +package com.coderising.ood.srp; + +/** + * Created by kenhuang on 2017/6/15. + */ +public class Product { + protected String productID = null; + protected String productDesc = null; + // protected String sendMailQuery = null; + public Product(String productID, String productDesc) { + this.productID = productID; + this.productDesc = productDesc; + } + protected String generateLoadQuery() { + System.out.println("loadQuery set"); + return "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + } +} diff --git a/students/395860968/SRP/PromotionMail.java b/students/395860968/SRP/PromotionMail.java new file mode 100644 index 0000000000..f62a56c295 --- /dev/null +++ b/students/395860968/SRP/PromotionMail.java @@ -0,0 +1,44 @@ +package com.coderising.ood.srp; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; + +public class PromotionMail { + protected String fromAddress = null; + protected List toAddressList = null; + protected String subject = "您关注的产品降价了"; + protected String message = null; + private Product product; + private int toAddressListIndex = -1 ; + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + public static void main(String[] args) throws Exception { + Product product = FileUtil.readFile(); + if (product != null) { + boolean emailDebug = false; + Configuration config = new Configuration(); + MailUtil mailUtil = new MailUtil(config.getProperty(ConfigurationKeys.SMTP_SERVER), + config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER)); + PromotionMail mail = new PromotionMail(config.getProperty(ConfigurationKeys.EMAIL_ADMIN),product); + mailUtil.sendPromotionMail(emailDebug,mail); + } + } + public PromotionMail(String fromAddress,Product product) throws Exception { + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + this.fromAddress = fromAddress; + this.product = product; + this.toAddressList = DBUtil.query(this.product.generateLoadQuery()); + } + public boolean hasNextToAddress(){ + return this.toAddressListIndex < this.toAddressList.size() - 1; + } + public String getNextToAddress(){ + HashMap map = (HashMap)this.toAddressList.get(++this.toAddressListIndex); + return (String)map.get(EMAIL_KEY); + } + protected String generateMessageToCurrentToAddress() throws IOException { + HashMap map = (HashMap)this.toAddressList.get(this.toAddressListIndex); + String name = (String) map.get(NAME_KEY); + return "尊敬的 "+name+", 您关注的产品 " + this.product.productDesc + " 降价了,欢迎购买!" ; + } +} diff --git a/students/395860968/SRP/product_promotion.txt b/students/395860968/SRP/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/395860968/SRP/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/395860968/SRP/src b/students/395860968/SRP/src new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/students/395860968/SRP/src @@ -0,0 +1 @@ + diff --git a/students/402246209/learning/pom.xml b/students/402246209/learning/pom.xml new file mode 100644 index 0000000000..8e4668829c --- /dev/null +++ b/students/402246209/learning/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + + com.mimieye + learning + RELEASE + jar + + + + 1.8 + + + + + + + + org.apache.maven.plugins + maven-resources-plugin + 3.0.2 + + UTF-8 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.0 + + 1.8 + 1.8 + + UTF-8 + + + + + + + + + + org.apache.commons + commons-lang3 + 3.5 + + + + + \ No newline at end of file diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/config/LoggerConstant.java b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/config/LoggerConstant.java new file mode 100644 index 0000000000..2f19e884c5 --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/config/LoggerConstant.java @@ -0,0 +1,26 @@ +package com.mimieye.odd.ocp.config; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by Pierreluo on 2017/6/20. + */ +public class LoggerConstant { + public static final int RAW_LOG = 1; + public static final int RAW_LOG_WITH_DATE = 2; + public static final int EMAIL_LOG = 1; + public static final int SMS_LOG = 2; + public static final int PRINT_LOG = 3; + + public static final Map TPYE_MAP = new HashMap<>(); + public static final Map METHOD_MAP = new HashMap<>(); + + static { + TPYE_MAP.put(1, "com.mimieye.odd.ocp.type.Impl.RawLogTypeImpl"); + TPYE_MAP.put(2, "com.mimieye.odd.ocp.type.Impl.RawLogWithDateTypeImpl"); + METHOD_MAP.put(1, "com.mimieye.odd.ocp.method.Impl.MailMethodImpl"); + METHOD_MAP.put(2, "com.mimieye.odd.ocp.method.Impl.SMSMethodImpl"); + METHOD_MAP.put(3, "com.mimieye.odd.ocp.method.Impl.PrintMethodImpl"); + } +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/logger/Impl/LoggerImpl.java b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/logger/Impl/LoggerImpl.java new file mode 100644 index 0000000000..869aa45227 --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/logger/Impl/LoggerImpl.java @@ -0,0 +1,36 @@ +package com.mimieye.odd.ocp.logger.Impl; + +import com.mimieye.odd.ocp.config.LoggerConstant; +import com.mimieye.odd.ocp.logger.LoggerInterface; +import com.mimieye.odd.ocp.method.MethodInterface; +import com.mimieye.odd.ocp.type.TypeInterface; +import com.mimieye.odd.ocp.util.MailUtil; +import com.mimieye.odd.ocp.util.SMSUtil; + +public class LoggerImpl implements LoggerInterface{ + + private TypeInterface type; + private MethodInterface method; + private Integer typeInt; + private Integer methodInt; + + public LoggerImpl(int typeInt, int methodInt) throws IllegalAccessException, InstantiationException, ClassNotFoundException { + this.typeInt = typeInt; + this.methodInt = methodInt; + init(); + } + + private void init() throws ClassNotFoundException, IllegalAccessException, InstantiationException { + String typeClass = LoggerConstant.TPYE_MAP.get(typeInt); + String methodClass = LoggerConstant.METHOD_MAP.get(methodInt); + TypeInterface typeInterface = (TypeInterface)Class.forName(typeClass).newInstance(); + MethodInterface methodInterface = (MethodInterface)Class.forName(methodClass).newInstance(); + this.type = typeInterface; + this.method = methodInterface; + } + + public void log(String msg){ + method.execute(type.getMsg(msg)); + } +} + diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/logger/LoggerInterface.java b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/logger/LoggerInterface.java new file mode 100644 index 0000000000..43519090bf --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/logger/LoggerInterface.java @@ -0,0 +1,8 @@ +package com.mimieye.odd.ocp.logger; + +/** + * Created by Pierreluo on 2017/6/20. + */ +public interface LoggerInterface { + void log(String msg); +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/main/LoggerMain.java b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/main/LoggerMain.java new file mode 100644 index 0000000000..e8bdeb2f51 --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/main/LoggerMain.java @@ -0,0 +1,24 @@ +package com.mimieye.odd.ocp.main; + +import com.mimieye.odd.ocp.config.LoggerConstant; +import com.mimieye.odd.ocp.logger.Impl.LoggerImpl; +import com.mimieye.odd.ocp.logger.LoggerInterface; + +/** + * Created by Pierreluo on 2017/6/20. + */ +public class LoggerMain { + public static void main(String[] args) { + try { + LoggerInterface logger = new LoggerImpl(LoggerConstant.RAW_LOG, LoggerConstant.EMAIL_LOG); + String msg = "log content."; + logger.log(msg); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + } +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/method/Impl/MailMethodImpl.java b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/method/Impl/MailMethodImpl.java new file mode 100644 index 0000000000..dda6d6c5d3 --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/method/Impl/MailMethodImpl.java @@ -0,0 +1,14 @@ +package com.mimieye.odd.ocp.method.Impl; + +import com.mimieye.odd.ocp.method.MethodInterface; +import com.mimieye.odd.ocp.util.MailUtil; + +/** + * Created by Pierreluo on 2017/6/20. + */ +public class MailMethodImpl implements MethodInterface { + @Override + public void execute(String logMsg) { + MailUtil.send(logMsg); + } +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/method/Impl/PrintMethodImpl.java b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/method/Impl/PrintMethodImpl.java new file mode 100644 index 0000000000..04d67545fe --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/method/Impl/PrintMethodImpl.java @@ -0,0 +1,15 @@ +package com.mimieye.odd.ocp.method.Impl; + +import com.mimieye.odd.ocp.method.MethodInterface; +import com.mimieye.odd.ocp.util.MailUtil; + +/** + * Created by Pierreluo on 2017/6/20. + */ +public class PrintMethodImpl implements MethodInterface { + + @Override + public void execute(String logMsg) { + System.out.println("print console msg - " + logMsg); + } +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/method/Impl/SMSMethodImpl.java b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/method/Impl/SMSMethodImpl.java new file mode 100644 index 0000000000..14a8fe0c34 --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/method/Impl/SMSMethodImpl.java @@ -0,0 +1,16 @@ +package com.mimieye.odd.ocp.method.Impl; + +import com.mimieye.odd.ocp.method.MethodInterface; +import com.mimieye.odd.ocp.util.MailUtil; +import com.mimieye.odd.ocp.util.SMSUtil; + +/** + * Created by Pierreluo on 2017/6/20. + */ +public class SMSMethodImpl implements MethodInterface { + + @Override + public void execute(String logMsg) { + SMSUtil.send(logMsg); + } +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/method/MethodInterface.java b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/method/MethodInterface.java new file mode 100644 index 0000000000..9134e8eeae --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/method/MethodInterface.java @@ -0,0 +1,8 @@ +package com.mimieye.odd.ocp.method; + +/** + * Created by Pierreluo on 2017/6/20. + */ +public interface MethodInterface { + void execute(String logMsg); +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/type/Impl/RawLogTypeImpl.java b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/type/Impl/RawLogTypeImpl.java new file mode 100644 index 0000000000..0f912ec56a --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/type/Impl/RawLogTypeImpl.java @@ -0,0 +1,16 @@ +package com.mimieye.odd.ocp.type.Impl; + +import com.mimieye.odd.ocp.config.LoggerConstant; +import com.mimieye.odd.ocp.type.TypeInterface; +import com.mimieye.odd.ocp.util.DateUtil; + +/** + * Created by Pierreluo on 2017/6/20. + */ +public class RawLogTypeImpl implements TypeInterface { + + @Override + public String getMsg(String msg) { + return msg; + } +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/type/Impl/RawLogWithDateTypeImpl.java b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/type/Impl/RawLogWithDateTypeImpl.java new file mode 100644 index 0000000000..876e48a830 --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/type/Impl/RawLogWithDateTypeImpl.java @@ -0,0 +1,18 @@ +package com.mimieye.odd.ocp.type.Impl; + +import com.mimieye.odd.ocp.type.TypeInterface; +import com.mimieye.odd.ocp.util.DateUtil; + +/** + * Created by Pierreluo on 2017/6/20. + */ +public class RawLogWithDateTypeImpl implements TypeInterface { + + @Override + public String getMsg(String msg) { + String logMsg = msg; + String txtDate = DateUtil.getCurrentDateAsString(); + logMsg = txtDate + ": " + msg; + return logMsg; + } +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/type/TypeInterface.java b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/type/TypeInterface.java new file mode 100644 index 0000000000..2ed457c68d --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/type/TypeInterface.java @@ -0,0 +1,8 @@ +package com.mimieye.odd.ocp.type; + +/** + * Created by Pierreluo on 2017/6/20. + */ +public interface TypeInterface { + String getMsg(String msg); +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/util/DateUtil.java b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/util/DateUtil.java new file mode 100644 index 0000000000..a55ad2d667 --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/util/DateUtil.java @@ -0,0 +1,12 @@ +package com.mimieye.odd.ocp.util; + +import java.text.SimpleDateFormat; +import java.util.Date; + +public class DateUtil { + + public static String getCurrentDateAsString() { + return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); + } + +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/util/MailUtil.java b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/util/MailUtil.java new file mode 100644 index 0000000000..2b75360ea2 --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/util/MailUtil.java @@ -0,0 +1,9 @@ +package com.mimieye.odd.ocp.util; + +public class MailUtil { + + public static void send(String logMsg) { + System.out.println("send email msg - " + logMsg); + } + +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/util/SMSUtil.java b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/util/SMSUtil.java new file mode 100644 index 0000000000..c07f9b46bc --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/ocp/util/SMSUtil.java @@ -0,0 +1,9 @@ +package com.mimieye.odd.ocp.util; + +public class SMSUtil { + + public static void send(String logMsg) { + System.out.println("send SMS msg - " + logMsg); + } + +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/srp/config/Configuration.java b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/config/Configuration.java new file mode 100644 index 0000000000..d4e3c6fe16 --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/config/Configuration.java @@ -0,0 +1,27 @@ +package com.mimieye.odd.srp.config; +import com.mimieye.odd.srp.util.PropertiesUtil; + +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +public class Configuration { + private static final String CONFIG_FILENAME = "config.properties"; + static Properties configurations = null; + static{ + try { + configurations = PropertiesUtil.getInstance(CONFIG_FILENAME); + } catch (Exception e) { + e.printStackTrace(); + } + } + /** + * @param key + * @return + */ + public String getProperty(String key) { + return configurations.getProperty(key); + } + +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/srp/config/ConfigurationKeys.java b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/config/ConfigurationKeys.java new file mode 100644 index 0000000000..7f1a264d0a --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/config/ConfigurationKeys.java @@ -0,0 +1,11 @@ +package com.mimieye.odd.srp.config; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + public static final String PROMOTION_FILEPATH = "promotion.filepath"; + public static final String EMAIL_DEBUG = "emailDebug"; + +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/srp/controller/PromotionAbstractMail.java b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/controller/PromotionAbstractMail.java new file mode 100644 index 0000000000..eb7544b4f1 --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/controller/PromotionAbstractMail.java @@ -0,0 +1,108 @@ +package com.mimieye.odd.srp.controller; + +import com.mimieye.odd.srp.config.Configuration; +import com.mimieye.odd.srp.config.ConfigurationKeys; +import com.mimieye.odd.srp.dao.impl.UserInfoDAOImpl; +import com.mimieye.odd.srp.service.PromotionInfoService; +import com.mimieye.odd.srp.service.UserInfoService; +import com.mimieye.odd.srp.service.impl.PromotionInfoServiceImpl; +import com.mimieye.odd.srp.service.impl.UserInfoServiceImpl; +import com.mimieye.odd.srp.util.MailUtil; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +public abstract class PromotionAbstractMail { + + protected static Configuration config; + protected static final String NAME_KEY = "NAME"; + protected static final String EMAIL_KEY = "EMAIL"; + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + protected String filePath; + protected boolean mailDebug; + protected List userInfos; + protected String productID; + protected String productDesc; + + public void init() throws Exception{ + config = new Configuration(); + setFilePath(config.getProperty(ConfigurationKeys.PROMOTION_FILEPATH)); + setMailDebug(Boolean.parseBoolean(ConfigurationKeys.EMAIL_DEBUG)); + setSMTPHost(); + setAltSMTPHost(); + setFromAddress(); + // 降价商品service + PromotionInfoService promotionInfoService = new PromotionInfoServiceImpl(); + // 邮件接收人service + UserInfoService userInfoService = new UserInfoServiceImpl(new UserInfoDAOImpl()); + // 获取第一条降价商品 + Map promotion = promotionInfoService.listPromotions(filePath).get(0); + setProductID(promotion.get("productID")); + setProductDesc(promotion.get("productDesc")); + // 获取邮件接收人 + setUserInfos(userInfoService.loadMailingList(productID)); + } + + + protected void configureEMail(HashMap userInfo) throws IOException { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected void sendEMails(boolean debug, List mailingList) throws IOException { + + System.out.println("开始发送邮件"); + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } catch (Exception e) { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + } else { + System.out.println("没有邮件发送"); + } + + } + + public void send() throws IOException { sendEMails(mailDebug, userInfos); } + + protected void setSMTPHost() { smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); } + + protected void setAltSMTPHost() { altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); } + + protected void setFromAddress() { fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); } + + protected void setFilePath(String filePath) { this.filePath = filePath; } + + protected void setMailDebug(boolean mailDebug) { this.mailDebug = mailDebug; } + + protected void setUserInfos(List userInfos) { this.userInfos = userInfos; } + + protected void setProductID(String productID) { this.productID = productID; } + + protected void setProductDesc(String productDesc) { this.productDesc = productDesc; } + + protected abstract void setMessage(HashMap userInfo) throws IOException ; +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/srp/controller/PromotionMail.java b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/controller/PromotionMail.java new file mode 100644 index 0000000000..983126e4db --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/controller/PromotionMail.java @@ -0,0 +1,19 @@ +package com.mimieye.odd.srp.controller; + +import java.io.IOException; +import java.util.HashMap; + +public class PromotionMail extends PromotionAbstractMail{ + + /** + * 自定义邮件内容 + * @param userInfo + * @throws IOException + */ + protected void setMessage(HashMap userInfo) throws IOException { + String name = (String) userInfo.get(NAME_KEY); + subject = "您关注的产品降价了"; + message = "尊敬的 " + name + ", 您关注的产品 " + productDesc + " 降价了,欢迎购买!"; + } + +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/srp/dao/UserInfoDAO.java b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/dao/UserInfoDAO.java new file mode 100644 index 0000000000..00ef1860b2 --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/dao/UserInfoDAO.java @@ -0,0 +1,13 @@ +package com.mimieye.odd.srp.dao; + +import com.mimieye.odd.srp.util.DBUtil; + +import java.util.List; + +/** + * Created by Pierreluo on 2017/6/15. + */ +public interface UserInfoDAO { + + List loadMailingList(String productID) throws Exception; +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/srp/dao/impl/UserInfoDAOImpl.java b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/dao/impl/UserInfoDAOImpl.java new file mode 100644 index 0000000000..c59b4bde9e --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/dao/impl/UserInfoDAOImpl.java @@ -0,0 +1,20 @@ +package com.mimieye.odd.srp.dao.impl; + +import com.mimieye.odd.srp.dao.UserInfoDAO; +import com.mimieye.odd.srp.util.DBUtil; + +import java.util.List; + +/** + * Created by Pierreluo on 2017/6/15. + */ +public class UserInfoDAOImpl implements UserInfoDAO { + + public List loadMailingList(String productID) throws Exception { + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID + "' " + + "and send_mail=1 "; + System.out.println("loadQuery set"); + return DBUtil.query(sendMailQuery); + } +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/srp/main/PromotionEmailMain.java b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/main/PromotionEmailMain.java new file mode 100644 index 0000000000..4a6c4366b2 --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/main/PromotionEmailMain.java @@ -0,0 +1,17 @@ +package com.mimieye.odd.srp.main; + +import com.mimieye.odd.srp.controller.PromotionAbstractMail; +import com.mimieye.odd.srp.controller.PromotionMail; + +/** + * Created by Pierreluo on 2017/6/17. + */ +public class PromotionEmailMain { + public static void main(String[] args) throws Exception { + PromotionAbstractMail mail = new PromotionMail(); + // 初始化数据 + mail.init(); + // 发送邮件 + mail.send(); + } +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/srp/service/PromotionInfoService.java b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/service/PromotionInfoService.java new file mode 100644 index 0000000000..bfcb508100 --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/service/PromotionInfoService.java @@ -0,0 +1,13 @@ +package com.mimieye.odd.srp.service; + +import com.mimieye.odd.srp.util.FileReadUtil; + +import java.io.IOException; +import java.util.*; + +/** + * Created by Pierreluo on 2017/6/15. + */ +public interface PromotionInfoService { + List> listPromotions(String filePath) throws Exception; +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/srp/service/UserInfoService.java b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/service/UserInfoService.java new file mode 100644 index 0000000000..57747f298a --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/service/UserInfoService.java @@ -0,0 +1,12 @@ +package com.mimieye.odd.srp.service; + +import com.mimieye.odd.srp.util.DBUtil; + +import java.util.List; + +/** + * Created by Pierreluo on 2017/6/15. + */ +public interface UserInfoService { + List loadMailingList(String productID) throws Exception; +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/srp/service/impl/PromotionInfoServiceImpl.java b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/service/impl/PromotionInfoServiceImpl.java new file mode 100644 index 0000000000..20aa392ea2 --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/service/impl/PromotionInfoServiceImpl.java @@ -0,0 +1,41 @@ +package com.mimieye.odd.srp.service.impl; + +import com.mimieye.odd.srp.service.PromotionInfoService; +import com.mimieye.odd.srp.util.FileReadUtil; + +import java.io.IOException; +import java.util.*; + +/** + * Created by Pierreluo on 2017/6/15. + */ +public class PromotionInfoServiceImpl implements PromotionInfoService { + + @Override + public List> listPromotions(String filePath) throws Exception { + List> list = null; + List results = FileReadUtil.readFile(filePath); + if(results != null && results.size()>0){ + list = new ArrayList<>(); + String temp = null; + String[] data = null; + Map map = null; + Iterator iterator = results.iterator(); + int i=1; + while(iterator.hasNext()){ + temp = iterator.next(); + data = temp.split(" "); + map = new HashMap<>(); + map.put("productID",data[0]); + map.put("productDesc",data[1]); + list.add(map); + System.out.println("产品"+(i)+"ID = " + data[0] ); + System.out.println("产品"+(i++)+"描述 = " + data[1] + "\n"); + } + }else{ + throw new IOException("No Records."); + } + return list; + } + +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/srp/service/impl/UserInfoServiceImpl.java b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/service/impl/UserInfoServiceImpl.java new file mode 100644 index 0000000000..39d7613a61 --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/service/impl/UserInfoServiceImpl.java @@ -0,0 +1,24 @@ +package com.mimieye.odd.srp.service.impl; + +import com.mimieye.odd.srp.dao.UserInfoDAO; +import com.mimieye.odd.srp.service.UserInfoService; +import com.mimieye.odd.srp.util.DBUtil; + +import java.util.List; + +/** + * Created by Pierreluo on 2017/6/15. + */ +public class UserInfoServiceImpl implements UserInfoService { + + private UserInfoDAO dao; + + public UserInfoServiceImpl(){} + public UserInfoServiceImpl(UserInfoDAO dao){ + this.dao = dao; + } + + public List loadMailingList(String productID) throws Exception { + return dao.loadMailingList(productID); + } +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/srp/util/DBUtil.java b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/util/DBUtil.java new file mode 100644 index 0000000000..c3e16050f4 --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/util/DBUtil.java @@ -0,0 +1,25 @@ +package com.mimieye.odd.srp.util; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/srp/util/FileReadUtil.java b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/util/FileReadUtil.java new file mode 100644 index 0000000000..0c0a8f58cf --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/util/FileReadUtil.java @@ -0,0 +1,42 @@ +package com.mimieye.odd.srp.util; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Created by Pierreluo on 2017/6/13. + */ +public class FileReadUtil { + + public static List readFile(String fileName) throws IOException { + File file = new File(fileName); + BufferedReader reader = null; + List results = null; + try { + reader = new BufferedReader(new FileReader(file)); + String tempString = null; + while ((tempString = reader.readLine()) != null) { + if(results == null){ + results = new ArrayList<>(); + } + results.add(tempString); + } + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + throw e; + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException e1) { + } + } + } + return results; + } +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/srp/util/MailUtil.java b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/util/MailUtil.java new file mode 100644 index 0000000000..b576aac1ed --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/util/MailUtil.java @@ -0,0 +1,18 @@ +package com.mimieye.odd.srp.util; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/srp/util/PropertiesUtil.java b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/util/PropertiesUtil.java new file mode 100644 index 0000000000..b40c49447c --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/srp/util/PropertiesUtil.java @@ -0,0 +1,18 @@ +package com.mimieye.odd.srp.util; + +import java.io.File; +import java.io.InputStream; +import java.util.Properties; + +/** + * Created by Pierreluo on 2017/6/17. + */ +public class PropertiesUtil { + + public static Properties getInstance(String fileName) throws Exception { + InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName); + Properties properties = new Properties(); + properties.load(in); + return properties; + } +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/uml/dice/Dice.java b/students/402246209/learning/src/main/java/com/mimieye/odd/uml/dice/Dice.java new file mode 100644 index 0000000000..c791c8f900 --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/uml/dice/Dice.java @@ -0,0 +1,37 @@ +package com.mimieye.odd.uml.dice; + +/** + * Created by Pierreluo on 2017/6/27. + */ +public class Dice { + private int[] values; + private int currentValueIndex; + private int capacity; + + public Dice(int capacity) { + this.capacity = capacity; + init(); + } + + private void init() { + this.values = new int[capacity]; + int i = 0; + int judge = capacity - 1; + while(true) { + values[i] = i; + if(i == judge) { + break; + } + i++; + } + this.currentValueIndex = 0; + } + + public int getCurrentValue() { + return values[currentValueIndex]; + } + + public void setCurrentValueIndex(int currentValueIndex) { + this.currentValueIndex = currentValueIndex; + } +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/uml/dice/DiceGame.java b/students/402246209/learning/src/main/java/com/mimieye/odd/uml/dice/DiceGame.java new file mode 100644 index 0000000000..439b5f7c7b --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/uml/dice/DiceGame.java @@ -0,0 +1,25 @@ +package com.mimieye.odd.uml.dice; + +/** + * Created by Pierreluo on 2017/6/27. + */ +public class DiceGame { + private int winValue; + + public DiceGame(int winValue) { + this.winValue = winValue; + } + + public boolean result(Dice... dices) { + int resultValue = 0; + for(Dice dice : dices) { + resultValue += dice.getCurrentValue(); + } + if(resultValue == winValue) { + return true; + } else { + return false; + } + } + +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/uml/dice/Player.java b/students/402246209/learning/src/main/java/com/mimieye/odd/uml/dice/Player.java new file mode 100644 index 0000000000..e6387788b6 --- /dev/null +++ b/students/402246209/learning/src/main/java/com/mimieye/odd/uml/dice/Player.java @@ -0,0 +1,47 @@ +package com.mimieye.odd.uml.dice; + +import org.apache.commons.lang3.RandomUtils; + +/** + * Created by Pierreluo on 2017/6/27. + */ +public class Player { + private Dice[] dices; + private DiceGame diceGame; + + public Player(int diceSize, int diceCapacity, int winValue) { + init(diceSize, diceCapacity, winValue); + } + + private void init(int diceSize, int diceCapacity, int winValue) { + dices = new Dice[diceSize]; + for(int i = 0; i < diceSize; i++) { + dices[i] = new Dice(diceCapacity); + } + diceGame = new DiceGame(winValue); + } + + public boolean play() { + for(Dice dice : dices) { + dice.setCurrentValueIndex(RandomUtils.nextInt(0,6)); + } + return diceGame.result(dices); + } + + public static void main(String[] args) { + Player player = new Player(2, 6, 7); + System.out.println(player.play()); + System.out.println(player.play()); + System.out.println(player.play()); + System.out.println(player.play()); + System.out.println(player.play()); + System.out.println(player.play()); + System.out.println(player.play()); + System.out.println(player.play()); + System.out.println(player.play()); + System.out.println(player.play()); + System.out.println(player.play()); + System.out.println(player.play()); + } + +} diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/uml/dice/diceClass.jpg b/students/402246209/learning/src/main/java/com/mimieye/odd/uml/dice/diceClass.jpg new file mode 100644 index 0000000000..845c31c1ca Binary files /dev/null and b/students/402246209/learning/src/main/java/com/mimieye/odd/uml/dice/diceClass.jpg differ diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/uml/dice/diceSequence.jpg b/students/402246209/learning/src/main/java/com/mimieye/odd/uml/dice/diceSequence.jpg new file mode 100644 index 0000000000..168baadc21 Binary files /dev/null and b/students/402246209/learning/src/main/java/com/mimieye/odd/uml/dice/diceSequence.jpg differ diff --git a/students/402246209/learning/src/main/java/com/mimieye/odd/uml/shopping/shoppingUseCase.jpg b/students/402246209/learning/src/main/java/com/mimieye/odd/uml/shopping/shoppingUseCase.jpg new file mode 100644 index 0000000000..33e6ac55ae Binary files /dev/null and b/students/402246209/learning/src/main/java/com/mimieye/odd/uml/shopping/shoppingUseCase.jpg differ diff --git a/students/402246209/learning/src/main/resources/config.properties b/students/402246209/learning/src/main/resources/config.properties new file mode 100644 index 0000000000..290d819f1e --- /dev/null +++ b/students/402246209/learning/src/main/resources/config.properties @@ -0,0 +1,5 @@ +smtp.server=smtp.163.com +alt.smtp.server=smtp1.163.com +email.admin=admin@company.com +promotion.filepath=F:/projectL/coding2017/students/402246209/learning/src/main/resources/product_promotion.txt +emailDebug=false diff --git a/students/402246209/learning/src/main/resources/product_promotion.txt b/students/402246209/learning/src/main/resources/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/402246209/learning/src/main/resources/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/402246209/readme.md b/students/402246209/readme.md new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/students/402246209/readme.md @@ -0,0 +1 @@ + diff --git "a/students/406400373/ood_assignment/refactor_odd/OOD_\351\207\215\346\236\204_\346\200\235\350\267\257.md" "b/students/406400373/ood_assignment/refactor_odd/OOD_\351\207\215\346\236\204_\346\200\235\350\267\257.md" new file mode 100644 index 0000000000..32dab3b3dd --- /dev/null +++ "b/students/406400373/ood_assignment/refactor_odd/OOD_\351\207\215\346\236\204_\346\200\235\350\267\257.md" @@ -0,0 +1,72 @@ +整个发送的流程主要是以下步骤 +1. 从配置文件中读取,生成要发送的产品信息。 +2. 设置邮件发送需要的SMTPHOST,ALTSMTPHOST,FROMADDRESS +3. 查询出需要发送的用户列表 +4. 设置发送邮件需要的 信息,从用户列表中读取要发送去的地址,用产品信息拼凑出Message +5. 发送邮件。 +其实Promotion就是一个job,衔接各个Handler,不自己做逻辑,完成发信的一个任务。 + +所以我理解首先可以独立出来的一堆职责就是邮件发送的类,它能够被初始化,然后接受参数发送邮件。 + +所以首先抽取出的职责就是和邮件发送相关的职责。EmailHandler。 +smtphost和altSmtpHost是定死的,应该设定成系统初始化时就设定好,至于From address在发送企业推送邮件时,也是统一的,也考虑封装在EmailHandler内部。 +在初始化一个EmailHandler时,即完成了邮件系统的相关设置。 +然后将发信的逻辑封装在EmailHandler内部。 +然后在PromotionMail中移除邮件系统相关的配置,引入EmailHandler。 +现在所有和发送相关以及邮件系统初始化的逻辑,全部移动到了EmailHandler内部。 +```java +public PromotionMail(File file, boolean mailDebug) throws Exception { + // 读文件,获得要推送的商品信息 + readFile(file); + // 查询用户 + setLoadQuery(); + // 初始化邮件发送Handler + EmailHandler emailHandler = new EmailHandler(); + // 对私有函数增加一个参数。 + sendEMails(mailDebug, loadMailingList(), emailHandler); + } +``` + +ok,接下来,邮件发送需要的主体信息是来自外部的,但它可以是一个纯数据类,存放着发送者,主题,message,一个pojo类,sendEMails应该只需要接受pojo的list,然后直接调emailHandler的发送函数即可,而不需要在里面还要进行取值的操作。 +```java + configureEMail((HashMap) iter.next()); + boolean result = emailHandler.sendMail(toAddress, subject, message, debug); +``` +一个简单的pojo类,emailHandler应该接受这个作为参数,修改代码如下 +```java + private String fromAddress; + private String toAddress; + private String subject; + private String message; +``` +新的发送邮件的函数 +```java +private void sendEMails(boolean debug, List emailEntities, EmailHandler emailHandler) + throws IOException { + + System.out.println("开始发送邮件"); + if (CollectionUtils.isNotEmpty(emailEntities)) { + for (EmailEntity emailEntity : emailEntities) { + boolean result = emailHandler.sendMail(emailEntity, debug); + System.out.println("发送邮件结果: " + result); + } + } else { + System.out.println("没有邮件发送"); + } + } +``` +emailHandler直接和emailEntity交互。 +接下来就是说我们怎么去构造emailEntities这个list了。 +然后这个商品信息的文件读取出来是一个list,首先对原有的读文件函数进行改动,用一个pojo类去代表商品的信息。同样的,用户的返回我们也用一个pojo类存储,因为这些东西以后的加字段可能是比较高的,通过一个统一的实体来管理会比较好。 +然后在job类里少用this,通过传参的方式,首先改变查询用户的函数,传入参数查询语句,返回的是user的list。 +分别构造出用来查询商品和用来处理用户的私有方法,准备下一步的重构。 +将查询商品相关的处理,封装到ProductHandler内部,只对外暴露获得商品列表的接口。 +```java +// 查询商品 +List products = new ProductHandler().fetchProducts(); +``` +用户是根据订阅了商品的来查的,所以处理用户的UserHandler接受一个sql语句查询,和商品之间解耦。 + +最终总结就是通过三个处理器负责商品,用户,邮件的处理,原有的PromotionMail则相当于是衔接各个处理器的job,具体的业务逻辑放在各个handler内部完成处理。 + +重构完毕。 diff --git a/students/406400373/ood_assignment/refactor_odd/pom.xml b/students/406400373/ood_assignment/refactor_odd/pom.xml new file mode 100644 index 0000000000..ecba4bc53e --- /dev/null +++ b/students/406400373/ood_assignment/refactor_odd/pom.xml @@ -0,0 +1,36 @@ + + + 4.0.0 + + ood-assignment + refactor-odd + 1.0-SNAPSHOT + + + + org.apache.commons + commons-lang3 + 3.5 + + + org.apache.commons + commons-collections4 + 4.1 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.7 + 1.7 + + + + + \ No newline at end of file diff --git a/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/ood/srp/Configuration.java b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..b161fa4691 --- /dev/null +++ b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "UserEntity" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..9f9e749af7 --- /dev/null +++ b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..00b12fb448 --- /dev/null +++ b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,198 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery = null; + + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected String productID = null; + protected String productDesc = null; + + private static Configuration config; + + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + File f = new File("/Users/cenkailun/codelab/coding2017/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/ood/srp/product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + + + config = new Configuration(); + + setSMTPHost(); + setAltSMTPHost(); + + + setFromAddress(); + + + setLoadQuery(); + + sendEMails(mailDebug, loadMailingList()); + + + } + + + + + protected void setProductID(String productID) + { + this.productID = productID; + + } + + protected String getproductID() + { + return productID; + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected void setSMTPHost() + { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() + { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + protected void setFromAddress() + { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setMessage(HashMap userInfo) throws IOException + { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + + + + } + + + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + private void setProductDesc(String desc) { + this.productDesc = desc; + } + + + protected void configureEMail(HashMap userInfo) throws IOException + { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try + { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } + + else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/PromotionMail.java b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/PromotionMail.java new file mode 100644 index 0000000000..5f41aaad78 --- /dev/null +++ b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/PromotionMail.java @@ -0,0 +1,60 @@ +package com.coderising.refactor_odd; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import com.coderising.refactor_odd.entity.EmailEntity; +import com.coderising.refactor_odd.entity.ProductEntity; +import com.coderising.refactor_odd.entity.UserEntity; +import com.coderising.refactor_odd.handler.EmailHandler; +import com.coderising.refactor_odd.handler.ProductHandler; +import com.coderising.refactor_odd.handler.UserHandler; +import org.apache.commons.collections4.CollectionUtils; + +public class PromotionMail { + + public static void main(String[] args) throws Exception { + // 初始化处理器 + EmailHandler emailHandler = new EmailHandler(); + ProductHandler productHandler = new ProductHandler(); + UserHandler userHandler = new UserHandler(); + + // 构造数据 + List emailEntities = new ArrayList<>(); + List products = productHandler.fetchProducts(); + for (ProductEntity product : products) { + List users = userHandler.fetchUser(buildUserQuery(product.getProductId())); + for (UserEntity user : users) { + EmailEntity emailEntity = new EmailEntity(); + emailEntity.setToAddress(user.getEmail()); + emailEntity.setSubject("您关注的产品降价了"); + emailEntity.setMessage("尊敬的 " + user.getName() + ", 您关注的产品 " + product.getProductName() + " 降价了,欢迎购买!"); + emailEntities.add(emailEntity); + } + } + // 发送邮件 + sendEMails(false, emailEntities, emailHandler); + + } + + private static String buildUserQuery(String productID) throws Exception { + + return "Select name from subscriptions " + "where product_id= '" + productID + "' " + "and send_mail=1 "; + } + + private static void sendEMails(boolean debug, List emailEntities, EmailHandler emailHandler) + throws IOException { + + System.out.println("开始发送邮件"); + if (CollectionUtils.isNotEmpty(emailEntities)) { + for (EmailEntity emailEntity : emailEntities) { + System.out.println("发送邮件:"); + emailHandler.sendMail(emailEntity, debug); + } + } else { + System.out.println("没有邮件发送"); + } + } +} diff --git a/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/constant/Constant.java b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/constant/Constant.java new file mode 100644 index 0000000000..4f4e9b5607 --- /dev/null +++ b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/constant/Constant.java @@ -0,0 +1,12 @@ +package com.coderising.refactor_odd.constant; + +/** + * @author cenkailun + * @Date 17/6/19 + * @Time 下午9:01 + */ +public class Constant { + + public static final String NAME_KEY = "NAME"; + public static final String EMAIL_KEY = "EMAIL"; +} diff --git a/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/entity/EmailEntity.java b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/entity/EmailEntity.java new file mode 100644 index 0000000000..1fb9278f43 --- /dev/null +++ b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/entity/EmailEntity.java @@ -0,0 +1,46 @@ +package com.coderising.refactor_odd.entity; + +/** + * @author cenkailun + * @Date 17/6/19 + * @Time 下午8:43 + */ +public class EmailEntity { + + private String fromAddress; + private String toAddress; + private String subject; + private String message; + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/entity/ProductEntity.java b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/entity/ProductEntity.java new file mode 100644 index 0000000000..a92910a608 --- /dev/null +++ b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/entity/ProductEntity.java @@ -0,0 +1,27 @@ +package com.coderising.refactor_odd.entity; + +/** + * @author cenkailun + * @Date 17/6/19 + * @Time 下午8:53 + */ +public class ProductEntity { + private String ProductId; + private String ProductName; + + public String getProductId() { + return ProductId; + } + + public void setProductId(String productId) { + ProductId = productId; + } + + public String getProductName() { + return ProductName; + } + + public void setProductName(String productName) { + ProductName = productName; + } +} diff --git a/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/entity/UserEntity.java b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/entity/UserEntity.java new file mode 100644 index 0000000000..b5d5f45d0a --- /dev/null +++ b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/entity/UserEntity.java @@ -0,0 +1,29 @@ +package com.coderising.refactor_odd.entity; + +/** + * @author cenkailun + * @Date 17/6/19 + * @Time 下午8:55 + */ +public class UserEntity { + + private String name; + + private String email; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/handler/EmailHandler.java b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/handler/EmailHandler.java new file mode 100644 index 0000000000..b55997038e --- /dev/null +++ b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/handler/EmailHandler.java @@ -0,0 +1,51 @@ +package com.coderising.refactor_odd.handler; + +import com.coderising.refactor_odd.entity.EmailEntity; +import org.apache.commons.lang3.StringUtils; + +import com.coderising.ood.srp.Configuration; +import com.coderising.ood.srp.ConfigurationKeys; +import com.coderising.ood.srp.MailUtil; + +/** + * @author cenkailun + * @Date 17/6/16 + * @Time 下午5:40 + */ +public class EmailHandler { + + private String smtpHost = null; + private String altSmtpHost = null; + private String fromAddress = null; + + public EmailHandler() { + initEmailHandler(); + } + + private void initEmailHandler() { + Configuration configuration = new Configuration(); + smtpHost = configuration.getProperty(ConfigurationKeys.SMTP_SERVER); + altSmtpHost = configuration.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + fromAddress = configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + public void sendMail(EmailEntity emailEntity, boolean debug) { + // TODO 校验 + send(emailEntity.getToAddress(), + StringUtils.isEmpty(emailEntity.getFromAddress()) ? this.fromAddress : emailEntity.getFromAddress(), + emailEntity.getSubject(), emailEntity.getMessage(), debug); + } + + private void send(String toAddress, String fromAddress, String subject, String message, boolean debug) { + try { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } catch (Exception e) { + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } +} diff --git a/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/handler/ProductHandler.java b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/handler/ProductHandler.java new file mode 100644 index 0000000000..03a5b74e2d --- /dev/null +++ b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/handler/ProductHandler.java @@ -0,0 +1,49 @@ +package com.coderising.refactor_odd.handler; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import com.coderising.refactor_odd.entity.ProductEntity; + +/** + * @author cenkailun + * @Date 17/6/19 + * @Time 下午9:13 + */ +public class ProductHandler { + + private List products = new ArrayList<>(); + + public ProductHandler() throws IOException { + File f = new File(this.getClass().getClassLoader().getResource("product_promotion.txt").getFile()); + initProducts(f); + } + + private List initProducts(File file) throws IOException { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = null; + while ((temp = br.readLine()) != null) { + String[] data = temp.split(" "); + ProductEntity product = new ProductEntity(); + product.setProductId(data[0]); + product.setProductName(data[1]); + products.add(product); + } + return products; + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + public List fetchProducts() { + return products; + } +} diff --git a/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/handler/UserHandler.java b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/handler/UserHandler.java new file mode 100644 index 0000000000..b26439c5eb --- /dev/null +++ b/students/406400373/ood_assignment/refactor_odd/src/main/java/com/coderising/refactor_odd/handler/UserHandler.java @@ -0,0 +1,29 @@ +package com.coderising.refactor_odd.handler; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import com.coderising.ood.srp.DBUtil; +import com.coderising.refactor_odd.constant.Constant; +import com.coderising.refactor_odd.entity.UserEntity; + +/** + * @author cenkailun + * @Date 17/6/19 + * @Time 下午9:18 + */ +public class UserHandler { + + public List fetchUser(String sql) { + List temp = DBUtil.query(sql); + List result = new ArrayList<>(); + for (HashMap hashMap : temp) { + UserEntity user = new UserEntity(); + user.setEmail((String) hashMap.get(Constant.EMAIL_KEY)); + user.setName((String) hashMap.get(Constant.NAME_KEY)); + result.add(user); + } + return result; + } +} diff --git a/students/406400373/ood_assignment/refactor_odd/src/main/resources/product_promotion.txt b/students/406400373/ood_assignment/refactor_odd/src/main/resources/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/406400373/ood_assignment/refactor_odd/src/main/resources/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/41689722.eulerlcs/regularexpression/pom.xml b/students/41689722.eulerlcs/regularexpression/pom.xml new file mode 100644 index 0000000000..86657499f5 --- /dev/null +++ b/students/41689722.eulerlcs/regularexpression/pom.xml @@ -0,0 +1,111 @@ + + 4.0.0 + com.github.eulerlcs + jmr-71-regularexpression + 0.0.1-SNAPSHOT + eulerlcs regular expression + + + + 1.7.24 + 4.12 + 2.17 + 1.8 + 1.8 + + + + + + org.projectlombok + lombok + 1.16.14 + provided + + + org.slf4j + slf4j-api + ${slf4j.version} + + + org.slf4j + slf4j-log4j12 + ${slf4j.version} + + + junit + junit + ${junit.version} + test + + + + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.0.1 + + + attach-source + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.1 + + ${maven.compiler.source} + ${maven.compiler.target} + + + + org.apache.maven.plugins + maven-jar-plugin + 3.0.2 + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + + true + 1.8 + protected + UTF-8 + UTF-8 + UTF-8 + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.19.1 + + + org.apache.maven.plugins + maven-surefire-report-plugin + 2.19.1 + + true + + + + + + + + org.apache.maven.plugins + maven-source-plugin + + + + \ No newline at end of file diff --git a/students/41689722.eulerlcs/regularexpression/src/main/java/com/github/eulerlcs/regularexpression/Utils.java b/students/41689722.eulerlcs/regularexpression/src/main/java/com/github/eulerlcs/regularexpression/Utils.java new file mode 100644 index 0000000000..aa5e45c5ed --- /dev/null +++ b/students/41689722.eulerlcs/regularexpression/src/main/java/com/github/eulerlcs/regularexpression/Utils.java @@ -0,0 +1,27 @@ +package com.github.eulerlcs.regularexpression; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +public class Utils { + + public static String readAllFromResouce(String resourceName) { + byte[] fileContentBytes; + try { + Path path = Paths.get(ClassLoader.getSystemResource(resourceName).toURI()); + fileContentBytes = Files.readAllBytes(path); + String fileContentStr = new String(fileContentBytes, StandardCharsets.UTF_8); + + return fileContentStr; + } catch (IOException | URISyntaxException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return ""; + } +} diff --git a/students/41689722.eulerlcs/regularexpression/src/main/resources/.gitkeep b/students/41689722.eulerlcs/regularexpression/src/main/resources/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/students/41689722.eulerlcs/regularexpression/src/main/resources/log4j.xml b/students/41689722.eulerlcs/regularexpression/src/main/resources/log4j.xml new file mode 100644 index 0000000000..831b8d9ce3 --- /dev/null +++ b/students/41689722.eulerlcs/regularexpression/src/main/resources/log4j.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/students/41689722.eulerlcs/regularexpression/src/test/java/.gitkeep b/students/41689722.eulerlcs/regularexpression/src/test/java/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/students/41689722.eulerlcs/regularexpression/src/test/java/com/github/eulerlcs/regularexpression/UtilsTest.java b/students/41689722.eulerlcs/regularexpression/src/test/java/com/github/eulerlcs/regularexpression/UtilsTest.java new file mode 100644 index 0000000000..3fa9e25c8d --- /dev/null +++ b/students/41689722.eulerlcs/regularexpression/src/test/java/com/github/eulerlcs/regularexpression/UtilsTest.java @@ -0,0 +1,316 @@ +package com.github.eulerlcs.regularexpression; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.Test; + +// http://www.cnblogs.com/playing/archive/2011/03/15/1984943.html + +public class UtilsTest { + + /** + * 多行模式-1 + */ + @Test + public void test01_01() { + String t1 = Utils.readAllFromResouce("01.txt"); + + // 默认 单行模式 + Pattern p1 = Pattern.compile("^def$"); + Matcher m1 = p1.matcher(t1); + + if (m1.find()) { + System.out.println("found!"); + } else { + System.out.println("not found!"); + } + } + + /** + *
+	 * 多行模式-2 
+	 *  (?m)		Pattern.MULTILINE
+	 * 
+ */ + @Test + public void test01_02() { + String t1 = Utils.readAllFromResouce("01.txt"); + + // 多行模式 写法一 + // Pattern p1 = Pattern.compile("(?m)^def$"); + // 多行模式 写法二 + Pattern p1 = Pattern.compile("^def$", Pattern.MULTILINE); + + Matcher m1 = p1.matcher(t1); + + if (m1.find()) { + System.out.println("found!"); + } else { + System.out.println("not found!"); + } + } + + /** + * flag设定和(?X)的等价关系 + * + *
+	 *  (?m)		Pattern.MULTILINE
+	 *  (?i)		Pattern.CASE_INSENSITIVE
+	 *  (?u)		Pattern.UNICODE_CASE
+	 *  (?s)		Pattern.DOTALL
+	 *  (?d)		Pattern.UNIX_LINES
+	 *  (?x)		Pattern.COMMENTS
+	 * 
+ */ + + /** + *
+	 * ascii大小写
+	 *  (?i)		Pattern.CASE_INSENSITIVE
+	 * 
+ */ + @Test + public void test02_01() { + String t1 = "abc AbC aCd abc ABc 2343"; + String r1 = "abc"; + + // 默认 区分大小写 + // Pattern p1 = Pattern.compile(r1); + + // 忽略ascii大小,写法一 + Pattern p1 = Pattern.compile("(?i)abc"); + + // 忽略ascii大小,写法而 + // Pattern p1 = Pattern.compile(r1, Pattern.CASE_INSENSITIVE ); + + Matcher m1 = p1.matcher(t1); + + while (m1.find()) { + System.out.println(m1.group()); + } + } + + /** + *
+	 * unicode大小写
+	 *  (?u)		Pattern.UNICODE_CASE
+	 * 
+ */ + @Test + public void test03_01() { + String t1 = "abc AbC aCd abc ABc 2343"; + String r1 = "abc";// 日文输入法下,全角abc,也就是宽字体 + + // 默认 区分大小写只适用于ascii + // Pattern p1 = Pattern.compile((?i)abc); + + // 忽略ascii大小,写法一 + Pattern p1 = Pattern.compile("(?iu)abc"); + + // 忽略ascii大小,写法而 + // Pattern p1 = Pattern.compile(r1, Pattern.UNICODE_CASE); + + Matcher m1 = p1.matcher(t1); + + while (m1.find()) { + System.out.println(m1.group()); + } + } + + /** 通过设定标志位忽略大小写 */ + @Test + public void test03_02() { + String t1 = "abc AbC aCd\nABCD 2343"; + String r1 = "(?i)(?m)abc"; + Pattern p1 = Pattern.compile(r1); + Matcher m1 = p1.matcher(t1); + + while (m1.find()) { + System.out.println(m1.group()); + } + } + + @Test + public void test04_01_dotall() { + Pattern p = null; + Matcher m = null; + + String text1 = "width height"; + String text2 = "width\nheight"; + // Pattern p = Pattern.compile("(?s)width.height"); + p = Pattern.compile("width.height", Pattern.DOTALL); + + m = p.matcher(text1); + boolean result1 = m.find(); + if (result1) { + System.out.println("text1 found"); + } else { + System.out.println("text1 not found"); + } + + m = p.matcher(text2); + boolean result2 = m.find(); + if (result2) { + System.out.println("text2 found"); + } else { + System.out.println("text2 not found"); + } + } + + /** + * group + * + *
+	 * group(0):正则表达式的匹配值 
+	 * group(1):第一个子串
+	 * 
+ */ + @Test + public void test05_01() { + Pattern p = Pattern.compile("([a-z]+)-(\\d+)"); + Matcher m = p.matcher("type x-235, type y-3, type zw-465"); + + while (m.find()) { + for (int i = 0; i < m.groupCount() + 1; i++) { + System.out.println("group(" + i + ")=" + m.group(i)); + } + System.out.println("---------------------"); + } + } + + /** + * 字符串分割的例子 + */ + @Test + public void test05_02() { + String abc = "a///b/c"; + + // 分割后的数组中包含空字符 + String[] array1 = abc.split("/"); + for (String str : array1) { + System.out.println(str); + } + + System.out.println("---------------------"); + + // 分割后的数组中取出了空字符 + String[] array2 = abc.split("/+"); + for (String str : array2) { + System.out.println(str); + } + } + + /** + * 替换 + */ + @Test + public void test06_01() { + String str = "Orange is 100yuan, Banana is 180 yuan."; + String regex = "\\d+\\s*yuan"; + Pattern p = Pattern.compile(regex); + + Matcher m = p.matcher(str); + System.out.println(m.find()); + String result = m.replaceFirst("_$0_"); + + System.out.println(result); + } + + /** + * 替换 + */ + @Test + public void test06_02() { + String str = "Orange is 100yuan, Banana is 180 yuan."; + String regex = "(\\d)\\s*(yuan)"; + + Pattern p = Pattern.compile(regex); + Matcher m = p.matcher(str); + + String result = m.replaceAll("$2_$1"); + + System.out.println(result); + } + + /** + * 命名分组,替换 + */ + @Test + public void test06_03() { + String pathfFilename = "aa/notepad.exe"; + + String regex = "^.+/(?.+)$"; + String replacement = "${filename}"; + + String filename = pathfFilename.replaceFirst(regex, replacement); + System.out.println(filename); + } + + /** + * 从文本中读取多行数据后,建议先把回车符删掉 + */ + @Test + public void test07_01() { + String t1 = Utils.readAllFromResouce("07.txt"); + System.out.println("--orignal text start--"); + System.out.print(t1); + System.out.println("--orignal text end --"); + + // 统一换行符 + String ret1 = t1.replaceAll("(\r\n)|\r", "\n"); + System.out.println("--统一换行符 start--"); + System.out.print(ret1); + System.out.println("--统一换行符 end --"); + + // 行单位前后trim + String ret2 = ret1.replaceAll("(?m)^\\s*(.*?)\\s*$", "$1"); + System.out.println("--行单位前后trim start--"); + System.out.println(ret2); + System.out.println("--行单位前后trim end --"); + + assertFalse(ret2.equals(t1)); + } + + @Test + public void test01_04_Zz() { + Pattern p = null; + Matcher m = null; + boolean result1 = false; + boolean result2 = false; + boolean result3 = false; + + String text1 = "abc def"; + String text2 = "def abc"; + String text3 = "def abc\n"; + + p = Pattern.compile("abc\\z"); + + m = p.matcher(text1); + result1 = m.find(); + + m = p.matcher(text2); + result2 = m.find(); + + m = p.matcher(text3); + result3 = m.find(); + + p = Pattern.compile("abc\\Z"); + + m = p.matcher(text1); + result1 = m.find(); + + m = p.matcher(text2); + result2 = m.find(); + + m = p.matcher(text3); + result3 = m.find(); + + assertFalse(result1); + assertTrue(result2); + assertTrue(result3); + } +} diff --git a/students/41689722.eulerlcs/regularexpression/src/test/resources/.gitkeep b/students/41689722.eulerlcs/regularexpression/src/test/resources/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/students/41689722.eulerlcs/regularexpression/src/test/resources/01.txt b/students/41689722.eulerlcs/regularexpression/src/test/resources/01.txt new file mode 100644 index 0000000000..5f5521fae2 --- /dev/null +++ b/students/41689722.eulerlcs/regularexpression/src/test/resources/01.txt @@ -0,0 +1,2 @@ +abc +def diff --git a/students/41689722.eulerlcs/regularexpression/src/test/resources/07.txt b/students/41689722.eulerlcs/regularexpression/src/test/resources/07.txt new file mode 100644 index 0000000000..be72da22ea --- /dev/null +++ b/students/41689722.eulerlcs/regularexpression/src/test/resources/07.txt @@ -0,0 +1,5 @@ + abc +def + +gh + diff --git a/students/429301805/ood-assignment/pom.xml b/students/429301805/ood-assignment/pom.xml new file mode 100644 index 0000000000..1be81576cc --- /dev/null +++ b/students/429301805/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..927c7155cc --- /dev/null +++ b/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..33e1d29f7d --- /dev/null +++ b/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,13 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + + public static final String NAME_KEY = "NAME"; + public static final String EMAIL_KEY = "EMAIL"; + + +} diff --git a/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..605d196312 --- /dev/null +++ b/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "user"+i+"@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/HostService.java b/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/HostService.java new file mode 100644 index 0000000000..ccb5041cad --- /dev/null +++ b/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/HostService.java @@ -0,0 +1,33 @@ +package com.coderising.ood.srp; + +public class HostService { + + private static String smtpHost; + + private static String altSmtpHost; + + public static void setSMTPHost(Configuration config) + { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + public static void setAltSMTPHost(Configuration config) + { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + public static String getSmtpHost() { + return smtpHost; + } + + + public static String getAltSmtpHost() { + return altSmtpHost; + } + + + +} diff --git a/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..f437e0e651 --- /dev/null +++ b/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,40 @@ +package com.coderising.ood.srp; + +import java.io.IOException; +import java.util.HashMap; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + public static boolean configureEMail(HashMap userInfo,String toAddress) //throws IOException + { + if (toAddress.length() > 0){ + return true; + }else{ + return false; + } + } + + public static String setFromAddress(Configuration config) + { + String fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + return fromAddress; + } + + public static String setToAddress(HashMap userInfo){ + String toAddress = (String) userInfo.get(ConfigurationKeys.EMAIL_KEY); + return toAddress; + } + +} diff --git a/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java b/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..5881e903ba --- /dev/null +++ b/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; + +public class Product { + + private String productID; + private String productDesc; + + public Product(String productID,String productDesc){ + this.productID = productID; + this.productDesc = productDesc; + } + + public String getProductID() { + return productID; + } + + public String getProductDesc() { + return productDesc; + } + + + +} diff --git a/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..54e494a37b --- /dev/null +++ b/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,144 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + protected String sendMailQuery = null; + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected String productID = null; + protected String productDesc = null; + + private static Configuration config; + + public static void main(String[] args) throws Exception { + + File f = new File("C:\\Users\\CHS\\Desktop\\ood-assignment1\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + + config = new Configuration(); + + initService(config); + + setLoadQuery(); + + sendEMails(mailDebug, loadMailingList()); + + + } + + protected void initService(Configuration config) { + HostService.setSMTPHost(config); + HostService.setAltSMTPHost(config); + smtpHost = HostService.getSmtpHost(); + altSmtpHost = HostService.getAltSmtpHost(); + fromAddress = MailUtil.setFromAddress(config); + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + System.out.println("loadQuery set"); + } + + protected void setMessage(HashMap userInfo) throws IOException + { + + String name = (String) userInfo.get(ConfigurationKeys.NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + + } + + + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + Product p = new Product(data[0], data[1]); + productID = p.getProductID(); + productDesc = p.getProductDesc(); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + protected void sendEMails(boolean debug, List mailingList) throws IOException + { + System.out.println("开始发送邮件"); + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + HashMap userInfo = (HashMap) iter.next(); + toAddress = MailUtil.setToAddress(userInfo); + if(MailUtil.configureEMail(userInfo,toAddress)) + setMessage(userInfo); + else + System.out.println("用户信息不正确!"); + try + { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + } + + else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/429301805/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/429301805/src/gz/sychs/cn/test.java b/students/429301805/src/gz/sychs/cn/test.java new file mode 100644 index 0000000000..9fa342b44f --- /dev/null +++ b/students/429301805/src/gz/sychs/cn/test.java @@ -0,0 +1,10 @@ +package gz.sychs.cn; + +public class test { + + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println("This is a test"); + } + +} diff --git a/students/463256809/ood-assignment/pom.xml b/students/463256809/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/463256809/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtil.java b/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtil.java new file mode 100644 index 0000000000..fad6f3219b --- /dev/null +++ b/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtil.java @@ -0,0 +1,35 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +/** + * Created by wenwei on 2017/6/14. + */ +public class FileUtil { + + private static Product product = new Product(); + + public static void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + product.setProductID(data[0]); + product.setProductDesc(data[1]); + + System.out.println("产品ID = " + product.getProductID() + "\n"); + System.out.println("产品描述 = " + product.getProductDesc() + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } +} diff --git a/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..73e822f361 --- /dev/null +++ b/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,138 @@ +package com.coderising.ood.srp; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class MailUtil { + + + private static String sendMailQuery = null; + private static String smtpHost = null; + private static String altSmtpHost = null; + private static String fromAddress = null; + private static String toAddress = null; + private static String subject = null; + private static String message = null; + + + private static Configuration config = new Configuration(); + private static Product product = new Product(); + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + protected static void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + product.getProductID() +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected static void setSMTPHost() + { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected static void setAltSMTPHost() + { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + protected static void setFromAddress() + { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected static void setMessage(HashMap userInfo) throws IOException + { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!" ; + + + + } + + + + protected static void configureEMail(HashMap userInfo) throws IOException + { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected static List loadMailingList() throws Exception { + return DBUtil.query(sendMailQuery); + } + + + public static void sendEMails(boolean debug, List mailingList) throws Exception + { + + setSMTPHost(); + setAltSMTPHost(); + setFromAddress(); + setLoadQuery(); + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try + { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } + + else { + System.out.println("没有邮件发送"); + + } + + } + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java b/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..4420dfc603 --- /dev/null +++ b/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,26 @@ +package com.coderising.ood.srp; + +/** + * Created by wenwei on 2017/6/14. + */ +public class Product { + + private String productID = null; + private String productDesc = null; + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git a/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..e4241217a2 --- /dev/null +++ b/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,27 @@ +package com.coderising.ood.srp; + +import java.io.File; + +public class PromotionMail { + + public static void main(String[] args) throws Exception { + +// File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + File f = new File("/Users/wenwei/mygit/coding2017/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + FileUtil.readFile(file); + + MailUtil.sendEMails(mailDebug, MailUtil.loadMailingList()); + } + + +} diff --git a/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/463256809/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/465034663/README.md b/students/465034663/README.md new file mode 100644 index 0000000000..773f79cede --- /dev/null +++ b/students/465034663/README.md @@ -0,0 +1 @@ +OOD面向对象 \ No newline at end of file diff --git a/students/465034663/src/main/java/com/coderising/ood/mytest/AltSMTPHost.java b/students/465034663/src/main/java/com/coderising/ood/mytest/AltSMTPHost.java new file mode 100644 index 0000000000..cc492d23be --- /dev/null +++ b/students/465034663/src/main/java/com/coderising/ood/mytest/AltSMTPHost.java @@ -0,0 +1,13 @@ +package com.coderising.ood.mytest; + +/** + * Created by Arthur on 2017/6/17. + */ +public class AltSMTPHost implements Host { + + @Override + public String setHost() { + return this.configuration.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + } + +} diff --git a/students/465034663/src/main/java/com/coderising/ood/mytest/Configuration.java b/students/465034663/src/main/java/com/coderising/ood/mytest/Configuration.java new file mode 100644 index 0000000000..ae74eda7be --- /dev/null +++ b/students/465034663/src/main/java/com/coderising/ood/mytest/Configuration.java @@ -0,0 +1,24 @@ +package com.coderising.ood.mytest; + +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/465034663/src/main/java/com/coderising/ood/mytest/ConfigurationKeys.java b/students/465034663/src/main/java/com/coderising/ood/mytest/ConfigurationKeys.java new file mode 100644 index 0000000000..ae9234e569 --- /dev/null +++ b/students/465034663/src/main/java/com/coderising/ood/mytest/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.mytest; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/465034663/src/main/java/com/coderising/ood/mytest/DBUtil.java b/students/465034663/src/main/java/com/coderising/ood/mytest/DBUtil.java new file mode 100644 index 0000000000..cb8b8d4927 --- /dev/null +++ b/students/465034663/src/main/java/com/coderising/ood/mytest/DBUtil.java @@ -0,0 +1,36 @@ +package com.coderising.ood.mytest; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } + + public static String loadQuery(String productID) throws Exception { + + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID + "' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + return sendMailQuery; + } +} diff --git a/students/465034663/src/main/java/com/coderising/ood/mytest/Email.java b/students/465034663/src/main/java/com/coderising/ood/mytest/Email.java new file mode 100644 index 0000000000..208fb59b21 --- /dev/null +++ b/students/465034663/src/main/java/com/coderising/ood/mytest/Email.java @@ -0,0 +1,64 @@ +package com.coderising.ood.mytest; + +/** + * Created by Arthur on 2017/6/17. + */ +public class Email { + + String toAddress; + String fromAddress; + String subject; + String message; + String smtpHost; + + public Email() {} + + public Email(String toAddress, String fromAddress, String subject, String message, String smtpHost) { + this.toAddress = toAddress; + this.fromAddress = fromAddress; + this.subject = subject; + this.message = message; + this.smtpHost = smtpHost; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getSmtpHost() { + return smtpHost; + } + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + +} diff --git a/students/465034663/src/main/java/com/coderising/ood/mytest/Host.java b/students/465034663/src/main/java/com/coderising/ood/mytest/Host.java new file mode 100644 index 0000000000..3c87232aba --- /dev/null +++ b/students/465034663/src/main/java/com/coderising/ood/mytest/Host.java @@ -0,0 +1,12 @@ +package com.coderising.ood.mytest; + +/** + * Created by Arthur on 2017/6/17. + */ +public interface Host { + + Configuration configuration = new Configuration(); + + String setHost(); + +} diff --git a/students/465034663/src/main/java/com/coderising/ood/mytest/IOUtils.java b/students/465034663/src/main/java/com/coderising/ood/mytest/IOUtils.java new file mode 100644 index 0000000000..2d44ca482e --- /dev/null +++ b/students/465034663/src/main/java/com/coderising/ood/mytest/IOUtils.java @@ -0,0 +1,30 @@ +package com.coderising.ood.mytest; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +/** + * Created by Arthur on 2017/6/17. + */ +public class IOUtils { + + protected static String[] readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + + try { + + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + return data; + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + +} diff --git a/students/465034663/src/main/java/com/coderising/ood/mytest/MailUtil.java b/students/465034663/src/main/java/com/coderising/ood/mytest/MailUtil.java new file mode 100644 index 0000000000..b29261e059 --- /dev/null +++ b/students/465034663/src/main/java/com/coderising/ood/mytest/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.mytest; + +public class MailUtil { + + public static void sendEmail(Email email, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(email.getFromAddress()).append("\n"); + buffer.append("To:").append(email.getToAddress()).append("\n"); + buffer.append("Subject:").append(email.getSubject()).append("\n"); + buffer.append("Content:").append(email.getMessage()).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/465034663/src/main/java/com/coderising/ood/mytest/PromotionMail.java b/students/465034663/src/main/java/com/coderising/ood/mytest/PromotionMail.java new file mode 100644 index 0000000000..19f8e66222 --- /dev/null +++ b/students/465034663/src/main/java/com/coderising/ood/mytest/PromotionMail.java @@ -0,0 +1,128 @@ +package com.coderising.ood.mytest; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery; + + + protected String smtpHost; + protected String altSmtpHost; + protected String fromAddress; + protected String toAddress; + protected String subject; + protected String message; + + protected String productID; + protected String productDesc; + + private Email email; + + private static Configuration config; + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + File f = new File("D:\\IdeaWorspace\\works\\coding2017\\students\\465034663\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + IOUtils.readFile(file); + + + config = new Configuration(); + + /*setSMTPHost(); + setAltSMTPHost();*/ + this.smtpHost = new SMTPHost().setHost(); + this.altSmtpHost = new AltSMTPHost().setHost(); + + setFromAddress(); + + + //setLoadQuery(); + + DBUtil.loadQuery(this.productID); + sendEMails(mailDebug, loadMailingList()); + + + } + + protected void setFromAddress() { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setMessage(HashMap userInfo) throws IOException { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 " + name + ", 您关注的产品 " + productDesc + " 降价了,欢迎购买!"; + + + } + + protected void configureEMail(HashMap userInfo) throws IOException { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + setEmail(); + try { + if (toAddress.length() > 0) + MailUtil.sendEmail(this.email, debug); + } catch (Exception e) { + + try { + MailUtil.sendEmail(this.email, debug); + + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } else { + System.out.println("没有邮件发送"); + + } + + } + + private void setEmail(){ + this.email = new Email(this.toAddress, this.fromAddress, this.subject, this.message, this.altSmtpHost); + } +} diff --git a/students/465034663/src/main/java/com/coderising/ood/mytest/SMTPHost.java b/students/465034663/src/main/java/com/coderising/ood/mytest/SMTPHost.java new file mode 100644 index 0000000000..3d2ab58ace --- /dev/null +++ b/students/465034663/src/main/java/com/coderising/ood/mytest/SMTPHost.java @@ -0,0 +1,14 @@ +package com.coderising.ood.mytest; + + +/** + * Created by Arthur on 2017/6/17. + */ +public class SMTPHost implements Host { + + @Override + public String setHost() { + return this.configuration.getProperty(ConfigurationKeys.SMTP_SERVER); + } + +} diff --git a/students/465034663/src/main/java/com/coderising/ood/srp/Configuration.java b/students/465034663/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/465034663/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/465034663/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/465034663/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/465034663/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/465034663/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/465034663/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/465034663/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/465034663/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/465034663/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..9f9e749af7 --- /dev/null +++ b/students/465034663/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/465034663/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/465034663/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..d29c2d3dc0 --- /dev/null +++ b/students/465034663/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,181 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery = null; + + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected String productID = null; + protected String productDesc = null; + + private static Configuration config; + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + File f = new File("D:\\IdeaWorspace\\works\\coding2017\\students\\465034663\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + + + config = new Configuration(); + + setSMTPHost(); + setAltSMTPHost(); + + + setFromAddress(); + + + setLoadQuery(); + + sendEMails(mailDebug, loadMailingList()); + + + } + + + protected void setProductID(String productID) { + this.productID = productID; + + } + + protected String getproductID() { + return productID; + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID + "' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected void setSMTPHost() { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + protected void setFromAddress() { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setMessage(HashMap userInfo) throws IOException { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 " + name + ", 您关注的产品 " + productDesc + " 降价了,欢迎购买!"; + + + } + + + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + private void setProductDesc(String desc) { + this.productDesc = desc; + } + + + protected void configureEMail(HashMap userInfo) throws IOException { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } catch (Exception e) { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/465034663/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/465034663/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/465034663/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/466199956/ood/ood-assignment/pom.xml b/students/466199956/ood/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/466199956/ood/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..af199815a4 --- /dev/null +++ b/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtil.java b/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtil.java new file mode 100644 index 0000000000..5d59ae261b --- /dev/null +++ b/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +/** + * Created by Dell on 2017/6/15. + */ +public class FileUtil { + public static String readFile (File file) throws IOException{ + + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + return br.readLine(); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } +} diff --git a/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java b/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java new file mode 100644 index 0000000000..cd2bb049dc --- /dev/null +++ b/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java @@ -0,0 +1,124 @@ +package com.coderising.ood.srp; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +/** + * Created by Dell on 2017/6/15. + */ +public class Mail { + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + + + protected String sendMailQuery = null; + + + protected static final String NAME_KEY = "NAME"; + protected static final String EMAIL_KEY = "EMAIL"; + + public String getSmtpHost() { + return smtpHost; + } + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + + + protected void sendEMails(boolean debug, List mailingList) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try + { + if (toAddress.length() > 0) + MailUtil.sendEmail(this, debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(this, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } + + else { + System.out.println("没有邮件发送"); + + } + + } + + protected void configureEMail(HashMap userInfo) throws IOException + { + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + +} diff --git a/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..c2d46495a0 --- /dev/null +++ b/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,17 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(Mail mail, boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(mail.getFromAddress()).append("\n"); + buffer.append("To:").append(mail.getToAddress()).append("\n"); + buffer.append("Subject:").append(mail.getSubject()).append("\n"); + buffer.append("Content:").append(mail.getMessage()).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java b/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..6587491c3b --- /dev/null +++ b/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,32 @@ +package com.coderising.ood.srp; + +/** + * Created by Dell on 2017/6/15. + */ +public class Product { + + private String productID = null; + private String productDesc = null; + + + + public void setProductID(String productID) + { + this.productID = productID; + + } + + public String getproductID() + { + return productID; + } + + + public void setProductDesc(String desc) { + this.productDesc = desc; + } + + public String getProductDesc() { + return productDesc; + } +} diff --git a/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..1d054470eb --- /dev/null +++ b/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,85 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail extends Mail { + protected Product product; + private static Configuration config; + + public static void main(String[] args) throws Exception { + File f = new File("E:\\LandWolf\\coding2017\\students\\466199956\\ood\\ood-assignment\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"); + boolean emailDebug = false; + PromotionMail pe = new PromotionMail(f, emailDebug); + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + product = new Product(); + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + config = new Configuration(); + + setSmtpHost(config.getProperty(ConfigurationKeys.SMTP_SERVER)); + setAltSmtpHost(config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER)); + + + setFromAddress(config.getProperty(ConfigurationKeys.EMAIL_ADMIN)); + + setLoadQuery(); + + sendEMails(mailDebug, loadMailingList()); + + + } + + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + product.getproductID() + "' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected void setMessage(HashMap userInfo) throws IOException { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 " + name + ", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!"; + + + } + + + protected void readFile(File file) throws IOException // @02C + { + String temp = FileUtil.readFile(file); + String[] data = temp.split(" "); + + product.setProductID(data[0]); + product.setProductDesc(data[1]); + + System.out.println("产品ID = " + product.getproductID() + "\n"); + System.out.println("产品描述 = " + product.getProductDesc() + "\n"); + } + + + @Override + protected void configureEMail(HashMap userInfo) throws IOException { + + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + this.setMessage(userInfo); + } +} diff --git a/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/466199956/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/466199956/readme.md b/students/466199956/readme.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/students/469880403/ood-assignment/pom.xml b/students/469880403/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/469880403/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..a6791a7cfa --- /dev/null +++ b/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,104 @@ +package com.coderising.ood.srp; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import com.coderising.ood.srp.dao.SubscriptionDao; +import com.coderising.ood.srp.entity.MailSetting; +import com.coderising.ood.srp.entity.ProductInfo; +import com.coderising.ood.srp.properties.Configuration; +import com.coderising.ood.srp.properties.ConfigurationKeys; +import com.coderising.ood.srp.util.FileUtil; +import com.coderising.ood.srp.util.MailUtil; + +public class PromotionMail { + + private boolean mailDebug; + + + private static SubscriptionDao subscriptionDao = new SubscriptionDao(); + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + public static void main(String[] args) throws Exception { + // 1 读取配置文件,加载产品信息 + File file = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + boolean emailDebug = false; + ProductInfo productInfo = new ProductInfo(); + FileUtil.readFileAndSetProductInfo(file, productInfo); + + // 2 设置邮箱服务信息 + Configuration config = new Configuration(); + MailSetting mailSetting = new MailSetting(); + loadMailSetting(config, mailSetting); + + // 3 查询意向用户信息 + subscriptionDao.setLoadQuery(productInfo.getProductID()); + List sendMailList = subscriptionDao.loadMailingList(); + + // 4 发送邮件 + PromotionMail pe = new PromotionMail(emailDebug); + pe.sendEMails(mailSetting, sendMailList, productInfo); + + } + + public PromotionMail( boolean mailDebug) throws Exception { + + this.mailDebug = mailDebug; + } + + private static void loadMailSetting(Configuration config, MailSetting mailSetting) { + + mailSetting.setAltSmtpHost(config.getProperty(ConfigurationKeys.SMTP_SERVER)); + mailSetting.setAltSmtpHost(config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER)); + mailSetting.setFromAddress(config.getProperty(ConfigurationKeys.SMTP_SERVER)); + } + + + + protected void sendEMails(MailSetting mailSetting, List mailingList, ProductInfo productInfo) throws IOException { + + System.out.println("开始发送邮件"); + String subject = "您关注的产品降价了"; + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + Map userInfo = (HashMap) iter.next(); + String userName = (String) userInfo.get(NAME_KEY); + String toAddress = (String) userInfo.get(EMAIL_KEY); + String productDesc = productInfo.getProductDesc(); + String message = "尊敬的 " + userName + ", 您关注的产品 " + productDesc + " 降价了,欢迎购买!"; + + try { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, mailSetting.getFromAddress(), subject, message, + mailSetting.getSmtpHost(), this.mailDebug); + } catch (Exception e) { + + try { + MailUtil.sendEmail(toAddress, mailSetting.getFromAddress(), subject, message, + mailSetting.getAltSmtpHost(), this.mailDebug); + + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + } + + else { + System.out.println("没有邮件发送"); + + } + + } + + +} diff --git a/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/dao/SubscriptionDao.java b/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/dao/SubscriptionDao.java new file mode 100644 index 0000000000..f5360f0373 --- /dev/null +++ b/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/dao/SubscriptionDao.java @@ -0,0 +1,22 @@ +package com.coderising.ood.srp.dao; + +import java.util.List; + +import com.coderising.ood.srp.util.DBUtil; + +public class SubscriptionDao { + + protected static String sendMailQuery = null; + public List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + public void setLoadQuery(String productID) throws Exception { + + sendMailQuery = "Select name from subscriptions " + "where product_id= '" + productID + "' " + + "and send_mail=1 "; + + System.out.println("loadQuery set"); + } + +} diff --git a/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/entity/MailSetting.java b/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/entity/MailSetting.java new file mode 100644 index 0000000000..c3db877aa4 --- /dev/null +++ b/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/entity/MailSetting.java @@ -0,0 +1,36 @@ +package com.coderising.ood.srp.entity; + +public class MailSetting { + + private String smtpHost = null; + private String altSmtpHost = null; + private String fromAddress = null; + private String toAddress = null; + + + public String getToAddress() { + return toAddress; + } + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + public String getSmtpHost() { + return smtpHost; + } + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + public String getAltSmtpHost() { + return altSmtpHost; + } + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + public String getFromAddress() { + return fromAddress; + } + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + +} diff --git a/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/entity/ProductInfo.java b/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/entity/ProductInfo.java new file mode 100644 index 0000000000..0a6a569f27 --- /dev/null +++ b/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/entity/ProductInfo.java @@ -0,0 +1,19 @@ +package com.coderising.ood.srp.entity; + +public class ProductInfo { + private String productID = null; + private String productDesc = null; + public String getProductID() { + return productID; + } + public void setProductID(String productID) { + this.productID = productID; + } + public String getProductDesc() { + return productDesc; + } + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + +} diff --git a/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/properties/Configuration.java b/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/properties/Configuration.java new file mode 100644 index 0000000000..73aaa9166e --- /dev/null +++ b/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/properties/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp.properties; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/properties/ConfigurationKeys.java b/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/properties/ConfigurationKeys.java new file mode 100644 index 0000000000..8b09c99124 --- /dev/null +++ b/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/properties/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp.properties; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/properties/product_promotion.txt b/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/properties/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/properties/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/util/DBUtil.java b/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/util/DBUtil.java new file mode 100644 index 0000000000..a23198fcea --- /dev/null +++ b/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/util/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp.util; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/util/FileUtil.java b/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/util/FileUtil.java new file mode 100644 index 0000000000..a0bb0f3a85 --- /dev/null +++ b/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/util/FileUtil.java @@ -0,0 +1,34 @@ +package com.coderising.ood.srp.util; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import com.coderising.ood.srp.entity.ProductInfo; + +public class FileUtil { + + public static void readFileAndSetProductInfo(File file,ProductInfo productInfo) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + productInfo.setProductID( data[0]); + productInfo.setProductDesc( data[1]); + + + + System.out.println("产品ID = " + data[0] + "\n"); + System.out.println("产品描述 = " + data[1] + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + +} diff --git a/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java b/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java new file mode 100644 index 0000000000..bb028c690c --- /dev/null +++ b/students/469880403/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp.util; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/469880403/readme.md b/students/469880403/readme.md new file mode 100644 index 0000000000..8fc153b34f --- /dev/null +++ b/students/469880403/readme.md @@ -0,0 +1 @@ +说明文件 \ No newline at end of file diff --git a/students/471398827/ood-assignment/pom.xml b/students/471398827/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/471398827/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/Config.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/Config.java new file mode 100644 index 0000000000..13520f693c --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/Config.java @@ -0,0 +1,12 @@ +package com.coderising.ood.ocp; + +/** + * Created by szf on 6/20/17. + */ +public class Config { + public static final int RAW_LOG = 1; + public static final int RAW_LOG_WITH_DATE = 2; + public static final int EMAIL_LOG = 1; + public static final int SMS_LOG = 2; + public static final int PRINT_LOG = 3; +} diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/DateMessage.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/DateMessage.java new file mode 100644 index 0000000000..cac875e053 --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/DateMessage.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp; + +/** + * Created by szf on 6/20/17. + */ +public class DateMessage implements IMessage{ + @Override + public String getMessage(String msg) { + return DateUtil.getCurrentDateAsString() + msg; + } +} diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java new file mode 100644 index 0000000000..e9d919c378 --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return "date : 8/20 "; + } + +} diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/ILog.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/ILog.java new file mode 100644 index 0000000000..40a34666b8 --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/ILog.java @@ -0,0 +1,8 @@ +package com.coderising.ood.ocp; + +/** + * Created by szf on 6/20/17. + */ +public interface ILog { + public void printLog(String msg); +} diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/IMessage.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/IMessage.java new file mode 100644 index 0000000000..2ec8103863 --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/IMessage.java @@ -0,0 +1,8 @@ +package com.coderising.ood.ocp; + +/** + * Created by szf on 6/20/17. + */ +public interface IMessage { + public String getMessage(String msg); +} diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/LogFactory.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/LogFactory.java new file mode 100644 index 0000000000..8ba78c7b1d --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/LogFactory.java @@ -0,0 +1,25 @@ +package com.coderising.ood.ocp; + +import com.coderising.ood.srp.Mail; + +/** + * Created by szf on 6/20/17. + */ +public class LogFactory { + + static ILog produce(int logMethod) { + ILog log = null; + switch (logMethod) { + case Config.EMAIL_LOG: + log = new MailUtil(); + break; + case Config.SMS_LOG: + log = new SMSUtil(); + break; + case Config.PRINT_LOG: + log = new PrintUtil(); + break; + } + return log; + } +} diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java new file mode 100644 index 0000000000..c0579975de --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java @@ -0,0 +1,22 @@ +package com.coderising.ood.ocp; + +public class Logger { + ILog myLog; + IMessage myMessage; + + public Logger(int logType, int logMethod){ + myMessage = MessageFactory.produce(logType); + myLog = LogFactory.produce(logMethod); + } + public void log(String msg){ + + myLog.printLog(myMessage.getMessage(msg)); + + } + + public static void main(String[] args) { + Logger logger = new Logger(Config.RAW_LOG_WITH_DATE, Config.EMAIL_LOG); + logger.log("this is a log message"); + } +} + diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java new file mode 100644 index 0000000000..76d830742a --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class MailUtil implements ILog{ + + @Override + public void printLog(String msg) { + msg = "Mail..." + "\n" + msg; + System.out.println(msg); + } +} diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/MessageFactory.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/MessageFactory.java new file mode 100644 index 0000000000..10faf8f6d0 --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/MessageFactory.java @@ -0,0 +1,20 @@ +package com.coderising.ood.ocp; + +/** + * Created by szf on 6/20/17. + */ +public class MessageFactory { + + static IMessage produce(int messageType) { + IMessage msg = null; + switch (messageType) { + case Config.RAW_LOG: + msg = new RawMessage(); + break; + case Config.RAW_LOG_WITH_DATE: + msg = new DateMessage(); + break; + } + return msg; + } +} diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/PrintUtil.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/PrintUtil.java new file mode 100644 index 0000000000..4e337a3d42 --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/PrintUtil.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp; + +/** + * Created by szf on 6/20/17. + */ +public class PrintUtil implements ILog{ + @Override + public void printLog(String msg) { + System.out.println(msg); + } +} diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/RawMessage.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/RawMessage.java new file mode 100644 index 0000000000..0d6c48a796 --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/RawMessage.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp; + +/** + * Created by szf on 6/20/17. + */ +public class RawMessage implements IMessage{ + @Override + public String getMessage(String msg) { + return msg; + } +} diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java new file mode 100644 index 0000000000..c85286a465 --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp; + +public class SMSUtil implements ILog{ + + @Override + public void printLog(String msg) { + msg = "SMS..." + "\n" + msg; + System.out.println(msg); + } + +} diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..bd0db32d2a --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,26 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static boolean MAIL_DEBUG = false; + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + configurations.put(ConfigurationKeys.FILE_PATH, "/Users/szf/git/coding2017/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public static String getProperty(String key) { + + return configurations.get(key); + + } + +} diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..d4acd3240f --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,10 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + public static final String FILE_PATH = "file.path"; + +} diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..140d505a65 --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + String userName = "User" + i; + String email = "aa@bb.com"; + User user = new User(userName, email); + userList.add(user); + } + + return userList; + } +} diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java new file mode 100644 index 0000000000..231947248d --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +/** + * Created by szf on 6/20/17. + */ +public class Mail { + private String host; + + public Mail(String host) { + this.host = host; + } + + public boolean send(Message msg) throws Exception { + System.out.println("Host: " + this.host); + msg.print(); + return true; + } +} diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..502a7d96f0 --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,53 @@ +package com.coderising.ood.srp; + +public class MailUtil { + private static Mail firstSMPTHost, secondSMPTHost; + + static { + String host1 = Configuration.getProperty(ConfigurationKeys.SMTP_SERVER); + String host2 = Configuration.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + firstSMPTHost = new Mail(host1); + secondSMPTHost = new Mail(host2); + } + + + public static void sendEmail(Message msg) throws Exception{ + //假装发了一封邮件 + + if (msg != null) { + + System.out.println("开始发送邮件"); + + if (msg.checkFormat()) { + + System.out.println("发送邮件..."); + + try { + + firstSMPTHost.send(msg); + + System.out.println("发送邮件成功"); + + } catch (Exception e) { + try { + + secondSMPTHost.send(msg); + + } catch (Exception e2) { + + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + + } + } + } else { + + System.out.println("邮件格式不对"); + + } + } else { + + System.out.println("没有邮件发送"); + + } + } +} diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/Message.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/Message.java new file mode 100644 index 0000000000..a0a16d2756 --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/Message.java @@ -0,0 +1,65 @@ +package com.coderising.ood.srp; + +/** + * Created by szf on 6/20/17. + */ +public class Message { + private String toAddress; + private String fromAddress; + private String subject; + private String message; + + public Message(String toAddress, String fromAddress, String subject, String message) { + this.toAddress = toAddress; + this.fromAddress = fromAddress; + this.subject = subject; + this.message = message; + } + + public void print() { + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + } + + public boolean checkFormat() { + return true; + } + + public String getToAddress() { + + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + +} diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..5662ace67d --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,33 @@ +package com.coderising.ood.srp; + +/** + * Created by szf on 6/20/17. + */ +public class Product { + public String getProductId() { + return productId; + } + + public Product(String productId, String productDesc) { + this.productId = productId; + this.productDesc = productDesc; + } + + public Product() { + } + + public void setProductId(String productId) { + this.productId = productId; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + + private String productId; + private String productDesc; +} diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/ProductFactory.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/ProductFactory.java new file mode 100644 index 0000000000..f7366c27e4 --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/ProductFactory.java @@ -0,0 +1,36 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Created by szf on 6/20/17. + */ +public class ProductFactory { + List getNewProdcuts(File file) throws IOException { + BufferedReader br = null; + List newProducts = new ArrayList<>(); + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + Product product = new Product(data[0], data[1]); + newProducts.add(product); + + System.out.println("产品ID = " + product.getProductId() + "\n"); + System.out.println("产品描述 = " + product.getProductDesc() + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + return newProducts; + } + +} diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..fa90f9a539 --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,51 @@ +package com.coderising.ood.srp; +import java.io.File; +import java.util.List; + +public class PromotionMail { + + + public static void main(String[] args) throws Exception { + + PromotionMail pe = new PromotionMail(); + + } + + + public PromotionMail() throws Exception { + + if (Configuration.MAIL_DEBUG) { + System.out.println("debugging..."); + } + + ProductFactory factory = new ProductFactory(); + + File file = new File(Configuration.getProperty(ConfigurationKeys.FILE_PATH)); + List products = factory.getNewProdcuts(file); + + String productID = "1"; + String sql = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + List users = DBUtil.query(sql); + + + for (User user : users) { + for (Product product : products) { + + String to_address = user.getEmail(); + String from_address = Configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN); + String subject = "您关注的产品降价了"; + String message = "尊敬的 "+ user.getName() + ", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!" ; + + Message msg = new Message(to_address, from_address, subject, message); + + MailUtil.sendEmail(msg); + } + + } + } + + +} diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/User.java b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/User.java new file mode 100644 index 0000000000..225f98b727 --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/User.java @@ -0,0 +1,32 @@ +package com.coderising.ood.srp; + +/** + * Created by szf on 6/20/17. + */ +public class User { + private String Name; + + public User(String name, String email) { + Name = name; + Email = email; + } + + public String getName() { + + return Name; + } + + public void setName(String name) { + Name = name; + } + + public String getEmail() { + return Email; + } + + public void setEmail(String email) { + Email = email; + } + + private String Email; +} diff --git a/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/471398827/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/472779948/helloworld.txt b/students/472779948/helloworld.txt new file mode 100644 index 0000000000..fe51499bb2 --- /dev/null +++ b/students/472779948/helloworld.txt @@ -0,0 +1 @@ +helloworld! \ No newline at end of file diff --git a/students/472779948/ood-assignment/pom.xml b/students/472779948/ood-assignment/pom.xml new file mode 100644 index 0000000000..06d60721b0 --- /dev/null +++ b/students/472779948/ood-assignment/pom.xml @@ -0,0 +1,34 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + 1.8 + 1.8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..930ab2805c --- /dev/null +++ b/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,37 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + protected String sendMailQuery = null; + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param productID + * @return + */ + public static List query(String productID){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } + + protected void setLoadQuery(String productID) throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID + "' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } +} diff --git a/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/FileManager.java b/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/FileManager.java new file mode 100644 index 0000000000..a280c09d67 --- /dev/null +++ b/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/FileManager.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +public class FileManager { + //读取配置文件方法,单独提出来,其他的类需要时可复用 + public static String[] readFile(File file) throws IOException // @02C + { + String data[] = null; + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + data = temp.split(" "); + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + return data; + } +} diff --git a/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java b/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java new file mode 100644 index 0000000000..42da2ec0b1 --- /dev/null +++ b/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java @@ -0,0 +1,83 @@ +package com.coderising.ood.srp; + +public class Mail { + private String smtpHost = null; + private String altSmtpHost = null; + private String fromAddress = null; + private String toAddress = null; + private String subject = null; + private String message = null; + + + public Mail() { + } + + public Mail(String smtpHost, String altSmtpHost, String fromAddress, String toAddress, String subject, String message) { + this.smtpHost = smtpHost; + this.altSmtpHost = altSmtpHost; + this.fromAddress = fromAddress; + this.toAddress = toAddress; + this.subject = subject; + this.message = message; + } + + public String getSmtpHost() { + return smtpHost; + } + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @Override + public String toString() { + return "Mail{" + + "smtpHost='" + smtpHost + '\'' + + ", altSmtpHost='" + altSmtpHost + '\'' + + ", fromAddress='" + fromAddress + '\'' + + ", toAddress='" + toAddress + '\'' + + ", subject='" + subject + '\'' + + ", message='" + message + '\'' + + '}'; + } +} diff --git a/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..ff00545c91 --- /dev/null +++ b/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; + +import java.util.List; + +public class MailUtil { + + public static void sendEmail(Mail mail, boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(mail.getFromAddress()).append("\n"); + buffer.append("To:").append(mail.getToAddress()).append("\n"); + buffer.append("Subject:").append(mail.getSubject()).append("\n"); + buffer.append("Content:").append(mail.getMessage()).append("\n"); + System.out.println(buffer.toString()); + + } + + public static List loadMailingList(String productID) throws Exception { + return DBUtil.query(productID); + } + + +} diff --git a/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java b/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..e4074ba44a --- /dev/null +++ b/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,30 @@ +package com.coderising.ood.srp; + +/** + * Created by lenovo on 2017/6/13. + */ +public class Product { + private String productID; + private String productDesc; + + public Product(String productID, String productDesc) { + this.productID = productID; + this.productDesc = productDesc; + } + + public String getproductID() { + return productID; + } + + public void setproductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git a/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..f7e083ec4b --- /dev/null +++ b/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,85 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + protected Mail mail = null; + protected Product product = null; + + private static Configuration config; + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + public static void main(String[] args) throws Exception { + + File f = new File("E:\\workspace\\private\\projects\\ood-assignment\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + config = new Configuration(); + + //构造Mail对象 + mail = new Mail(); + mail.setSmtpHost(config.getProperty(ConfigurationKeys.SMTP_SERVER)); + mail.setAltSmtpHost(config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER)); + mail.setFromAddress(config.getProperty(ConfigurationKeys.EMAIL_ADMIN)); + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + String[] data = FileManager.readFile(file); + product = new Product(data[0],data[1]); + + sendEMails(mailDebug, MailUtil.loadMailingList(product.getproductID()));//MailUtil + } + + protected void setMessage(HashMap userInfo) throws IOException { + String name = (String) userInfo.get(NAME_KEY); + mail.setSubject("您关注的产品降价了"); + mail.setMessage("尊敬的 " + name + ", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!"); + + } + + protected void configureEMail(HashMap userInfo) throws IOException { + mail.setToAddress((String) userInfo.get(EMAIL_KEY)); + if (mail.getToAddress().length() > 0) + setMessage(userInfo); + } + + protected void sendEMails(boolean debug, List mailingList) throws IOException { + System.out.println("开始发送邮件"); + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try { + if (mail.getToAddress().length() > 0) + MailUtil.sendEmail(mail, debug); + } catch (Exception e) { + + try { + MailUtil.sendEmail(mail, debug); + + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + } else { + System.out.println("没有邮件发送"); + + } + } +} diff --git a/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/472779948/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/494800949/pom.xml b/students/494800949/pom.xml new file mode 100644 index 0000000000..521e154bc6 --- /dev/null +++ b/students/494800949/pom.xml @@ -0,0 +1,12 @@ + + + 4.0.0 + + season2 + season2 + 1.0-SNAPSHOT + + + \ No newline at end of file diff --git a/students/494800949/src/main/java/ood/assignment/srp/Configuration.java b/students/494800949/src/main/java/ood/assignment/srp/Configuration.java new file mode 100644 index 0000000000..858e860697 --- /dev/null +++ b/students/494800949/src/main/java/ood/assignment/srp/Configuration.java @@ -0,0 +1,24 @@ +package ood.assignment.srp; + +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/494800949/src/main/java/ood/assignment/srp/ConfigurationKeys.java b/students/494800949/src/main/java/ood/assignment/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..c41514a2fb --- /dev/null +++ b/students/494800949/src/main/java/ood/assignment/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package ood.assignment.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/494800949/src/main/java/ood/assignment/srp/DBUtil.java b/students/494800949/src/main/java/ood/assignment/srp/DBUtil.java new file mode 100644 index 0000000000..26ba6bb524 --- /dev/null +++ b/students/494800949/src/main/java/ood/assignment/srp/DBUtil.java @@ -0,0 +1,25 @@ +package ood.assignment.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/494800949/src/main/java/ood/assignment/srp/MailUtil.java b/students/494800949/src/main/java/ood/assignment/srp/MailUtil.java new file mode 100644 index 0000000000..03aca56c16 --- /dev/null +++ b/students/494800949/src/main/java/ood/assignment/srp/MailUtil.java @@ -0,0 +1,19 @@ +package ood.assignment.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + + +} diff --git a/students/494800949/src/main/java/ood/assignment/srp/PromotionMail.java b/students/494800949/src/main/java/ood/assignment/srp/PromotionMail.java new file mode 100644 index 0000000000..326f56a3d5 --- /dev/null +++ b/students/494800949/src/main/java/ood/assignment/srp/PromotionMail.java @@ -0,0 +1,198 @@ +package ood.assignment.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery = null; + + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected String productID = null; + protected String productDesc = null; + + private static Configuration config; + + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + File f = new File("I:\\sourceCode\\coding2017_2\\students\\494800949\\src\\main\\java\\ood\\assignment\\srp\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + + + config = new Configuration(); + + setSMTPHost(); + setAltSMTPHost(); + + + setFromAddress(); + + + setLoadQuery(); + + sendEMails(mailDebug, loadMailingList()); + + + } + + + + + protected void setProductID(String productID) + { + this.productID = productID; + + } + + protected String getproductID() + { + return productID; + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected void setSMTPHost() + { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() + { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + protected void setFromAddress() + { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setMessage(HashMap userInfo) throws IOException + { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + + + + } + + + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + private void setProductDesc(String desc) { + this.productDesc = desc; + } + + + protected void configureEMail(HashMap userInfo) throws IOException + { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try + { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } + + else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/494800949/src/main/java/ood/assignment/srp/product_promotion.txt b/students/494800949/src/main/java/ood/assignment/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/494800949/src/main/java/ood/assignment/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/494800949/src/main/java/ood/work/srp/Configuration.java b/students/494800949/src/main/java/ood/work/srp/Configuration.java new file mode 100644 index 0000000000..878ae499c2 --- /dev/null +++ b/students/494800949/src/main/java/ood/work/srp/Configuration.java @@ -0,0 +1,24 @@ +package ood.work.srp; + +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/494800949/src/main/java/ood/work/srp/ConfigurationKeys.java b/students/494800949/src/main/java/ood/work/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..6127d61f88 --- /dev/null +++ b/students/494800949/src/main/java/ood/work/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package ood.work.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/494800949/src/main/java/ood/work/srp/DBUtil.java b/students/494800949/src/main/java/ood/work/srp/DBUtil.java new file mode 100644 index 0000000000..48f108e054 --- /dev/null +++ b/students/494800949/src/main/java/ood/work/srp/DBUtil.java @@ -0,0 +1,24 @@ +package ood.work.srp; +import java.util.ArrayList; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + User userInfo = new User(); + userInfo.setName("User" + i); + userInfo.setEmail("aa"+ i +"@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/494800949/src/main/java/ood/work/srp/Email.java b/students/494800949/src/main/java/ood/work/srp/Email.java new file mode 100644 index 0000000000..2d3c4a4995 --- /dev/null +++ b/students/494800949/src/main/java/ood/work/srp/Email.java @@ -0,0 +1,41 @@ +package ood.work.srp; + +/** + * Created by Administrator on 2017/6/17 0017. + */ +public class Email { + + private String toAddress; + private String subject; + private String message; + + public Email(String toAddress, String subject, String message) { + this.toAddress = toAddress; + this.subject = subject; + this.message = message; + } + + public String getToAddress() { + return toAddress; + } + + public String getSubject() { + return subject; + } + + public String getMessage() { + return message; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/students/494800949/src/main/java/ood/work/srp/Emails.java b/students/494800949/src/main/java/ood/work/srp/Emails.java new file mode 100644 index 0000000000..768e513c88 --- /dev/null +++ b/students/494800949/src/main/java/ood/work/srp/Emails.java @@ -0,0 +1,38 @@ +package ood.work.srp; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Created by Administrator on 2017/6/17 0017. + */ +public class Emails { + + public static Email newEmail(User user, Product product) { + String subject = "您关注的产品降价了"; + String message = "尊敬的 "+user.getName()+", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!" ; + return new Email(user.getEmail(), subject, message); + } + + public static List createEmails(String path) throws IOException { + List products = ProductInfoLoader.readFile(path); + List mails = new ArrayList<>(); + for (Product product : products) { + String sql = getSql(product.getProductId()); + List users = DBUtil.query(sql); + for (User user : users) { + Email mail = Emails.newEmail(user, product); + mails.add(mail); + } + } + return mails; + } + + private static String getSql(String productId) { + System.out.println("loadQuery set"); + return "Select name from subscriptions " + + "where product_id= '" + productId +"' " + + "and send_mail=1 "; + } +} diff --git a/students/494800949/src/main/java/ood/work/srp/MailUtil.java b/students/494800949/src/main/java/ood/work/srp/MailUtil.java new file mode 100644 index 0000000000..43ab9a4339 --- /dev/null +++ b/students/494800949/src/main/java/ood/work/srp/MailUtil.java @@ -0,0 +1,24 @@ +package ood.work.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + public static void sendEmail(Email mailInfo, String fromAddress, String smtphost, boolean debug) { + String toAddress = mailInfo.getToAddress(); + String subject = mailInfo.getSubject(); + String message = mailInfo.getMessage(); + sendEmail(toAddress, fromAddress, subject, message, smtphost, debug); + } + +} diff --git a/students/494800949/src/main/java/ood/work/srp/Product.java b/students/494800949/src/main/java/ood/work/srp/Product.java new file mode 100644 index 0000000000..b3b4400014 --- /dev/null +++ b/students/494800949/src/main/java/ood/work/srp/Product.java @@ -0,0 +1,26 @@ +package ood.work.srp; + +/** + * Created by Administrator on 2017/6/17 0017. + * 商品类 + */ +public class Product { + private String productId; + private String productDesc; + + public String getProductId() { + return productId; + } + + public void setProductId(String productId) { + this.productId = productId; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git a/students/494800949/src/main/java/ood/work/srp/ProductInfoLoader.java b/students/494800949/src/main/java/ood/work/srp/ProductInfoLoader.java new file mode 100644 index 0000000000..8a484e9524 --- /dev/null +++ b/students/494800949/src/main/java/ood/work/srp/ProductInfoLoader.java @@ -0,0 +1,35 @@ +package ood.work.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Created by Administrator on 2017/6/17 0017. + */ +public class ProductInfoLoader { + + public static List readFile(String path) throws IOException // @02C + { + File file = new File(path); + List products = new ArrayList<>(); + try(BufferedReader br = new BufferedReader(new FileReader(file))) { + String line; + while ((line = br.readLine()) != null) { + String[] data = line.split(" "); + Product product = new Product(); + product.setProductId(data[0]); + product.setProductDesc(data[1]); + products.add(product); + System.out.println("产品ID = " + product.getProductId() + "\n"); + System.out.println("产品描述 = " + product.getProductDesc() + "\n"); + } + } catch (IOException e) { + throw new IOException(e.getMessage()); + } + return products; + } +} diff --git a/students/494800949/src/main/java/ood/work/srp/PromotionMail.java b/students/494800949/src/main/java/ood/work/srp/PromotionMail.java new file mode 100644 index 0000000000..fb9e5e0774 --- /dev/null +++ b/students/494800949/src/main/java/ood/work/srp/PromotionMail.java @@ -0,0 +1,32 @@ +package ood.work.srp; + +import java.io.IOException; + +/** + * Created by Administrator on 2017/6/17 0017. + */ +public class PromotionMail { + + private String path; + + public PromotionMail(String path) { + this.path = path; + } + + public void execute() throws IOException { + SMTPClient client = new SMTPClient(); + client.sendEmails(false, Emails.createEmails(path)); + } + + + + public static void main(String[] args) { + String path = "I:\\sourceCode\\coding2017_2\\students\\494800949\\src\\main\\java\\ood\\assignment\\srp\\product_promotion.txt"; + PromotionMail mail = new PromotionMail(path); + try { + mail.execute(); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + } +} diff --git a/students/494800949/src/main/java/ood/work/srp/SMTPClient.java b/students/494800949/src/main/java/ood/work/srp/SMTPClient.java new file mode 100644 index 0000000000..dda491e029 --- /dev/null +++ b/students/494800949/src/main/java/ood/work/srp/SMTPClient.java @@ -0,0 +1,71 @@ +package ood.work.srp; + +import java.util.Iterator; +import java.util.List; + +/** + * Created by Administrator on 2017/6/17 0017. + * + */ +public class SMTPClient { + + private String smtpHost; + private String altSmtpHost; + private String emailAdmin; + + public void config() { + Configuration configuration = new Configuration(); + this.smtpHost = configuration.getProperty(ConfigurationKeys.SMTP_SERVER); + this.altSmtpHost = configuration.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + this.emailAdmin = configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + public SMTPClient() { + config(); + } + + /** + * 发送一封邮件 + * @param debug + * @param mailInfo + */ + public void sendEmail(boolean debug, Email mailInfo) { + try + { + if (mailInfo.getToAddress().length() > 0) + MailUtil.sendEmail(mailInfo, emailAdmin, smtpHost, debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(mailInfo, emailAdmin, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + + /** + * 发送多封邮件 + */ + + public void sendEmails(boolean debug, List mailingList){ + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + sendEmail(debug, iter.next()); + } + } + else { + System.out.println("没有邮件发送"); + } + } + + + +} diff --git a/students/494800949/src/main/java/ood/work/srp/User.java b/students/494800949/src/main/java/ood/work/srp/User.java new file mode 100644 index 0000000000..091f594199 --- /dev/null +++ b/students/494800949/src/main/java/ood/work/srp/User.java @@ -0,0 +1,25 @@ +package ood.work.srp; + +/** + * Created by Administrator on 2017/6/17 0017. + */ +public class User { + private String name; + private String email; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/students/495232796/OOD/LiteJUnit/pom.xml b/students/495232796/OOD/LiteJUnit/pom.xml new file mode 100644 index 0000000000..84bf4627e3 --- /dev/null +++ b/students/495232796/OOD/LiteJUnit/pom.xml @@ -0,0 +1,42 @@ + + 4.0.0 + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.7 + 1.7 + + + + + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + \ No newline at end of file diff --git a/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/Assert.java b/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/Assert.java new file mode 100644 index 0000000000..c381fa242a --- /dev/null +++ b/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/Assert.java @@ -0,0 +1,28 @@ +package com.coderising.litejunit; + +public class Assert { + static public void assertEquals(int expected, int actual) { + assertEquals(null, new Integer(expected), new Integer(actual)); + } + + static public void assertEquals(String message, Object expected, Object actual) { + if (expected == null && actual == null) { + return ; + } + if (expected != null && expected.equals(actual)) { + return ; + } + failNotEquals(message, expected, actual); + } + + static public void fail(String message) { + throw new AssertionFailedError(message); + } + + static private void failNotEquals(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected:<"+expected+"> but was:<"+actual+">"); + } +} diff --git a/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/AssertionFailedError.java b/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/AssertionFailedError.java new file mode 100644 index 0000000000..928d0713d9 --- /dev/null +++ b/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/AssertionFailedError.java @@ -0,0 +1,10 @@ +package com.coderising.litejunit; + +public class AssertionFailedError extends Error { + + public AssertionFailedError () { + } + public AssertionFailedError (String message) { + super (message); + } +} diff --git a/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/Calculator.java b/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/Calculator.java new file mode 100644 index 0000000000..b76d82c9d2 --- /dev/null +++ b/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/Calculator.java @@ -0,0 +1,17 @@ +package com.coderising.litejunit; + +public class Calculator { + private int result = 0; + + public void add(int num) { + result += num; + } + + public void substract(int num) { + result -= num; + } + + public int getResult() { + return result; + } +} diff --git a/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/CalculatorTest.java b/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/CalculatorTest.java new file mode 100644 index 0000000000..8e31d51766 --- /dev/null +++ b/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/CalculatorTest.java @@ -0,0 +1,39 @@ +package com.coderising.litejunit; + +public class CalculatorTest extends TestCase{ + private Calculator cal = null; + + public CalculatorTest(String name) { + super(name); + // TODO Auto-generated constructor stub + } + + public void setUp() { + cal = new Calculator(); + } + + public void tearDown() { + cal = null; + } + + public void testAdd() { + cal.add(10); + Assert.assertEquals(cal.getResult(), 10); + } + + public void testSubstract() { + cal.add(10); + cal.substract(5); + assertEquals(cal.getResult(), 50); + } + + public static void main(String[] args){ + TestSuite ts = new TestSuite(CalculatorTest.class); + TestResult tr = new TestResult(); + ts.run(tr); + System.out.println(tr.wasSuccessful()); + for(TestFailure failure : tr.failures){ + System.err.println(failure); + } + } +} diff --git a/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/Test.java b/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/Test.java new file mode 100644 index 0000000000..ffbc4b336f --- /dev/null +++ b/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/Test.java @@ -0,0 +1,6 @@ +package com.coderising.litejunit; + +public interface Test { + public abstract int countTestCases(); + public void run(TestResult tr); +} diff --git a/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/TestCase.java b/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/TestCase.java new file mode 100644 index 0000000000..2961924618 --- /dev/null +++ b/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/TestCase.java @@ -0,0 +1,71 @@ +package com.coderising.litejunit; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +public class TestCase extends Assert implements Test{ + private String name; + + public TestCase(String name) { + this.name = name; + } + + @Override + public int countTestCases() { + return 1; + } + + @Override + public void run(TestResult tr) { + tr.run(this); + } + + public void doRun() throws Throwable { + setUp(); + + try { + runTest(); + } finally { + tearDown(); + } + + } + + protected void runTest() throws Throwable { + Method method = null; + + try { + method = getClass().getMethod(name, null); + } catch (NoSuchMethodException e) { + fail("method " + name + "is not found."); + } + + if (!Modifier.isPublic(method.getModifiers())) { + fail("method " + name + " is not public."); + } + + try { + method.invoke(this, new Class[0]); + } catch (IllegalArgumentException e) { + e.fillInStackTrace(); + throw e; + } catch (InvocationTargetException e) { + e.fillInStackTrace(); + throw e.getTargetException(); + } catch (IllegalAccessException e) { + e.fillInStackTrace(); + throw e; + } + + } + + protected void setUp() { + + } + + protected void tearDown() { + + } + +} diff --git a/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/TestFailure.java b/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/TestFailure.java new file mode 100644 index 0000000000..340a11a2dc --- /dev/null +++ b/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/TestFailure.java @@ -0,0 +1,26 @@ +package com.coderising.litejunit; + +public class TestFailure { + protected Test failedTest; + protected Throwable thrownException; + + public TestFailure(Test failedTest, Throwable thrownException) { + this.failedTest= failedTest; + this.thrownException= thrownException; + } + + + public Test failedTest() { + return failedTest; + } + + public Throwable thrownException() { + return thrownException; + } + + public String toString() { + StringBuffer buffer= new StringBuffer(); + buffer.append(failedTest+": "+thrownException.getMessage()); + return buffer.toString(); + } +} diff --git a/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/TestResult.java b/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/TestResult.java new file mode 100644 index 0000000000..41c9887857 --- /dev/null +++ b/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/TestResult.java @@ -0,0 +1,61 @@ +package com.coderising.litejunit; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class TestResult { + private boolean stop; + protected List failures; + protected List errors; + protected int testCount; + + public TestResult() { + failures= new ArrayList<>(); + errors= new ArrayList<>(); + + testCount= 0; + stop= false; + } + public void startTest(Test test) { + int count= test.countTestCases(); + testCount+= count; + } + + public void endTest(Test test) { + } + + public void run(TestCase tc) { + startTest(tc); + + try { + tc.doRun(); + } catch (AssertionFailedError e) { + addFailure(tc, e); + } catch (Throwable e) { + addError(tc, e); + } + + endTest(tc); + } + + public boolean shouldStop() { + return this.stop; + } + + public void addError(Test test, Throwable t) { + errors.add(new TestFailure(test, t)); + } + + public void addFailure(Test test, AssertionFailedError t) { + failures.add(new TestFailure(test, t)); + } + + public Iterator failures() { + return failures.iterator(); + } + + public boolean wasSuccessful() { + return failures.size() == 0 && errors.size() == 0; + } +} diff --git a/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/TestSuite.java b/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/TestSuite.java new file mode 100644 index 0000000000..60d8f855af --- /dev/null +++ b/students/495232796/OOD/LiteJUnit/src/main/java/com/coderising/litejunit/TestSuite.java @@ -0,0 +1,128 @@ +package com.coderising.litejunit; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +public class TestSuite implements Test{ + private List tests= new ArrayList<>(); + private String name; + public TestSuite(){ + + } + + public TestSuite(final Class tClass) { + this.name = tClass.getName(); + Constructor constructor = null; + try { + constructor = getConstructor(tClass); + } catch (NoSuchMethodException e) { + addTest(warning("Class " + name + " has no public constructor TestCase(String name).")); + return ; + } + + if (!Modifier.isPublic(tClass.getModifiers())) { + addTest(warning("Class " + name + " is not public.")); + return ; + } + + List names = new ArrayList<>(); + Method[] methods = tClass.getDeclaredMethods(); + for (Method m : methods) { + addTestMethod(m, names, constructor); + } + + if (tests.size() == 0) { + addTest(warning("No testcase in Class " + name)); + } + } + + private void addTestMethod(Method m, List names, Constructor constructor) { + String name = m.getName(); + if (names.contains(name)) { + return ; + } + + if (isPublicMethod(m)) { + names.add(name); + Object[] args = new Object[]{name}; + + try { + addTest((Test)constructor.newInstance(args)); + } catch (InstantiationException e) { + addTest(warning("Method " + name + " InstantiationException:" + exceptionToString(e))); + } catch (IllegalAccessException e) { + addTest(warning("Method " + name + " IllegalAccessException:" + exceptionToString(e))); + } catch (IllegalArgumentException e) { + addTest(warning("Method " + name + " IllegalArgumentException:" + exceptionToString(e))); + } catch (InvocationTargetException e) { + addTest(warning("Method " + name + " InvocationTargetException:" + exceptionToString(e))); + } + } else { + if (isTestMethod(m)) { + addTest(warning("Test method " + name + " is not public.")); + } + } + } + + private String exceptionToString(Throwable t) { + StringWriter stringWriter= new StringWriter(); + PrintWriter writer= new PrintWriter(stringWriter); + t.printStackTrace(writer); + return stringWriter.toString(); + + } + + private boolean isPublicMethod(Method m) { + return isTestMethod(m) && Modifier.isPublic(m.getModifiers()); + } + private boolean isTestMethod(Method m) { + String name = m.getName(); + Class[] parameters = m.getParameterTypes(); + Class retType = m.getReturnType(); + + return parameters.length == 0 && name.startsWith("test") && retType.equals(Void.TYPE); + } + + private Test warning(final String message) { + return new TestCase("warning") { + public void doRun() { + fail(message); + } + }; + } + + public void addTest(Test t) { + this.tests.add(t); + } + + private Constructor getConstructor(Class theClass) throws NoSuchMethodException { + Class[] args= { String.class }; + return theClass.getConstructor(args); + } + + @Override + public int countTestCases() { + int cnt = 0; + for (Test t : tests) { + cnt += t.countTestCases(); + } + return cnt; + } + + @Override + public void run(TestResult tr) { + for (Test t : tests) { + if (tr.shouldStop()) { + break; + } + t.run(tr);; + } + } + +} diff --git a/students/495232796/OOD/UML/DiceGame-class.jpg b/students/495232796/OOD/UML/DiceGame-class.jpg new file mode 100644 index 0000000000..869d72dd5e Binary files /dev/null and b/students/495232796/OOD/UML/DiceGame-class.jpg differ diff --git a/students/495232796/OOD/UML/DiceGame-sequence.jpg b/students/495232796/OOD/UML/DiceGame-sequence.jpg new file mode 100644 index 0000000000..8d6b90e9b3 Binary files /dev/null and b/students/495232796/OOD/UML/DiceGame-sequence.jpg differ diff --git a/students/495232796/OOD/UML/ShoppingSite.jpg b/students/495232796/OOD/UML/ShoppingSite.jpg new file mode 100644 index 0000000000..5e05336f62 Binary files /dev/null and b/students/495232796/OOD/UML/ShoppingSite.jpg differ diff --git a/students/495232796/OOD/bridgepattern/DrawCircle.java b/students/495232796/OOD/bridgepattern/DrawCircle.java new file mode 100644 index 0000000000..a9d515fbb4 --- /dev/null +++ b/students/495232796/OOD/bridgepattern/DrawCircle.java @@ -0,0 +1,15 @@ +package com.coderising.dp.bridge; + +public class DrawCircle extends Shape{ + public int x, y, r; + + public DrawCircle(Drawing drawing, int x, int y, int r) { + super(drawing); + this.x =x; + this.y = y; + this.r = r; + } + public void draw() { + this.drawing.drawCircle(x, y, r); + } +} diff --git a/students/495232796/OOD/bridgepattern/DrawLine.java b/students/495232796/OOD/bridgepattern/DrawLine.java new file mode 100644 index 0000000000..df0271d16b --- /dev/null +++ b/students/495232796/OOD/bridgepattern/DrawLine.java @@ -0,0 +1,16 @@ +package com.coderising.dp.bridge; + +public class DrawLine extends Shape{ + int x1, y1, x2, y2; + + public DrawLine(Drawing drawing, int x1, int y1, int x2, int y2) { + super(drawing); + this.x1 = x1; + this.x2 = x2; + this.y1 = y1; + this.y2 = y2; + } + public void draw() { + this.drawing.drawLine(x1, y1, x2, y2); + } +} diff --git a/students/495232796/OOD/bridgepattern/Drawing.java b/students/495232796/OOD/bridgepattern/Drawing.java new file mode 100644 index 0000000000..3149c68822 --- /dev/null +++ b/students/495232796/OOD/bridgepattern/Drawing.java @@ -0,0 +1,6 @@ +package com.coderising.dp.bridge; + +public interface Drawing { + public void drawLine(int x1,int y1,int x2,int y2); + public void drawCircle(int x,int y, int r); +} diff --git a/students/495232796/OOD/bridgepattern/GraphicLibrary1.java b/students/495232796/OOD/bridgepattern/GraphicLibrary1.java new file mode 100644 index 0000000000..1ecf2f0548 --- /dev/null +++ b/students/495232796/OOD/bridgepattern/GraphicLibrary1.java @@ -0,0 +1,10 @@ +package com.coderising.dp.bridge; + +public class GraphicLibrary1{ + public void draw_a_line(int x1,int y1,int x2,int y2){ + System.out.println("Draw a line with using library1."); + } + public void draw_a_circle(int x,int y, int r){ + System.out.println("Draw a circle with using library1"); + } +} diff --git a/students/495232796/OOD/bridgepattern/GraphicLibrary1Adapter.java b/students/495232796/OOD/bridgepattern/GraphicLibrary1Adapter.java new file mode 100644 index 0000000000..8e33fd2482 --- /dev/null +++ b/students/495232796/OOD/bridgepattern/GraphicLibrary1Adapter.java @@ -0,0 +1,15 @@ +package com.coderising.dp.bridge; + +public class GraphicLibrary1Adapter implements Drawing{ + GraphicLibrary1 glib = new GraphicLibrary1(); + @Override + public void drawLine(int x1, int y1, int x2, int y2) { + this.glib.draw_a_line(x1, y1, x2, y2); + } + + @Override + public void drawCircle(int x, int y, int r) { + this.glib.draw_a_circle(x, y, r); + } + +} diff --git a/students/495232796/OOD/bridgepattern/GraphicLibrary2.java b/students/495232796/OOD/bridgepattern/GraphicLibrary2.java new file mode 100644 index 0000000000..f008fa54db --- /dev/null +++ b/students/495232796/OOD/bridgepattern/GraphicLibrary2.java @@ -0,0 +1,10 @@ +package com.coderising.dp.bridge; + +public class GraphicLibrary2 implements Drawing{ + public void drawLine(int x1,int x2,int y1,int y2){ + System.out.println("Draw a line with using library2."); + } + public void drawCircle(int x,int y, int r){ + System.out.println("Draw a circle with using library2."); + } +} diff --git a/students/495232796/OOD/bridgepattern/Shape.java b/students/495232796/OOD/bridgepattern/Shape.java new file mode 100644 index 0000000000..34861f43f9 --- /dev/null +++ b/students/495232796/OOD/bridgepattern/Shape.java @@ -0,0 +1,10 @@ +package com.coderising.dp.bridge; + +public abstract class Shape { + public Drawing drawing; + public Shape(Drawing drawing) { + this.drawing = drawing; + } + public void draw() { + } +} diff --git a/students/495232796/OOD/builderpattern/pom.xml b/students/495232796/OOD/builderpattern/pom.xml new file mode 100644 index 0000000000..84bf4627e3 --- /dev/null +++ b/students/495232796/OOD/builderpattern/pom.xml @@ -0,0 +1,42 @@ + + 4.0.0 + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.7 + 1.7 + + + + + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + \ No newline at end of file diff --git a/students/495232796/OOD/builderpattern/src/main/java/com/coderising/dp/builder/TagBuilder.java b/students/495232796/OOD/builderpattern/src/main/java/com/coderising/dp/builder/TagBuilder.java new file mode 100644 index 0000000000..cf143e1ee6 --- /dev/null +++ b/students/495232796/OOD/builderpattern/src/main/java/com/coderising/dp/builder/TagBuilder.java @@ -0,0 +1,41 @@ +package com.coderising.dp.builder; + +public class TagBuilder { + private TagNode rootNode = null; + private TagNode curNode = null; + private TagNode parentNode = null; + + public TagBuilder(String rootTagName){ + rootNode = new TagNode(rootTagName); + curNode = rootNode; + } + + public TagBuilder addChild(String childTagName){ + TagNode tn = new TagNode(childTagName); + curNode.add(tn); + parentNode = curNode; + curNode = tn; + + return this; + } + public TagBuilder addSibling(String siblingTagName){ + TagNode tn = new TagNode(siblingTagName); + parentNode.add(tn); + curNode = tn; + + return this; + } + public TagBuilder setAttribute(String name, String value){ + curNode.setAttribute(name, value); + + return this; + } + public TagBuilder setText(String value){ + curNode.setValue(value); + + return this; + } + public String toXML(){ + return rootNode.toXML(); + } +} diff --git a/students/495232796/OOD/builderpattern/src/main/java/com/coderising/dp/builder/TagBuilderTest.java b/students/495232796/OOD/builderpattern/src/main/java/com/coderising/dp/builder/TagBuilderTest.java new file mode 100644 index 0000000000..e98cfae947 --- /dev/null +++ b/students/495232796/OOD/builderpattern/src/main/java/com/coderising/dp/builder/TagBuilderTest.java @@ -0,0 +1,41 @@ +package com.coderising.dp.builder; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class TagBuilderTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testToXML() { + + TagBuilder builder = new TagBuilder("order"); + + String xml = builder.addChild("line-items") + .addChild("line-item").setAttribute("pid", "P3677").setAttribute("qty", "3") + .addSibling("line-item").setAttribute("pid", "P9877").setAttribute("qty", "10") + .toXML(); + + String expected = "" + + "" + + "" + + "" + + "" + + ""; + + System.out.println(xml); + System.out.println(expected.equals(xml)); + assertEquals(expected, xml); + } + +} diff --git a/students/495232796/OOD/builderpattern/src/main/java/com/coderising/dp/builder/TagNode.java b/students/495232796/OOD/builderpattern/src/main/java/com/coderising/dp/builder/TagNode.java new file mode 100644 index 0000000000..6a31e04192 --- /dev/null +++ b/students/495232796/OOD/builderpattern/src/main/java/com/coderising/dp/builder/TagNode.java @@ -0,0 +1,82 @@ +package com.coderising.dp.builder; + +import java.util.ArrayList; +import java.util.List; + +public class TagNode { + private String tagName; + private String tagValue; + private List children = new ArrayList<>(); + private List attributes = new ArrayList<>(); + + public TagNode(String name){ + this.tagName = name; + } + public void add(TagNode child){ + this.children.add(child); + } + public void setAttribute(String name, String value) { + Attribute attr = findAttribute(name); + if(attr != null){ + attr.value = value; + } else { + attributes.add(new Attribute(name,value)); + } + } + private Attribute findAttribute(String name){ + for(Attribute attr : attributes){ + if(attr.name.equals(name)){ + return attr; + } + } + return null; + } + public void setValue(String value) { + this.tagValue = value; + + } + public String getTagName() { + return tagName; + } + public List getChildren() { + return children; + } + + private static class Attribute{ + public Attribute(String name, String value) { + this.name = name; + this.value = value; + } + String name; + String value; + + } + public String toXML(){ + return toXML(this); + } + private String toXML(TagNode node){ + StringBuilder buffer = new StringBuilder(); + buffer.append("<").append(node.tagName); + if(node.attributes.size()> 0){ + for(int i=0;i"); + return buffer.toString(); + } + buffer.append(">"); + for(TagNode childNode : node.children){ + buffer.append(toXML(childNode)); + } + buffer.append(""); + + + return buffer.toString(); + } + private String toXML(Attribute attr){ + return attr.name+"=\""+attr.value + "\""; + } +} diff --git a/students/495232796/OOD/builderpattern/src/main/java/com/coderising/dp/main/TestAll.java b/students/495232796/OOD/builderpattern/src/main/java/com/coderising/dp/main/TestAll.java new file mode 100644 index 0000000000..d5ab3b0f05 --- /dev/null +++ b/students/495232796/OOD/builderpattern/src/main/java/com/coderising/dp/main/TestAll.java @@ -0,0 +1,17 @@ +package com.coderising.dp.main; + +import com.coderising.dp.builder.TagBuilderTest; + +public class TestAll { + + public void testTag() { + TagBuilderTest tt = new TagBuilderTest(); + tt.testToXML(); + } + + public static void main(String[] args) { + TestAll ta = new TestAll(); + ta.testTag(); + } + +} diff --git a/students/495232796/OOD/commandpattern/pom.xml b/students/495232796/OOD/commandpattern/pom.xml new file mode 100644 index 0000000000..84bf4627e3 --- /dev/null +++ b/students/495232796/OOD/commandpattern/pom.xml @@ -0,0 +1,42 @@ + + 4.0.0 + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.7 + 1.7 + + + + + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + \ No newline at end of file diff --git a/students/495232796/OOD/commandpattern/src/main/java/com/coderising/dp/command/Cook.java b/students/495232796/OOD/commandpattern/src/main/java/com/coderising/dp/command/Cook.java new file mode 100644 index 0000000000..d832433731 --- /dev/null +++ b/students/495232796/OOD/commandpattern/src/main/java/com/coderising/dp/command/Cook.java @@ -0,0 +1,11 @@ +package com.coderising.dp.command; + +public class Cook { + public void cookSteak() { + System.out.println("Steak is OK."); + } + + public void cookPork() { + System.out.println("Pork is OK."); + } +} diff --git a/students/495232796/OOD/commandpattern/src/main/java/com/coderising/dp/command/OrderCommand.java b/students/495232796/OOD/commandpattern/src/main/java/com/coderising/dp/command/OrderCommand.java new file mode 100644 index 0000000000..361a489e6e --- /dev/null +++ b/students/495232796/OOD/commandpattern/src/main/java/com/coderising/dp/command/OrderCommand.java @@ -0,0 +1,5 @@ +package com.coderising.dp.command; + +public interface OrderCommand { + public void doOrder(); +} diff --git a/students/495232796/OOD/commandpattern/src/main/java/com/coderising/dp/command/OrderPorkCommand.java b/students/495232796/OOD/commandpattern/src/main/java/com/coderising/dp/command/OrderPorkCommand.java new file mode 100644 index 0000000000..cbe37e372a --- /dev/null +++ b/students/495232796/OOD/commandpattern/src/main/java/com/coderising/dp/command/OrderPorkCommand.java @@ -0,0 +1,14 @@ +package com.coderising.dp.command; + +public class OrderPorkCommand implements OrderCommand{ + private Cook cook; + + public OrderPorkCommand(Cook cook) { + this.cook = cook; + } + + @Override + public void doOrder() { + this.cook.cookPork();; + } +} diff --git a/students/495232796/OOD/commandpattern/src/main/java/com/coderising/dp/command/OrderSteakCommand.java b/students/495232796/OOD/commandpattern/src/main/java/com/coderising/dp/command/OrderSteakCommand.java new file mode 100644 index 0000000000..9884e14bb2 --- /dev/null +++ b/students/495232796/OOD/commandpattern/src/main/java/com/coderising/dp/command/OrderSteakCommand.java @@ -0,0 +1,15 @@ +package com.coderising.dp.command; + +public class OrderSteakCommand implements OrderCommand{ + private Cook cook; + + public OrderSteakCommand(Cook cook) { + this.cook = cook; + } + + @Override + public void doOrder() { + this.cook.cookSteak(); + } + +} diff --git a/students/495232796/OOD/commandpattern/src/main/java/com/coderising/dp/command/Waiter.java b/students/495232796/OOD/commandpattern/src/main/java/com/coderising/dp/command/Waiter.java new file mode 100644 index 0000000000..acc9f1418e --- /dev/null +++ b/students/495232796/OOD/commandpattern/src/main/java/com/coderising/dp/command/Waiter.java @@ -0,0 +1,18 @@ +package com.coderising.dp.command; + +import java.util.LinkedList; +import java.util.List; + +public class Waiter { + private List orderList = new LinkedList<>(); + + public void addOrder(OrderCommand order) { + this.orderList.add(order); + } + + public void sendOrders() { + for (int i = 0; i < orderList.size(); i++) { + orderList.get(i).doOrder(); + } + } +} diff --git a/students/495232796/OOD/compositepattern/Line.java b/students/495232796/OOD/compositepattern/Line.java new file mode 100644 index 0000000000..884e8d9220 --- /dev/null +++ b/students/495232796/OOD/compositepattern/Line.java @@ -0,0 +1,10 @@ +package com.coderising.dp.composite; + +public class Line implements Shape { + + @Override + public void draw() { + System.out.println("This is a line."); + } + +} diff --git a/students/495232796/OOD/compositepattern/Picture.java b/students/495232796/OOD/compositepattern/Picture.java new file mode 100644 index 0000000000..8029dc4aac --- /dev/null +++ b/students/495232796/OOD/compositepattern/Picture.java @@ -0,0 +1,19 @@ +package com.coderising.dp.composite; + +import java.util.ArrayList; +import java.util.List; + +public class Picture implements Shape{ + List shapes = new ArrayList<>(); + + @Override + public void draw() { + for(Shape shape : shapes) { + shape.draw(); + } + } + + public void addShape(Shape shape) { + shapes.add(shape); + } +} diff --git a/students/495232796/OOD/compositepattern/Rectangle.java b/students/495232796/OOD/compositepattern/Rectangle.java new file mode 100644 index 0000000000..d0734b4d63 --- /dev/null +++ b/students/495232796/OOD/compositepattern/Rectangle.java @@ -0,0 +1,10 @@ +package com.coderising.dp.composite; + +public class Rectangle implements Shape { + + @Override + public void draw() { + System.out.println("This is a rectangle."); + } + +} diff --git a/students/495232796/OOD/compositepattern/Shape.java b/students/495232796/OOD/compositepattern/Shape.java new file mode 100644 index 0000000000..4562f10b12 --- /dev/null +++ b/students/495232796/OOD/compositepattern/Shape.java @@ -0,0 +1,5 @@ +package com.coderising.dp.composite; + +public interface Shape { + public void draw(); +} diff --git a/students/495232796/OOD/compositepattern/Square.java b/students/495232796/OOD/compositepattern/Square.java new file mode 100644 index 0000000000..30ab0e7b85 --- /dev/null +++ b/students/495232796/OOD/compositepattern/Square.java @@ -0,0 +1,10 @@ +package com.coderising.dp.composite; + +public class Square implements Shape { + + @Override + public void draw() { + System.out.println("This is a sqare."); + } + +} diff --git a/students/495232796/OOD/compositepattern/Text.java b/students/495232796/OOD/compositepattern/Text.java new file mode 100644 index 0000000000..0f831f62fe --- /dev/null +++ b/students/495232796/OOD/compositepattern/Text.java @@ -0,0 +1,10 @@ +package com.coderising.dp.composite; + +public class Text implements Shape { + + @Override + public void draw() { + System.out.println("This is a text."); + } + +} diff --git a/students/495232796/OOD/decoratorpattern/Email.java b/students/495232796/OOD/decoratorpattern/Email.java new file mode 100644 index 0000000000..064de1e837 --- /dev/null +++ b/students/495232796/OOD/decoratorpattern/Email.java @@ -0,0 +1,6 @@ +package com.coderising.dp.decorator; + +public interface Email { + public String getContent(); +} + diff --git a/students/495232796/OOD/decoratorpattern/EmailDecorator.java b/students/495232796/OOD/decoratorpattern/EmailDecorator.java new file mode 100644 index 0000000000..61ea7c2d2a --- /dev/null +++ b/students/495232796/OOD/decoratorpattern/EmailDecorator.java @@ -0,0 +1,13 @@ +package com.coderising.dp.decorator; + +public abstract class EmailDecorator implements Email{ + protected Email email; + + public EmailDecorator(Email e) { + this.email = e; + } + + public String getContent(){ + return this.email.getContent(); + } +} \ No newline at end of file diff --git a/students/495232796/OOD/decoratorpattern/EmailEncryptionDecorator.java b/students/495232796/OOD/decoratorpattern/EmailEncryptionDecorator.java new file mode 100644 index 0000000000..65a6e56a26 --- /dev/null +++ b/students/495232796/OOD/decoratorpattern/EmailEncryptionDecorator.java @@ -0,0 +1,20 @@ +package com.coderising.dp.decorator; + +public class EmailEncryptionDecorator extends EmailDecorator{ + + public EmailEncryptionDecorator(Email e) { + super(e); + } + + public String encryptContext() { + return this.email.getContent(); + } + + public String decryptContext() { + return this.email.getContent(); + } + + public String getContent() { + return this.encryptContext(); + } +} diff --git a/students/495232796/OOD/decoratorpattern/EmailImpl.java b/students/495232796/OOD/decoratorpattern/EmailImpl.java new file mode 100644 index 0000000000..640aef6da3 --- /dev/null +++ b/students/495232796/OOD/decoratorpattern/EmailImpl.java @@ -0,0 +1,12 @@ +package com.coderising.dp.decorator; + +public class EmailImpl implements Email { + private String content; + + public EmailImpl(String content) { + this.content = content; + } + public String getContent() { + return content; + } +} diff --git a/students/495232796/OOD/decoratorpattern/EmailStatementDecorator.java b/students/495232796/OOD/decoratorpattern/EmailStatementDecorator.java new file mode 100644 index 0000000000..15e14ecabd --- /dev/null +++ b/students/495232796/OOD/decoratorpattern/EmailStatementDecorator.java @@ -0,0 +1,22 @@ +package com.coderising.dp.decorator; + +public class EmailStatementDecorator extends EmailDecorator{ + private String statement; + + public EmailStatementDecorator(Email e) { + super(e); + } + + public String getStatement() { + return statement; + } + + public void setStatement(String statement) { + this.statement = statement; + } + + public String getContent() { + return this.email.getContent() + this.statement; + } + +} diff --git a/students/495232796/OOD/ood-assignment/config/product_promotion.txt b/students/495232796/OOD/ood-assignment/config/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/495232796/OOD/ood-assignment/config/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/495232796/OOD/ood-assignment/pom.xml b/students/495232796/OOD/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/495232796/OOD/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/ComSender.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/ComSender.java new file mode 100644 index 0000000000..19f2c796b0 --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/ComSender.java @@ -0,0 +1,7 @@ +package com.coderising.ood.ocp; + +public class ComSender implements Sender { + public void send(String msg) { + System.out.println(msg); + } +} diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java new file mode 100644 index 0000000000..b6cf28c096 --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return null; + } + +} diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/LogType.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/LogType.java new file mode 100644 index 0000000000..d33d7d0240 --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/LogType.java @@ -0,0 +1,9 @@ +package com.coderising.ood.ocp; + +public class LogType { + public static final int RAW_LOG = 1; + public static final int RAW_LOG_WITH_DATE = 2; + public static final int EMAIL_LOG = 1; + public static final int SMS_LOG = 2; + public static final int PRINT_LOG = 3; +} diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java new file mode 100644 index 0000000000..45525df9ba --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java @@ -0,0 +1,25 @@ +package com.coderising.ood.ocp; + +public class Logger { + int type = 0; + int method = 0; + + public Logger(int logType, int logMethod){ + this.type = logType; + this.method = logMethod; + } + public void log(String msg){ + + String logMsg = msg; + + if(this.type == LogType.RAW_LOG){ + logMsg = msg; + } else if(this.type == LogType.RAW_LOG_WITH_DATE){ + String txtDate = DateUtil.getCurrentDateAsString(); + logMsg = txtDate + ": " + msg; + } + + SenderFactory.createSender(type).send(logMsg); + } +} + diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java new file mode 100644 index 0000000000..dff0eb9748 --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class MailUtil implements Sender{ + + public void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java new file mode 100644 index 0000000000..be47b2c084 --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class SMSUtil implements Sender { + + public void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/Sender.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/Sender.java new file mode 100644 index 0000000000..4bb54aa1e8 --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/Sender.java @@ -0,0 +1,5 @@ +package com.coderising.ood.ocp; + +public interface Sender { + public void send(String msg); +} diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/SenderFactory.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/SenderFactory.java new file mode 100644 index 0000000000..6915ff2992 --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/SenderFactory.java @@ -0,0 +1,15 @@ +package com.coderising.ood.ocp; + +public class SenderFactory { + public static Sender createSender(int type) { + if(type == LogType.EMAIL_LOG){ + return new MailUtil(); + } else if(type == LogType.SMS_LOG){ + return new SMSUtil(); + } else if(type == LogType.PRINT_LOG){ + return new ComSender(); + } + + return new ComSender(); + } +} diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Formatter.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Formatter.java new file mode 100644 index 0000000000..b6e2ccbc16 --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Formatter.java @@ -0,0 +1,7 @@ +package com.coderising.ood.ocp.good; + +public interface Formatter { + + String format(String msg); + +} diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/good/FormatterFactory.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/good/FormatterFactory.java new file mode 100644 index 0000000000..3c2009a674 --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/good/FormatterFactory.java @@ -0,0 +1,13 @@ +package com.coderising.ood.ocp.good; + +public class FormatterFactory { + public static Formatter createFormatter(int type){ + if(type == 1){ + return new RawFormatter(); + } + if (type == 2){ + return new HtmlFormatter(); + } + return null; + } +} diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/good/HtmlFormatter.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/good/HtmlFormatter.java new file mode 100644 index 0000000000..3d375f5acc --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/good/HtmlFormatter.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp.good; + +public class HtmlFormatter implements Formatter { + + @Override + public String format(String msg) { + + return null; + } + +} diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Logger.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Logger.java new file mode 100644 index 0000000000..f206472d0d --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Logger.java @@ -0,0 +1,18 @@ +package com.coderising.ood.ocp.good; + +public class Logger { + + private Formatter formatter; + private Sender sender; + + public Logger(Formatter formatter,Sender sender){ + this.formatter = formatter; + this.sender = sender; + } + public void log(String msg){ + sender.send(formatter.format(msg)) ; + } + + +} + diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/good/RawFormatter.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/good/RawFormatter.java new file mode 100644 index 0000000000..7f1cb4ae30 --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/good/RawFormatter.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp.good; + +public class RawFormatter implements Formatter { + + @Override + public String format(String msg) { + + return null; + } + +} diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Sender.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Sender.java new file mode 100644 index 0000000000..aaa46c1fb7 --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/ocp/good/Sender.java @@ -0,0 +1,7 @@ +package com.coderising.ood.ocp.good; + +public interface Sender { + + void send(String msg); + +} diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/CommonKeys.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/CommonKeys.java new file mode 100644 index 0000000000..2980cc40ca --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/CommonKeys.java @@ -0,0 +1,10 @@ +package com.coderising.ood.srp; + +public class CommonKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + public static final String NAME_KEY = "NAME"; + public static final String EMAIL_KEY = "EMAIL"; +} diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..13cc1b5890 --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(CommonKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(CommonKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(CommonKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..ff8215b4d2 --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put(CommonKeys.NAME_KEY, "User" + i); + userInfo.put(CommonKeys.EMAIL_KEY, "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/MailAddr.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/MailAddr.java new file mode 100644 index 0000000000..239166dd11 --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/MailAddr.java @@ -0,0 +1,42 @@ +package com.coderising.ood.srp; + +public class MailAddr { + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + + public MailAddr(Configuration config) { + reloadconfig(config); + } + + public void reloadconfig(Configuration config) { + smtpHost = config.getProperty(CommonKeys.SMTP_SERVER); + altSmtpHost = config.getProperty(CommonKeys.ALT_SMTP_SERVER); + fromAddress = config.getProperty(CommonKeys.EMAIL_ADMIN); + } + + public void setToAddress(String address) { + toAddress = address; + } + + public String getToAddress() { + return toAddress; + } + + public boolean checkToAddress() { + return toAddress.length() > 0; + } + + public String getSmtpHost() { + return smtpHost; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public String getFromAddress() { + return fromAddress; + } +} diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/MailMsg.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/MailMsg.java new file mode 100644 index 0000000000..dd834ccfef --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/MailMsg.java @@ -0,0 +1,19 @@ +package com.coderising.ood.srp; + +public class MailMsg { + protected String subject = null; + protected String message = null; + + public MailMsg(String sub, String msg) { + this.subject = sub; + this.message = msg; + } + + public String getSubject() { + return subject; + } + + public String getMessage() { + return message; + } +} diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..cfb2cffa7c --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,14 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(MailAddr mailAddr, MailMsg mailMsg, boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(mailAddr.getFromAddress()).append("\n"); + buffer.append("To:").append(mailAddr.getToAddress()).append("\n"); + buffer.append("Subject:").append(mailMsg.getSubject()).append("\n"); + buffer.append("Content:").append(mailMsg.getMessage()).append("\n"); + System.out.println(buffer.toString()); + } +} diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/ProductInfo.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/ProductInfo.java new file mode 100644 index 0000000000..ad68f0a7eb --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/ProductInfo.java @@ -0,0 +1,49 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +public class ProductInfo { + protected String productID = null; + protected String productDesc = null; + + public ProductInfo(String path) { + try { + readFile(path); + } catch (IOException e) { + e.printStackTrace(); + } + } + + protected void readFile(String path) throws IOException + { + File f = new File(path); + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(f)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + this.productID = data[0]; + this.productDesc = data[1]; + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + public String getProductID() { + return productID; + } + + public String getProductDesc() { + return productDesc; + } +} diff --git a/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..808caab9f8 --- /dev/null +++ b/students/495232796/OOD/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,89 @@ +package com.coderising.ood.srp; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + protected String sendMailQuery = null; + protected boolean emailDebug = false; + protected ProductInfo productInfo = null; + protected MailAddr mailAddr = null; + private static Configuration config; + + public static void main(String[] args) throws Exception { + String path = "D:\\projects\\OOD\\project\\ood-assignment\\config\\product_promotion.txt"; + + PromotionMail pe = new PromotionMail(path, false); + pe.sendEmails(); + } + + public PromotionMail(String path, boolean mailDebug) throws Exception { + this.emailDebug = mailDebug; + productInfo = new ProductInfo(path); + config = new Configuration(); + mailAddr = new MailAddr(config); + } + + protected void setLoadQuery() throws Exception { + sendMailQuery = "Select name from subscriptions " + "where product_id= '" + this.productInfo.getProductID() + + "' " + "and send_mail=1 "; + + System.out.println("loadQuery set"); + } + + protected MailMsg setMessage(HashMap userInfo) throws IOException { + + String name = (String) userInfo.get(CommonKeys.NAME_KEY); + + String subject = "您关注的产品降价了"; + String message = "尊敬的 " + name + ", 您关注的产品 " + this.productInfo.getProductDesc() + " 降价了,欢迎购买!"; + + return new MailMsg(subject, message); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + public void sendEmails() { + try { + setLoadQuery(); + sendEMails(emailDebug, loadMailingList()); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + protected void sendEMails(boolean debug, List mailingList) throws IOException { + System.out.println("开始发送邮件"); + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + HashMap userInfo = (HashMap) iter.next(); + mailAddr.setToAddress((String) userInfo.get(CommonKeys.EMAIL_KEY)); + if (mailAddr.checkToAddress()) { + MailMsg mailmsg = setMessage(userInfo); + try { + MailUtil.sendEmail(mailAddr, mailmsg, debug); + } catch (Exception e) { + try { + MailUtil.sendEmail(mailAddr, mailmsg, debug); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + } + } else { + System.out.println("没有邮件发送"); + } + + } +} diff --git a/students/495232796/OOD/payment/src/Affiliation/Affiliation.java b/students/495232796/OOD/payment/src/Affiliation/Affiliation.java new file mode 100644 index 0000000000..5e2dac8fa0 --- /dev/null +++ b/students/495232796/OOD/payment/src/Affiliation/Affiliation.java @@ -0,0 +1,7 @@ +package Affiliation; + +import PayCheck.PayCheck; + +public abstract class Affiliation { + public abstract double calculateDeduction(PayCheck pc); +} diff --git a/students/495232796/OOD/payment/src/Affiliation/NonAffiliation.java b/students/495232796/OOD/payment/src/Affiliation/NonAffiliation.java new file mode 100644 index 0000000000..d37c1e35ff --- /dev/null +++ b/students/495232796/OOD/payment/src/Affiliation/NonAffiliation.java @@ -0,0 +1,12 @@ +package Affiliation; + +import PayCheck.PayCheck; + +public class NonAffiliation extends Affiliation{ + + @Override + public double calculateDeduction(PayCheck pc) { + return 0.0; + } + +} diff --git a/students/495232796/OOD/payment/src/Affiliation/ServiceCharge.java b/students/495232796/OOD/payment/src/Affiliation/ServiceCharge.java new file mode 100644 index 0000000000..a7faa67adb --- /dev/null +++ b/students/495232796/OOD/payment/src/Affiliation/ServiceCharge.java @@ -0,0 +1,20 @@ +package Affiliation; + +import java.util.Date; + +public class ServiceCharge { + private Date date; + private double amount; + public double getAmount() { + return amount; + } + public void setAmount(double amount) { + this.amount = amount; + } + public Date getDate() { + return date; + } + public void setDate(Date date) { + this.date = date; + } +} diff --git a/students/495232796/OOD/payment/src/Affiliation/UnionAffiliation.java b/students/495232796/OOD/payment/src/Affiliation/UnionAffiliation.java new file mode 100644 index 0000000000..02e645ef1f --- /dev/null +++ b/students/495232796/OOD/payment/src/Affiliation/UnionAffiliation.java @@ -0,0 +1,27 @@ +package Affiliation; + +import java.util.Date; +import java.util.Map; + +import PayCheck.PayCheck; +import DateUtil.DateUtil; + +public class UnionAffiliation extends Affiliation{ + private String memId; + private double weeklyDue; + private Map serviceCharges; + @Override + public double calculateDeduction(PayCheck pc) { + int fridays = DateUtil.getFridays(pc.getPayPeriodStartDate(), pc.getPayPeriodEndDate()); + double totalDue = fridays*this.weeklyDue; + + double totalCharges = 0.0; + for (ServiceCharge sc : serviceCharges.values()) { + if (DateUtil.between(sc.getDate(), pc.getPayPeriodStartDate(), pc.getPayPeriodEndDate())) { + totalCharges += sc.getAmount(); + } + } + return totalDue+totalCharges; + } + +} diff --git a/students/495232796/OOD/payment/src/DateUtil/DateUtil.java b/students/495232796/OOD/payment/src/DateUtil/DateUtil.java new file mode 100644 index 0000000000..6ed884bfa8 --- /dev/null +++ b/students/495232796/OOD/payment/src/DateUtil/DateUtil.java @@ -0,0 +1,37 @@ +package DateUtil; + +import java.util.Date; + +public class DateUtil { + public static boolean isFriday(Date d) { + return true; + } + + public static Date add(Date d, int days) { + return new Date(); + } + + public static boolean isLastDayofMonth(Date d) { + return false; + } + + public static Date getFirstDay(Date d) { + return new Date(); + } + + public static long getDaysBetween(Date start, Date end) { + return 0; + } + + public static Date parseDay(String dayStr) { + return new Date(); + } + + public static boolean between(Date d, Date start, Date end) { + return true; + } + + public static int getFridays(Date start, Date end) { + return 0; + } +} diff --git a/students/495232796/OOD/payment/src/Employ/Employee.java b/students/495232796/OOD/payment/src/Employ/Employee.java new file mode 100644 index 0000000000..b21eec7869 --- /dev/null +++ b/students/495232796/OOD/payment/src/Employ/Employee.java @@ -0,0 +1,41 @@ +package Employ; + +import java.util.Date; + +import Affiliation.Affiliation; +import PayCheck.PayCheck; +import PaymentClassification.PaymentClassification; +import PaymentMethod.PaymentMethod; +import PaymentSchedule.PaymentSchedule; + +public class Employee { + private String id; + private String name; + private String address; + PaymentClassification payment; + PaymentSchedule paySch; + PaymentMethod payMethod; + Affiliation af; + + public Employee(String name, String address) { + this.name = name; + this.address = address; + } + public boolean isPayDay(Date d) { + return this.paySch.isPayDay(d); + } + + public Date getPayPeriodStartDate(Date d) { + return this.paySch.getPayPeriodStartDate(d); + } + + public void payDay(PayCheck pc) { + double grossPay = payment.calculatePay(pc); + double dedutions = af.calculateDeduction(pc); + double netPay = grossPay - dedutions; + pc.setGrossPay(grossPay); + pc.setDeductions(dedutions); + pc.setNetPay(netPay); + payMethod.pay(pc); + } +} diff --git a/students/495232796/OOD/payment/src/PayCheck/PayCheck.java b/students/495232796/OOD/payment/src/PayCheck/PayCheck.java new file mode 100644 index 0000000000..ceea1e41fe --- /dev/null +++ b/students/495232796/OOD/payment/src/PayCheck/PayCheck.java @@ -0,0 +1,36 @@ +package PayCheck; + +import java.util.Date; + +public class PayCheck { + private int payPeriodStart; + private int payPeriodEnd; + private double grossPay; + private double deductions; + private double netPay; + public double getGrossPay() { + return grossPay; + } + public void setGrossPay(double grossPay) { + this.grossPay = grossPay; + } + public double getDeductions() { + return deductions; + } + public void setDeductions(double deductions) { + this.deductions = deductions; + } + public double getNetPay() { + return netPay; + } + public void setNetPay(double netPay) { + this.netPay = netPay; + } + + public Date getPayPeriodStartDate() { + return new Date(); + } + public Date getPayPeriodEndDate() { + return new Date(); + } +} diff --git a/students/495232796/OOD/payment/src/PaymentClassification/CommissionClassification.java b/students/495232796/OOD/payment/src/PaymentClassification/CommissionClassification.java new file mode 100644 index 0000000000..e1b9edab23 --- /dev/null +++ b/students/495232796/OOD/payment/src/PaymentClassification/CommissionClassification.java @@ -0,0 +1,23 @@ +package PaymentClassification; + +import java.util.Date; +import java.util.Map; + +import PayCheck.PayCheck; +import DateUtil.DateUtil; + +public class CommissionClassification extends PaymentClassification{ + private double rate = 0.0; + private double salary = 0.0; + private Map receipts; + @Override + public double calculatePay(PayCheck pc) { + double commission = 0.0; + for (SalesReceipt sr : receipts.values()) { + if (DateUtil.between(sr.getDate(), pc.getPayPeriodStartDate(), pc.getPayPeriodEndDate())) { + commission += sr.getAmount()*rate; + } + } + return commission+salary; + } +} diff --git a/students/495232796/OOD/payment/src/PaymentClassification/HourlyClassification.java b/students/495232796/OOD/payment/src/PaymentClassification/HourlyClassification.java new file mode 100644 index 0000000000..00ae430777 --- /dev/null +++ b/students/495232796/OOD/payment/src/PaymentClassification/HourlyClassification.java @@ -0,0 +1,38 @@ +package PaymentClassification; + +import java.util.Date; +import java.util.Map; + +import DateUtil.DateUtil; +import PayCheck.PayCheck; + +public class HourlyClassification extends PaymentClassification{ + private double hourlyRate = 0.0; + private Map timeCards; + + public void addTimeCard(TimeCard tc) { + timeCards.put(tc.getDate(), tc); + } + + @Override + public double calculatePay(PayCheck pc) { + double total = 0.0; + + for (TimeCard tc : timeCards.values()) { + if (DateUtil.between(tc.getDate(), pc.getPayPeriodStartDate(), pc.getPayPeriodEndDate())) { + total += calculatePayForTimeCard(tc); + } + } + + return total; + } + + private double calculatePayForTimeCard(TimeCard tc) { + int hours = tc.getHours(); + if (hours > 8) { + return 8*this.hourlyRate + (hours - 8)*this.hourlyRate*1.5; + } else { + return 8*this.hourlyRate; + } + } +} diff --git a/students/495232796/OOD/payment/src/PaymentClassification/PaymentClassification.java b/students/495232796/OOD/payment/src/PaymentClassification/PaymentClassification.java new file mode 100644 index 0000000000..f9b06d744f --- /dev/null +++ b/students/495232796/OOD/payment/src/PaymentClassification/PaymentClassification.java @@ -0,0 +1,7 @@ +package PaymentClassification; + +import PayCheck.PayCheck; + +public abstract class PaymentClassification { + public abstract double calculatePay(PayCheck pc); +} diff --git a/students/495232796/OOD/payment/src/PaymentClassification/SalariedClassification.java b/students/495232796/OOD/payment/src/PaymentClassification/SalariedClassification.java new file mode 100644 index 0000000000..941bde9869 --- /dev/null +++ b/students/495232796/OOD/payment/src/PaymentClassification/SalariedClassification.java @@ -0,0 +1,12 @@ +package PaymentClassification; + +import PayCheck.PayCheck; + +public class SalariedClassification extends PaymentClassification { + private double salary = 0.0; + + @Override + public double calculatePay(PayCheck pc) { + return salary; + } +} diff --git a/students/495232796/OOD/payment/src/PaymentClassification/SalesReceipt.java b/students/495232796/OOD/payment/src/PaymentClassification/SalesReceipt.java new file mode 100644 index 0000000000..a9f07140bd --- /dev/null +++ b/students/495232796/OOD/payment/src/PaymentClassification/SalesReceipt.java @@ -0,0 +1,20 @@ +package PaymentClassification; + +import java.util.Date; + +public class SalesReceipt { + private Date date; + private double amount; + public Date getDate() { + return date; + } + public void setDate(Date date) { + this.date = date; + } + public double getAmount() { + return amount; + } + public void setAmount(double amount) { + this.amount = amount; + } +} diff --git a/students/495232796/OOD/payment/src/PaymentClassification/TimeCard.java b/students/495232796/OOD/payment/src/PaymentClassification/TimeCard.java new file mode 100644 index 0000000000..e4396ee603 --- /dev/null +++ b/students/495232796/OOD/payment/src/PaymentClassification/TimeCard.java @@ -0,0 +1,21 @@ +package PaymentClassification; + +import java.util.Date; + +public class TimeCard { + private Date date; + private int startTime; + private int endTime; + + public Date getDate() { + return date; + } + public void setDate(Date date) { + this.date = date; + } + + public int getHours() { + return endTime - startTime; + } + +} diff --git a/students/495232796/OOD/payment/src/PaymentMethod/BankMethod.java b/students/495232796/OOD/payment/src/PaymentMethod/BankMethod.java new file mode 100644 index 0000000000..1ef31f13ba --- /dev/null +++ b/students/495232796/OOD/payment/src/PaymentMethod/BankMethod.java @@ -0,0 +1,13 @@ +package PaymentMethod; + +import PayCheck.PayCheck; + +public class BankMethod extends PaymentMethod{ + private String bank; + private double account; + @Override + public void pay(PayCheck pc) { + // TODO Auto-generated method stub + + } +} diff --git a/students/495232796/OOD/payment/src/PaymentMethod/HoldMethod.java b/students/495232796/OOD/payment/src/PaymentMethod/HoldMethod.java new file mode 100644 index 0000000000..62d9b4439c --- /dev/null +++ b/students/495232796/OOD/payment/src/PaymentMethod/HoldMethod.java @@ -0,0 +1,13 @@ +package PaymentMethod; + +import PayCheck.PayCheck; + +public class HoldMethod extends PaymentMethod{ + + @Override + public void pay(PayCheck pc) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/495232796/OOD/payment/src/PaymentMethod/MailMethod.java b/students/495232796/OOD/payment/src/PaymentMethod/MailMethod.java new file mode 100644 index 0000000000..f8a98e5113 --- /dev/null +++ b/students/495232796/OOD/payment/src/PaymentMethod/MailMethod.java @@ -0,0 +1,13 @@ +package PaymentMethod; + +import PayCheck.PayCheck; + +public class MailMethod extends PaymentMethod{ + private String address; + + @Override + public void pay(PayCheck pc) { + // TODO Auto-generated method stub + + } +} diff --git a/students/495232796/OOD/payment/src/PaymentMethod/PaymentMethod.java b/students/495232796/OOD/payment/src/PaymentMethod/PaymentMethod.java new file mode 100644 index 0000000000..67093ae1a0 --- /dev/null +++ b/students/495232796/OOD/payment/src/PaymentMethod/PaymentMethod.java @@ -0,0 +1,7 @@ +package PaymentMethod; + +import PayCheck.PayCheck; + +public abstract class PaymentMethod { + public abstract void pay(PayCheck pc); +} diff --git a/students/495232796/OOD/payment/src/PaymentSchedule/BiWeeklySchedule.java b/students/495232796/OOD/payment/src/PaymentSchedule/BiWeeklySchedule.java new file mode 100644 index 0000000000..ced0eb1d15 --- /dev/null +++ b/students/495232796/OOD/payment/src/PaymentSchedule/BiWeeklySchedule.java @@ -0,0 +1,19 @@ +package PaymentSchedule; + +import java.util.Date; +import DateUtil.DateUtil; + +public class BiWeeklySchedule implements PaymentSchedule{ + Date firstFriday = DateUtil.parseDay("2017-01-01"); + @Override + public boolean isPayDay(Date date) { + long interval = DateUtil.getDaysBetween(firstFriday, date); + return interval%14 == 0; + } + + @Override + public Date getPayPeriodStartDate(Date date) { + return DateUtil.add(date, -13); + } + +} diff --git a/students/495232796/OOD/payment/src/PaymentSchedule/MothlySchedule.java b/students/495232796/OOD/payment/src/PaymentSchedule/MothlySchedule.java new file mode 100644 index 0000000000..edac34d480 --- /dev/null +++ b/students/495232796/OOD/payment/src/PaymentSchedule/MothlySchedule.java @@ -0,0 +1,19 @@ +package PaymentSchedule; + +import java.util.Date; + +import DateUtil.DateUtil; + +public class MothlySchedule implements PaymentSchedule{ + + @Override + public boolean isPayDay(Date date) { + return DateUtil.isLastDayofMonth(date); + } + + @Override + public Date getPayPeriodStartDate(Date date) { + return DateUtil.getFirstDay(date); + } + +} diff --git a/students/495232796/OOD/payment/src/PaymentSchedule/PaymentSchedule.java b/students/495232796/OOD/payment/src/PaymentSchedule/PaymentSchedule.java new file mode 100644 index 0000000000..e1dea539f8 --- /dev/null +++ b/students/495232796/OOD/payment/src/PaymentSchedule/PaymentSchedule.java @@ -0,0 +1,10 @@ +package PaymentSchedule; + +import java.util.Date; + +public interface PaymentSchedule { + + public boolean isPayDay(Date date); + + public Date getPayPeriodStartDate(Date date); +} diff --git a/students/495232796/OOD/payment/src/PaymentSchedule/WeeklySchedule.java b/students/495232796/OOD/payment/src/PaymentSchedule/WeeklySchedule.java new file mode 100644 index 0000000000..9e8e4dfe9f --- /dev/null +++ b/students/495232796/OOD/payment/src/PaymentSchedule/WeeklySchedule.java @@ -0,0 +1,18 @@ +package PaymentSchedule; + +import java.util.Date; +import DateUtil.DateUtil; + +public class WeeklySchedule implements PaymentSchedule{ + + @Override + public boolean isPayDay(Date date) { + return DateUtil.isFriday(date); + } + + @Override + public Date getPayPeriodStartDate(Date date) { + return DateUtil.add(date, -6); + } + +} diff --git a/students/495232796/OOD/responsibilitychainpattern/pom.xml b/students/495232796/OOD/responsibilitychainpattern/pom.xml new file mode 100644 index 0000000000..84bf4627e3 --- /dev/null +++ b/students/495232796/OOD/responsibilitychainpattern/pom.xml @@ -0,0 +1,42 @@ + + 4.0.0 + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.7 + 1.7 + + + + + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + \ No newline at end of file diff --git a/students/495232796/OOD/responsibilitychainpattern/src/main/java/com/coderising/dp/ResponsibilityChain/EmailLogger.java b/students/495232796/OOD/responsibilitychainpattern/src/main/java/com/coderising/dp/ResponsibilityChain/EmailLogger.java new file mode 100644 index 0000000000..bc3d446019 --- /dev/null +++ b/students/495232796/OOD/responsibilitychainpattern/src/main/java/com/coderising/dp/ResponsibilityChain/EmailLogger.java @@ -0,0 +1,25 @@ +package com.coderising.dp.ResponsibilityChain; + +public class EmailLogger implements Logger{ + private int level = Logger.DEBUG; + private Logger next; + + public EmailLogger(int level) { + this.level = level; + } + @Override + public void message(String context, int level) { + if (level >= this.level) { + System.out.println(this.getClass().getName()+ " " + context); + } + if (this.next != null) { + this.next.message(context, level); + } + } + + @Override + public void setNext(Logger next) { + this.next = next; + } + +} diff --git a/students/495232796/OOD/responsibilitychainpattern/src/main/java/com/coderising/dp/ResponsibilityChain/FileLogger.java b/students/495232796/OOD/responsibilitychainpattern/src/main/java/com/coderising/dp/ResponsibilityChain/FileLogger.java new file mode 100644 index 0000000000..e549d9b626 --- /dev/null +++ b/students/495232796/OOD/responsibilitychainpattern/src/main/java/com/coderising/dp/ResponsibilityChain/FileLogger.java @@ -0,0 +1,24 @@ +package com.coderising.dp.ResponsibilityChain; + +public class FileLogger implements Logger{ + private int level = Logger.DEBUG; + private Logger next; + + public FileLogger(int level) { + this.level = level; + } + @Override + public void message(String context, int level) { + if (level >= this.level) { + System.out.println(this.getClass().getName()+ " " + context); + } + if (this.next != null) { + this.next.message(context, level); + } + } + + @Override + public void setNext(Logger next) { + this.next = next; + } +} diff --git a/students/495232796/OOD/responsibilitychainpattern/src/main/java/com/coderising/dp/ResponsibilityChain/Logger.java b/students/495232796/OOD/responsibilitychainpattern/src/main/java/com/coderising/dp/ResponsibilityChain/Logger.java new file mode 100644 index 0000000000..3edbc68e0f --- /dev/null +++ b/students/495232796/OOD/responsibilitychainpattern/src/main/java/com/coderising/dp/ResponsibilityChain/Logger.java @@ -0,0 +1,10 @@ +package com.coderising.dp.ResponsibilityChain; + +public interface Logger { + public static final int DEBUG = 0; + public static final int NOTICE = 1; + public static final int ERR = 2; + + public void message(String context, int level); + public void setNext(Logger next); +} diff --git a/students/495232796/OOD/responsibilitychainpattern/src/main/java/com/coderising/dp/ResponsibilityChain/StdoutLogger.java b/students/495232796/OOD/responsibilitychainpattern/src/main/java/com/coderising/dp/ResponsibilityChain/StdoutLogger.java new file mode 100644 index 0000000000..fcc49437f6 --- /dev/null +++ b/students/495232796/OOD/responsibilitychainpattern/src/main/java/com/coderising/dp/ResponsibilityChain/StdoutLogger.java @@ -0,0 +1,26 @@ +package com.coderising.dp.ResponsibilityChain; + +public class StdoutLogger implements Logger { + private int level = Logger.DEBUG; + private Logger next; + + public StdoutLogger(int level) { + this.level = level; + } + + @Override + public void message(String context, int level) { + if (level >= this.level) { + System.out.println(this.getClass().getName()+ " " + context); + } + if (this.next != null) { + this.next.message(context, level); + } + } + + @Override + public void setNext(Logger next) { + this.next = next; + } + +} diff --git a/students/501917623/src/work/Test/Test.java b/students/501917623/src/work/Test/Test.java new file mode 100644 index 0000000000..3da24e1f28 --- /dev/null +++ b/students/501917623/src/work/Test/Test.java @@ -0,0 +1,10 @@ +package work.Test; + +public class Test { + + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println("hello world"); + } + +} diff --git a/students/505217361/src/main/java/com/coderising/ood/srp/Configuration.java b/students/505217361/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..efd3c58820 --- /dev/null +++ b/students/505217361/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,26 @@ +package main.java.com.coderising.ood.srp; + + +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} + \ No newline at end of file diff --git a/students/505217361/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/505217361/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..b927dbac2f --- /dev/null +++ b/students/505217361/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,10 @@ +package main.java.com.coderising.ood.srp; + + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/505217361/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/505217361/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..3f7760a6e7 --- /dev/null +++ b/students/505217361/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,28 @@ +package main.java.com.coderising.ood.srp; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + + } + + return userList; + } +} diff --git a/students/505217361/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/505217361/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..f422fd9088 --- /dev/null +++ b/students/505217361/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,19 @@ +package main.java.com.coderising.ood.srp; + + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/505217361/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/505217361/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..6796f35858 --- /dev/null +++ b/students/505217361/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,202 @@ +package main.java.com.coderising.ood.srp; + + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery = null; + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected String productID = null; + protected String productDesc = null; + + private static Configuration config; + + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + File f = new File("E:/product_promotion.txt"); + + + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + + + config = new Configuration(); + + setSMTPHost(); + setAltSMTPHost(); + setFromAddress(); + setLoadQuery(); + + sendEMails(mailDebug, loadMailingList()); + + + } + + + + + protected void setProductID(String productID) + { + this.productID = productID; + + } + + protected String getproductID() + { + return productID; + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected void setSMTPHost() + { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() + { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + protected void setFromAddress() + { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setMessage(HashMap userInfo) throws IOException + { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + + + + } + + + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + System.out.println("进入"); + br = new BufferedReader(new FileReader(file)); + System.out.println("br"); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + private void setProductDesc(String desc) { + this.productDesc = desc; + } + + + protected void configureEMail(HashMap userInfo) throws IOException + { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try + { + + if (toAddress.length() > 0) + // 首选服务器 + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } + catch (Exception e) + { + + try { + // 备选服务器 + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } + + else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/505217361/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/505217361/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/505217361/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/505217361/src/test/java/org/coderising/liteaop/Configuration.java b/students/505217361/src/test/java/org/coderising/liteaop/Configuration.java new file mode 100644 index 0000000000..06dde10147 --- /dev/null +++ b/students/505217361/src/test/java/org/coderising/liteaop/Configuration.java @@ -0,0 +1,55 @@ +package test.java.org.coderising.liteaop; + + +import java.util.HashMap; +import java.util.Map; + + +public class Configuration { + + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + static Map configurations = new HashMap(); + + + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + + protected String setSMTPHost() + { + smtpHost = getProperty(ConfigurationKeys.SMTP_SERVER); + return smtpHost; + } + + + protected String setAltSMTPHost() + { + altSmtpHost = getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + return altSmtpHost; + } + + + protected String setFromAddress() + { + fromAddress = getProperty(ConfigurationKeys.EMAIL_ADMIN); + return fromAddress; + } + + + +} + \ No newline at end of file diff --git a/students/505217361/src/test/java/org/coderising/liteaop/ConfigurationKeys.java b/students/505217361/src/test/java/org/coderising/liteaop/ConfigurationKeys.java new file mode 100644 index 0000000000..8471dcf4a0 --- /dev/null +++ b/students/505217361/src/test/java/org/coderising/liteaop/ConfigurationKeys.java @@ -0,0 +1,12 @@ +package test.java.org.coderising.liteaop; + + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + + + +} diff --git a/students/505217361/src/test/java/org/coderising/liteaop/DBUtil.java b/students/505217361/src/test/java/org/coderising/liteaop/DBUtil.java new file mode 100644 index 0000000000..23ec85320d --- /dev/null +++ b/students/505217361/src/test/java/org/coderising/liteaop/DBUtil.java @@ -0,0 +1,29 @@ +package test.java.org.coderising.liteaop; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + /* + * 数据库交互类 + * */ + + // 假设这个是获取人员的数据库交互 + public List executeQuery(String sql){ + System.out.println("execute sql "); + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + + User user = new User(); + user.setUsername("User"+i); + user.setEmailadd("aa@bb.com"); + userList.add(user); + + } + + return userList; + + } + +} diff --git a/students/505217361/src/test/java/org/coderising/liteaop/EmailUtil.java b/students/505217361/src/test/java/org/coderising/liteaop/EmailUtil.java new file mode 100644 index 0000000000..0e1d84fa64 --- /dev/null +++ b/students/505217361/src/test/java/org/coderising/liteaop/EmailUtil.java @@ -0,0 +1,96 @@ +package test.java.org.coderising.liteaop; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + + + +public class EmailUtil { + + private static final String EMAIL_KEY = "EMAIL"; + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String subject = null; + protected String message = null; + + + + public void sendEmail(List users,Production product){ + boolean debugs = false; + // 获取配置信息 + Configuration config = new Configuration(); + smtpHost = config.setSMTPHost(); + altSmtpHost = config.setAltSMTPHost(); + fromAddress = config.setFromAddress(); + System.out.println("开始发送邮件"); + if(users != null){ + Iterator iter = users.iterator(); + while(iter.hasNext()){ + User user = (User) iter.next(); + String userEmail = user.getEmailadd(); + String userName = user.getUsername(); + + // 获取输入值 + setMessage(userName,product); + + try{ + if(userEmail.length()>0){ + Mail mail = new Mail(); + mail.setFromAddress(fromAddress); + mail.setUserEmail(userEmail); + mail.setSmtpHost(altSmtpHost); + mail.setSubject(subject); + mail.setMessage(message); + + mail.sendEmail(debugs); + + } + }catch(Exception e ){ + try{ + + Mail mail = new Mail(); + mail.setFromAddress(fromAddress); + mail.setUserEmail(userEmail); + mail.setSmtpHost(altSmtpHost); + mail.setSubject(subject); + mail.setMessage(message); + + System.out.println("使用备用服务器地址发送邮件!"); + mail.sendEmail(debugs); + + + }catch(Exception e2){ + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + + + } + }else { + System.out.println("没有邮件发送"); + + } + + + } + + + + protected void setMessage(String username,Production product) + { + + String name = username; + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!" ; + + } + + + + + + +} diff --git a/students/505217361/src/test/java/org/coderising/liteaop/Mail.java b/students/505217361/src/test/java/org/coderising/liteaop/Mail.java new file mode 100644 index 0000000000..ddb5fa8bc1 --- /dev/null +++ b/students/505217361/src/test/java/org/coderising/liteaop/Mail.java @@ -0,0 +1,80 @@ +package test.java.org.coderising.liteaop; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; + + + +public class Mail { + String fromAddress; + String userEmail; + String smtpHost; + String subject; + String message; + + + public String getFromAddress() { + return fromAddress; + } + + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + + public String getUserEmail() { + return userEmail; + } + + + public void setUserEmail(String userEmail) { + this.userEmail = userEmail; + } + + + public String getSmtpHost() { + return smtpHost; + } + + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + + + public String getSubject() { + return subject; + } + + + public void setSubject(String subject) { + this.subject = subject; + } + + + public String getMessage() { + return message; + } + + + public void setMessage(String message) { + this.message = message; + } + + + public void sendEmail(boolean debug) { + + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(userEmail).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/505217361/src/test/java/org/coderising/liteaop/ProductUtil.java b/students/505217361/src/test/java/org/coderising/liteaop/ProductUtil.java new file mode 100644 index 0000000000..40434158f4 --- /dev/null +++ b/students/505217361/src/test/java/org/coderising/liteaop/ProductUtil.java @@ -0,0 +1,33 @@ +package test.java.org.coderising.liteaop; + +import java.io.File; + +public class ProductUtil { + /* + 获取促销产品 + */ + + // 存放产品信息文本 + + Production product ; + + public Production getPromotionalProduct(){ + + // filepath 产品信息路径 + String filepath = "E:/product_promotion.txt"; + + try{ + fileUtil fu = new fileUtil(); + + product = fu.readFile(filepath); + + }catch(Exception e){ + + e.printStackTrace(); + } + + return product; + + } + +} diff --git a/students/505217361/src/test/java/org/coderising/liteaop/Production.java b/students/505217361/src/test/java/org/coderising/liteaop/Production.java new file mode 100644 index 0000000000..c148a98fab --- /dev/null +++ b/students/505217361/src/test/java/org/coderising/liteaop/Production.java @@ -0,0 +1,20 @@ +package test.java.org.coderising.liteaop; + +public class Production { + String productID; + String ProductDesc; + public String getProductID() { + return productID; + } + public void setProductID(String productID) { + this.productID = productID; + } + public String getProductDesc() { + return ProductDesc; + } + public void setProductDesc(String productDesc) { + ProductDesc = productDesc; + } + + +} diff --git a/students/505217361/src/test/java/org/coderising/liteaop/User.java b/students/505217361/src/test/java/org/coderising/liteaop/User.java new file mode 100644 index 0000000000..683733054b --- /dev/null +++ b/students/505217361/src/test/java/org/coderising/liteaop/User.java @@ -0,0 +1,21 @@ +package test.java.org.coderising.liteaop; + +public class User { + public String username ; + public String emailadd; + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + public String getEmailadd() { + return emailadd; + } + public void setEmailadd(String emailadd) { + this.emailadd = emailadd; + } + + + +} diff --git a/students/505217361/src/test/java/org/coderising/liteaop/UserUtil.java b/students/505217361/src/test/java/org/coderising/liteaop/UserUtil.java new file mode 100644 index 0000000000..66e4f63e29 --- /dev/null +++ b/students/505217361/src/test/java/org/coderising/liteaop/UserUtil.java @@ -0,0 +1,24 @@ +package test.java.org.coderising.liteaop; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class UserUtil { + + // 获取有关注相关产品信息的用户 + public List getSubscriptionUser(String productID){ + String sql = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + DBUtil dbu = new DBUtil(); + List users = dbu.executeQuery(sql); + + System.out.println("loadQuery set"); + return users; + + } + + +} diff --git a/students/505217361/src/test/java/org/coderising/liteaop/fileUtil.java b/students/505217361/src/test/java/org/coderising/liteaop/fileUtil.java new file mode 100644 index 0000000000..2bc83a0213 --- /dev/null +++ b/students/505217361/src/test/java/org/coderising/liteaop/fileUtil.java @@ -0,0 +1,39 @@ +package test.java.org.coderising.liteaop; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +public class fileUtil { + + Production product; + + public Production readFile (String filepath) throws IOException // @02C + { + File file_product = new File("E:/product_promotion.txt"); + + BufferedReader br = null; + try { + + br = new BufferedReader(new FileReader(file_product)); + + String temp = br.readLine(); + String[] data = temp.split(" "); + product = new Production(); + product.setProductID(data[0]); + product.setProductDesc(data[1]); + + System.out.println("产品ID = " + data[0] + "\n"); + System.out.println("产品描述 = " + data[1] + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + + return product; + + } +} diff --git a/students/505217361/src/test/java/org/coderising/liteaop/promotionMail.java b/students/505217361/src/test/java/org/coderising/liteaop/promotionMail.java new file mode 100644 index 0000000000..87e1438634 --- /dev/null +++ b/students/505217361/src/test/java/org/coderising/liteaop/promotionMail.java @@ -0,0 +1,26 @@ +package test.java.org.coderising.liteaop; + +import java.util.List; + +public class promotionMail { + + public static void main(String[] args) { + // 促销邮件 + + // 促销产品 + ProductUtil pp = new ProductUtil(); + Production product = pp.getPromotionalProduct(); + + // 获得订阅人员 + UserUtil uu = new UserUtil(); + List userlist = uu.getSubscriptionUser(product.getProductID()); + + // 发送邮件 + EmailUtil eu = new EmailUtil(); + eu.sendEmail(userlist,product); + + } + + + +} diff --git a/students/506359831/src/com/coderising/ood/srp/Configuration.java b/students/506359831/src/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/506359831/src/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/506359831/src/com/coderising/ood/srp/ConfigurationKeys.java b/students/506359831/src/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/506359831/src/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/506359831/src/com/coderising/ood/srp/DBUtil.java b/students/506359831/src/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/506359831/src/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/506359831/src/com/coderising/ood/srp/MailUtil.java b/students/506359831/src/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..9f9e749af7 --- /dev/null +++ b/students/506359831/src/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/506359831/src/com/coderising/ood/srp/PromotionMail.java b/students/506359831/src/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..781587a846 --- /dev/null +++ b/students/506359831/src/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,199 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery = null; + + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected String productID = null; + protected String productDesc = null; + + private static Configuration config; + + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + + + config = new Configuration(); + + setSMTPHost(); + setAltSMTPHost(); + + + setFromAddress(); + + + setLoadQuery(); + + sendEMails(mailDebug, loadMailingList()); + + + } + + + + + protected void setProductID(String productID) + { + this.productID = productID; + + } + + protected String getproductID() + { + return productID; + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected void setSMTPHost() + { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() + { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + protected void setFromAddress() + { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setMessage(HashMap userInfo) throws IOException + { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + + + + } + + + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + private void setProductDesc(String desc) { + this.productDesc = desc; + } + + + protected void configureEMail(HashMap userInfo) throws IOException + { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try + { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } + + else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/506359831/src/com/coderising/ood/srp/product_promotion.txt b/students/506359831/src/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/506359831/src/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/511134962/ood-assignment/pom.xml b/students/511134962/ood-assignment/pom.xml new file mode 100644 index 0000000000..542d8e08ef --- /dev/null +++ b/students/511134962/ood-assignment/pom.xml @@ -0,0 +1,40 @@ + + + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..aae91db287 --- /dev/null +++ b/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,147 @@ +/********************************************************************************************************************** + * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit. * + * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. * + * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. * + * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. * + * Vestibulum commodo. Ut rhoncus gravida arcu. * + **********************************************************************************************************************/ + +package com.coderising.ood.srp; + +import com.coderising.ood.srp.common.Configuration; +import com.coderising.ood.srp.common.ConfigurationKeys; +import com.coderising.ood.srp.dao.ProductPromotionDAO; +import com.coderising.ood.srp.util.FileUtil; +import com.coderising.ood.srp.util.MailUtil; +import com.coderising.ood.srp.vo.ProductInfo; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail +{ + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + private ProductPromotionDAO productPromotionDAO = new ProductPromotionDAO(); + private Configuration config = new Configuration(); + private ProductInfo productInfo = new ProductInfo(); + private FileUtil fileUtil = new FileUtil(); + private boolean emailDebug = false; + private String smtpHost = null; + private String altSmtpHost = null; + private String fromAddress = null; + private String toAddress = null; + private String subject = null; + private String message = null; + private List< HashMap > mailingList = null; + + + public PromotionMail( File file, boolean mailDebug ) throws Exception + { + this.emailDebug = mailDebug; + readProductInfos( file ); + configuringEMAILSetting(); + mailingList = queryMailingList(); + } + + private void readProductInfos( File file ) throws IOException + {//读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + String[] productInfos = fileUtil.readFile( file ); + productInfo.setProductID( productInfos[ 0 ] ); + productInfo.setProductDesc( productInfos[ 1 ] ); + System.out.println( "产品ID = " + productInfo.getProductID() + "\n" ); + System.out.println( "产品描述 = " + productInfo.getProductDesc() + "\n" ); + } + + private void configuringEMAILSetting() + { + setSMTPHost(); + setAltSMTPHost(); + setFromAddress(); + } + + private List< HashMap > queryMailingList() throws Exception + { + productPromotionDAO.setLoadQuery( productInfo.getProductID() ); + return productPromotionDAO.loadMailingList(); + } + + protected void setSMTPHost() + { + smtpHost = config.getProperty( ConfigurationKeys.SMTP_SERVER ); + } + + protected void setAltSMTPHost() + { + altSmtpHost = config.getProperty( ConfigurationKeys.ALT_SMTP_SERVER ); + } + + protected void setFromAddress() + { + fromAddress = config.getProperty( ConfigurationKeys.EMAIL_ADMIN ); + } + + public static void main( String[] args ) throws Exception + { + File productPromotionFile = new File( "D:\\02_workspace\\myproject\\coding2017\\students\\511134962\\ood-assignment\\src\\main\\resources\\product_promotion.txt" ); + boolean emailDebug = false; + PromotionMail pe = new PromotionMail( productPromotionFile, emailDebug ); + pe.sendEMails(); + } + + protected void sendEMails() throws IOException + { + System.out.println( "开始发送邮件" ); + if ( mailingList != null ) + { + Iterator iter = mailingList.iterator(); + while ( iter.hasNext() ) + { + configureEMail( ( HashMap ) iter.next() ); + try + { + if ( toAddress.length() > 0 ) + { + MailUtil.sendEmail( toAddress, fromAddress, subject, message, smtpHost, emailDebug ); + } + } + catch ( Exception e ) + { + try + { + MailUtil.sendEmail( toAddress, fromAddress, subject, message, altSmtpHost, emailDebug ); + } + catch ( Exception e2 ) + { + System.out.println( "通过备用 SMTP服务器发送邮件失败: " + e2.getMessage() ); + } + } + } + } + else + { + System.out.println( "没有邮件发送" ); + } + + } + + protected void configureEMail( HashMap userInfo ) throws IOException + { + toAddress = ( String ) userInfo.get( EMAIL_KEY ); + if ( toAddress.length() > 0 ) + { + setMessage( userInfo ); + } + } + + protected void setMessage( HashMap userInfo ) throws IOException + { + String name = ( String ) userInfo.get( NAME_KEY ); + subject = "您关注的产品降价了"; + message = "尊敬的 " + name + ", 您关注的产品 " + productInfo.getProductDesc() + " 降价了,欢迎购买!"; + } + +} diff --git a/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/common/Configuration.java b/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/common/Configuration.java new file mode 100644 index 0000000000..331f204e58 --- /dev/null +++ b/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/common/Configuration.java @@ -0,0 +1,36 @@ +/********************************************************************************************************************** + * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit. * + * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. * + * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. * + * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. * + * Vestibulum commodo. Ut rhoncus gravida arcu. * + **********************************************************************************************************************/ + +package com.coderising.ood.srp.common; + +import java.util.HashMap; +import java.util.Map; + +public class Configuration +{ + static Map< String, String > configurations = new HashMap<>(); + static + { + configurations.put( ConfigurationKeys.SMTP_SERVER, "smtp.163.com" ); + configurations.put( ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com" ); + configurations.put( ConfigurationKeys.EMAIL_ADMIN, "admin@company.com" ); + } + + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * + * @param key + * + * @return + */ + public String getProperty( String key ) + { + return configurations.get( key ); + } + +} diff --git a/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/common/ConfigurationKeys.java b/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/common/ConfigurationKeys.java new file mode 100644 index 0000000000..fa6b1ec04a --- /dev/null +++ b/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/common/ConfigurationKeys.java @@ -0,0 +1,15 @@ +/********************************************************************************************************************** + * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit. * + * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. * + * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. * + * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. * + * Vestibulum commodo. Ut rhoncus gravida arcu. * + **********************************************************************************************************************/ + +package com.coderising.ood.srp.common; + +public class ConfigurationKeys { + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; +} diff --git a/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/dao/ProductPromotionDAO.java b/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/dao/ProductPromotionDAO.java new file mode 100644 index 0000000000..62b8c05710 --- /dev/null +++ b/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/dao/ProductPromotionDAO.java @@ -0,0 +1,33 @@ +/********************************************************************************************************************** + * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit. * + * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. * + * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. * + * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. * + * Vestibulum commodo. Ut rhoncus gravida arcu. * + **********************************************************************************************************************/ + +package com.coderising.ood.srp.dao; + +import com.coderising.ood.srp.util.DBUtil; + +import java.util.HashMap; +import java.util.List; + +public class ProductPromotionDAO +{ + private String sendMailQuery = null; + + public ProductPromotionDAO() { } + + public void setLoadQuery( String productID ) throws Exception + { + sendMailQuery + = "Select name from subscriptions " + "where product_id= '" + productID + "' " + "and send_mail=1 "; + System.out.println( "loadQuery set" ); + } + + public List loadMailingList() throws Exception + { + return DBUtil.query( this.sendMailQuery ); + } +} \ No newline at end of file diff --git a/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/util/DBUtil.java b/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/util/DBUtil.java new file mode 100644 index 0000000000..832ba0408a --- /dev/null +++ b/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/util/DBUtil.java @@ -0,0 +1,37 @@ +/********************************************************************************************************************** + * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit. * + * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. * + * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. * + * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. * + * Vestibulum commodo. Ut rhoncus gravida arcu. * + **********************************************************************************************************************/ + +package com.coderising.ood.srp.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil +{ + + /** + * 应该从数据库读, 但是简化为直接生成。 + * + * @param sql + * + * @return + */ + public static List< HashMap > query( String sql ) + { + List< HashMap > userList = new ArrayList(); + for ( int i = 1; i <= 3; i++ ) + { + HashMap< String, String > userInfo = new HashMap(); + userInfo.put( "NAME", "User" + i ); + userInfo.put( "EMAIL", "aa@bb.com" ); + userList.add( userInfo ); + } + return userList; + } +} diff --git a/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/util/FileUtil.java b/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/util/FileUtil.java new file mode 100644 index 0000000000..963eb72001 --- /dev/null +++ b/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/util/FileUtil.java @@ -0,0 +1,43 @@ +/********************************************************************************************************************** + * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit. * + * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. * + * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. * + * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. * + * Vestibulum commodo. Ut rhoncus gravida arcu. * + **********************************************************************************************************************/ + +package com.coderising.ood.srp.util; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +public class FileUtil +{ + public FileUtil() { } + + public String[] readFile( File file ) throws IOException // @02C + { + BufferedReader br = null; + try + { + br = new BufferedReader( new FileReader( file ) ); + String temp = br.readLine(); + String[] data = temp.split( " " ); + br.close(); + return data; + } + catch ( IOException e ) + { + throw new IOException( e.getMessage() ); + } + finally + { + if ( null != br ) + { + br.close(); + } + } + } +} \ No newline at end of file diff --git a/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java b/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java new file mode 100644 index 0000000000..cac1a23f8d --- /dev/null +++ b/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java @@ -0,0 +1,23 @@ +/********************************************************************************************************************** + * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit. * + * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. * + * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. * + * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. * + * Vestibulum commodo. Ut rhoncus gravida arcu. * + **********************************************************************************************************************/ + +package com.coderising.ood.srp.util; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + } +} diff --git a/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/vo/ProductInfo.java b/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/vo/ProductInfo.java new file mode 100644 index 0000000000..3bd52e942d --- /dev/null +++ b/students/511134962/ood-assignment/src/main/java/com/coderising/ood/srp/vo/ProductInfo.java @@ -0,0 +1,72 @@ +/********************************************************************************************************************** + * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit. * + * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. * + * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. * + * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. * + * Vestibulum commodo. Ut rhoncus gravida arcu. * + **********************************************************************************************************************/ + +package com.coderising.ood.srp.vo; + +import java.util.Objects; + +public class ProductInfo +{ + private String productID = null; + private String productDesc = null; + + public ProductInfo() { } + + @Override + public int hashCode() + { + return Objects.hash( getProductID(), getProductDesc() ); + } + + @Override + public boolean equals( Object o ) + { + if ( this == o ) + { + return true; + } + if ( !( o instanceof ProductInfo ) ) + { + return false; + } + ProductInfo that = ( ProductInfo ) o; + return Objects.equals( getProductID(), that.getProductID() ) && Objects.equals( getProductDesc(), + that.getProductDesc() ); + } + + public String getProductID() + { + return productID; + } + + public String getProductDesc() + { + + return productDesc; + } + + public void setProductDesc( String productDesc ) + { + this.productDesc = productDesc; + } + + public void setProductID( String productID ) + { + this.productID = productID; + } + + @Override + public String toString() + { + final StringBuilder sb = new StringBuilder( "ProductInfo{" ); + sb.append( " productDesc='" ).append( productDesc ).append( '\'' ); + sb.append( ", productID='" ).append( productID ).append( '\'' ); + sb.append( '}' ); + return sb.toString(); + } +} \ No newline at end of file diff --git a/students/511134962/ood-assignment/src/main/resources/product_promotion.txt b/students/511134962/ood-assignment/src/main/resources/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/511134962/ood-assignment/src/main/resources/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/511739113/6.11/ood-assignment/pom.xml b/students/511739113/6.11/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/511739113/6.11/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..bf42021028 --- /dev/null +++ b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,46 @@ +package com.coderising.ood.srp; + +import java.io.File; + +import com.coderising.ood.srp.bean.Product; +import com.coderising.ood.srp.service.MessageService; +import com.coderising.ood.srp.service.UserService; +import com.coderising.ood.srp.util.FileUtil; + +/** + * 模拟 商品促销通知系统 + *

标题:

+ *

描述:

+ * @autho zx + * @time 2017年6月12日 下午11:43:57 +*/ +public class PromotionMail { + + /** 模拟注入userService */ + private UserService userService = new UserService(); + + /** 模拟注入messageService */ + private MessageService messageService = new MessageService(); + + public static void main(String[] args) throws Exception { + File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + boolean emailDebug = false; + new PromotionMail(f, emailDebug); + } + + /** + * 商品促销通知系统 + *

标题:

+ *

描述:

+ * @param file + * @param mailDebug + * @throws Exception + */ + public PromotionMail(File file, boolean mailDebug) throws Exception { + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + Product product = FileUtil.readFile(file); + messageService.sendEMails(mailDebug, userService.queryUserInfo(product.getProductId()),product); + } + + +} diff --git a/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/bean/Message.java b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/bean/Message.java new file mode 100644 index 0000000000..01cd33b04c --- /dev/null +++ b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/bean/Message.java @@ -0,0 +1,37 @@ +package com.coderising.ood.srp.bean; + +/** + * 推送的消息 实体 + *

标题:

+ *

描述:

+ * @autho zx + * @time 2017年6月13日 上午2:01:17 +*/ +public class Message extends ServerBean{ + + /** */ + private static final long serialVersionUID = 3850050693864793038L; + + /** 标题 */ + private String subject; + + /** 消息 */ + private String message; + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + +} diff --git a/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/bean/Product.java b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/bean/Product.java new file mode 100644 index 0000000000..ed841c4f72 --- /dev/null +++ b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/bean/Product.java @@ -0,0 +1,40 @@ +package com.coderising.ood.srp.bean; + +import java.io.Serializable; + +/** + * 商品类 + *

标题:

+ *

描述:

+ * @autho zx + * @time 2017年6月13日 上午12:29:56 +*/ +public class Product implements Serializable{ + + /** */ + private static final long serialVersionUID = 2966621699675433678L; + + /** 商品Id */ + private String productId; + + /** 商品描述 */ + private String productDesc; + + public String getProductId() { + return productId; + } + + public void setProductId(String productId) { + this.productId = productId; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + + +} diff --git a/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/bean/ServerBean.java b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/bean/ServerBean.java new file mode 100644 index 0000000000..948f501f01 --- /dev/null +++ b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/bean/ServerBean.java @@ -0,0 +1,61 @@ +package com.coderising.ood.srp.bean; + +import java.io.Serializable; + +/** + * 服务配置 + *

标题:

+ *

描述:

+ * @autho zx + * @time 2017年6月13日 上午1:22:38 +*/ +public class ServerBean implements Serializable{ + + /** */ + private static final long serialVersionUID = -1842399098772577584L; + + /** 服务器地址 */ + private String smtpHost; + + /** 备用服务器地址 */ + private String altSmtpHost; + + /** 发送地址 */ + private String fromAddress; + + /** 接受地址 */ + private String toAddress; + + public String getSmtpHost() { + return smtpHost; + } + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + +} diff --git a/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/config/Configuration.java b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/config/Configuration.java new file mode 100644 index 0000000000..45cbf41c11 --- /dev/null +++ b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/config/Configuration.java @@ -0,0 +1,31 @@ +package com.coderising.ood.srp.config; +import java.util.HashMap; +import java.util.Map; + +/** + * 配置类,模拟从配置文件中读取参数 + *

标题:

+ *

描述:

+ * @autho zx + * @time 2017年6月12日 下午11:44:36 +*/ +public class Configuration { + + private static Map configurations = new HashMap(); + + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + return configurations.get(key); + } + +} diff --git a/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/config/ConfigurationKeys.java b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/config/ConfigurationKeys.java new file mode 100644 index 0000000000..0e8c889f2e --- /dev/null +++ b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/config/ConfigurationKeys.java @@ -0,0 +1,21 @@ +package com.coderising.ood.srp.config; + +/** + * 常量类 存放配置文件key + *

标题:

+ *

描述:

+ * @autho zx + * @time 2017年6月12日 下午11:45:43 +*/ +public class ConfigurationKeys { + + /** 服务器地址 */ + public static final String SMTP_SERVER = "smtp.server"; + + /** 备用服务器地址 */ + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + + /** email地址 */ + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/jdbc/UserJDBC.java b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/jdbc/UserJDBC.java new file mode 100644 index 0000000000..b0382b21a8 --- /dev/null +++ b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/jdbc/UserJDBC.java @@ -0,0 +1,29 @@ +package com.coderising.ood.srp.jdbc; + +import java.util.List; + +import com.coderising.ood.srp.util.DBUtil; + +/** + * 用户 jdbc + *

标题:

+ *

描述:

+ * @autho zx + * @time 2017年6月13日 上午12:51:00 +*/ +public class UserJDBC { + + /** + * 根据商品Id 获取用户信息 + *

方法名称:

+ *

方法说明:

+ * @param productId + * @return + * @autho zx + * @time 2017年6月13日 上午12:51:14 + */ + public List selectUserId(String sql){ + return DBUtil.query(sql); + } + +} diff --git a/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/service/MessageService.java b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/service/MessageService.java new file mode 100644 index 0000000000..61202c0a6f --- /dev/null +++ b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/service/MessageService.java @@ -0,0 +1,83 @@ +package com.coderising.ood.srp.service; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import com.coderising.ood.srp.bean.Message; +import com.coderising.ood.srp.bean.Product; +import com.coderising.ood.srp.config.Configuration; +import com.coderising.ood.srp.config.ConfigurationKeys; +import com.coderising.ood.srp.util.MailUtil; + +/** + * 推送消息 + *

标题:

+ *

描述:

+ * @autho zx + * @time 2017年6月13日 上午1:10:27 +*/ +public class MessageService { + + private static final String EMAIL_KEY = "EMAIL"; + + private static final String NAME_KEY = "NAME"; + + private Configuration configuration = new Configuration(); + + /** + * 推送消息 + *

方法名称:

+ *

方法说明:

+ * @param debug + * @param mailingList + * @param product + * @throws IOException + * @autho zx + * @time 2017年6月13日 上午1:59:31 + */ + public void sendEMails(boolean debug, List mailingList,Product product) throws IOException{ + System.out.println("开始发送邮件"); + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + Message message = configureEMail((HashMap) iter.next(),product.getProductDesc()); + try { + if (message!=null) + MailUtil.sendEmail(message, debug); + }catch (Exception e){ + try { + MailUtil.sendEmail(message, debug); + } catch (Exception e2){ + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + }else { + System.out.println("没有邮件发送"); + } + } + + private Message configureEMail(HashMap userInfo,String productDesc) throws IOException{ + String toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + return getMessage(userInfo,productDesc,toAddress); + return null; + } + + private Message getMessage(HashMap userInfo,String productDesc,String toAddress) throws IOException{ + String name = (String) userInfo.get(NAME_KEY); + Message messageBean = new Message(); + String subject = "您关注的产品降价了"; + String message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + messageBean.setMessage(message); + messageBean.setSubject(subject); + messageBean.setToAddress(toAddress); + messageBean.setAltSmtpHost(configuration.getProperty(ConfigurationKeys.ALT_SMTP_SERVER)); + messageBean.setSmtpHost(configuration.getProperty(ConfigurationKeys.SMTP_SERVER)); + messageBean.setFromAddress(configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN)); + return messageBean; + } + +} diff --git a/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/service/UserService.java b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/service/UserService.java new file mode 100644 index 0000000000..99161f9349 --- /dev/null +++ b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/service/UserService.java @@ -0,0 +1,35 @@ +package com.coderising.ood.srp.service; + +import java.util.List; + +import com.coderising.ood.srp.jdbc.UserJDBC; + +/** + * 用户 service + *

标题:

+ *

描述:

+ * @autho zx + * @time 2017年6月13日 上午12:53:30 +*/ +public class UserService { + + /** 模拟注入userJDBC */ + private UserJDBC userJDBC = new UserJDBC(); + + /** + * 获取用户信息 + *

方法名称:

+ *

方法说明:

+ * @param productId + * @return + * @autho zx + * @time 2017年6月13日 上午12:56:45 + */ + public List queryUserInfo(String productId){ + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productId +"' " + + "and send_mail=1 "; + return userJDBC.selectUserId(sendMailQuery); + } + +} diff --git a/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/util/DBUtil.java b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/util/DBUtil.java new file mode 100644 index 0000000000..e466fcb0d4 --- /dev/null +++ b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/util/DBUtil.java @@ -0,0 +1,32 @@ +package com.coderising.ood.srp.util; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * 模拟获取数据库 + *

标题:

+ *

描述:

+ * @autho zx + * @time 2017年6月12日 下午11:47:21 +*/ +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/util/FileUtil.java b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/util/FileUtil.java new file mode 100644 index 0000000000..01eeef3227 --- /dev/null +++ b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/util/FileUtil.java @@ -0,0 +1,52 @@ +package com.coderising.ood.srp.util; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import com.coderising.ood.srp.bean.Product; + +/** + * file工具类 + *

标题:

+ *

描述:

+ * @autho zx + * @time 2017年6月13日 上午2:04:59 +*/ +public class FileUtil { + + /** + * 读取商品信息 + *

方法名称:

+ *

方法说明:

+ * @param file + * @return + * @throws IOException + * @autho zx + * @time 2017年6月13日 上午12:39:06 + */ + public static Product readFile(File file) throws IOException{ + BufferedReader br = null; + Product product = new Product(); + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + String productId = data[0]; + String productDesc = data[1]; + product.setProductId(productId); + product.setProductDesc(productDesc); + + System.out.println("产品ID = " + productId + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + return product; + } + +} diff --git a/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java new file mode 100644 index 0000000000..a7ecb7f213 --- /dev/null +++ b/students/511739113/6.11/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp.util; + +import com.coderising.ood.srp.bean.Message; + +/** + * 消息推送工具类 + *

标题:

+ *

描述:

+ * @autho zhangxu + * @time 2017年6月13日 上午2:03:46 +*/ +public class MailUtil { + + public static void sendEmail(Message message,boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(message.getFromAddress()).append("\n"); + buffer.append("To:").append(message.getToAddress()).append("\n"); + buffer.append("Subject:").append(message.getSubject()).append("\n"); + buffer.append("Content:").append(message.getMessage()).append("\n"); + System.out.println(buffer.toString()); + } + + +} diff --git a/students/513274874/ood/ood-assignment/pom.xml b/students/513274874/ood/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/513274874/ood/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/builder/Attribute.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/builder/Attribute.java new file mode 100644 index 0000000000..6ee7739309 --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/builder/Attribute.java @@ -0,0 +1,11 @@ +package com.coderising.dp.builder; + +public class Attribute{ + public Attribute(String name, String value) { + this.name = name; + this.value = value; + } + String name; + String value; + + } \ No newline at end of file diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/builder/TagBuilder.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/builder/TagBuilder.java new file mode 100644 index 0000000000..59c9dd8066 --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/builder/TagBuilder.java @@ -0,0 +1,46 @@ +package com.coderising.dp.builder; + +public class TagBuilder { + TagNode root; + TagNode parNode; + TagNode curNode; + + + public TagBuilder(String rootTagName) { + root = new TagNode(rootTagName); + curNode = root; + parNode = root; + } + + public TagBuilder addChild(String childTagName) { + TagNode node = new TagNode(childTagName); + curNode.add(node); + parNode = curNode; + curNode = node; + return this; + } + + public TagBuilder addSibling(String siblingTagName) { + TagNode node = new TagNode(siblingTagName); + parNode.add(node); + parNode = curNode; + curNode = node; + return this; + + } + + public TagBuilder setAttribute(String name, String value) { + curNode.setAttribute(name, value); + return this; + } + + public TagBuilder setText(String value) { + curNode.setValue(value); + return this; + } + + public String toXML() { + return root.toXML(); + } + +} diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/builder/TagBuilderTest.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/builder/TagBuilderTest.java new file mode 100644 index 0000000000..e30d20285b --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/builder/TagBuilderTest.java @@ -0,0 +1,40 @@ +package com.coderising.dp.builder; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class TagBuilderTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testToXML() { + + TagBuilder builder = new TagBuilder("order"); + + String xml = builder.addChild("line-items") + .addChild("line-item").setAttribute("pid", "P3677").setAttribute("qty", "3") + .addSibling("line-item").setAttribute("pid", "P9877").setAttribute("qty", "10") + .toXML(); + + String expected = "" + + "" + + "" + + "" + + "" + + ""; + + System.out.println(xml); + assertEquals(expected, xml); + } + +} diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/builder/TagNode.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/builder/TagNode.java new file mode 100644 index 0000000000..0a28545af0 --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/builder/TagNode.java @@ -0,0 +1,78 @@ +package com.coderising.dp.builder; + +import java.util.ArrayList; +import java.util.List; + +public class TagNode { + private String tagName; + private String tagValue; + private List children = new ArrayList<>(); + private List attributes = new ArrayList<>(); + + public TagNode(String name){ + this.tagName = name; + } + public void add(TagNode child){ + this.children.add(child); + } + public void setAttribute(String name, String value) { + Attribute attr = findAttribute(name); + if(attr != null){ + attr.value = value; + return; + } + + attributes.add(new Attribute(name,value)); + } + private Attribute findAttribute(String name){ + for(Attribute attr : attributes){ + if(attr.name.equals(name)){ + return attr; + } + } + return null; + } + public void setValue(String value) { + this.tagValue = value; + } + public String getTagName() { + return tagName; + } + public List getChildren() { + return children; + } + + public String toXML(){ + return toXML(this); + } + private String toXML(TagNode node){ + StringBuilder buffer = new StringBuilder(); + buffer.append("<").append(node.tagName); + if(node.attributes.size()> 0){ + for(int i=0;i"); + return buffer.toString(); + } + buffer.append(">"); + for(TagNode childNode : node.children){ + buffer.append(toXML(childNode)); + } + buffer.append(""); + + + return buffer.toString(); + } + private String toXML(Attribute attr){ + return attr.name+"=\""+attr.value + "\""; + } + + public TagNode(TagBuilder builder){ + + + } +} diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java new file mode 100644 index 0000000000..0d0d01098f --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return null; + } + +} diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java new file mode 100644 index 0000000000..e404d9e702 --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java @@ -0,0 +1,39 @@ +package com.coderising.ood.ocp; + +public class Logger { + + public final int RAW_LOG = 1; + public final int RAW_LOG_WITH_DATE = 2; + + public final int EMAIL_LOG = 1; + public final int SMS_LOG = 2; + public final int PRINT_LOG = 3; + + int type = 0; + int method = 0; + + public Logger(int logType, int logMethod){ + this.type = logType; + this.method = logMethod; + } + public void log(String msg){ + + String logMsg = msg; + + if(this.type == RAW_LOG){ + logMsg = msg; + } else if(this.type == RAW_LOG_WITH_DATE){ + String txtDate = DateUtil.getCurrentDateAsString(); + logMsg = txtDate + ": " + msg; + } + + if(this.method == EMAIL_LOG){ + MailUtil.send(logMsg); + } else if(this.method == SMS_LOG){ + SMSUtil.send(logMsg); + } else if(this.method == PRINT_LOG){ + System.out.println(logMsg); + } + } +} + diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java new file mode 100644 index 0000000000..59d77649a2 --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/MailUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class MailUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java new file mode 100644 index 0000000000..fab4cd01b7 --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class SMSUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/Fomatter.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/Fomatter.java new file mode 100644 index 0000000000..6d107d54e9 --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/Fomatter.java @@ -0,0 +1,8 @@ +package com.coderising.ood.ocp.mine; + +/** + * Created by guodongchow on 2017/6/21. + */ +public interface Fomatter { + public String format(String message); +} diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/Logger.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/Logger.java new file mode 100644 index 0000000000..e25da9ca4b --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/Logger.java @@ -0,0 +1,19 @@ +package com.coderising.ood.ocp.mine; + +/** + * Created by guodongchow on 2017/6/21. + */ +public class Logger { + + private Fomatter fomatter; + private Processor processor; + + public Logger(Fomatter fomatter, Processor processor) { + this.fomatter = fomatter; + this.processor = processor; + } + + public void log(String message){ + processor.process(fomatter.format(message)); + } +} diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/MailProcessor.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/MailProcessor.java new file mode 100644 index 0000000000..c3ce50d5ec --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/MailProcessor.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp.mine; + +/** + * Created by guodongchow on 2017/6/21. + */ +public class MailProcessor implements Processor { + public void process(String message) { + System.out.println("Mail sending message :"+message); + } +} diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/PrintProcessor.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/PrintProcessor.java new file mode 100644 index 0000000000..13b983064d --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/PrintProcessor.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp.mine; + +/** + * Created by guodongchow on 2017/6/21. + */ +public class PrintProcessor implements Processor { + public void process(String message) { + System.out.println("Printing message :"+message); + } +} diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/Processor.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/Processor.java new file mode 100644 index 0000000000..4cca74572f --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/Processor.java @@ -0,0 +1,8 @@ +package com.coderising.ood.ocp.mine; + +/** + * Created by guodongchow on 2017/6/21. + */ +public interface Processor { + public void process(String message); +} diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/RawLogFormatter.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/RawLogFormatter.java new file mode 100644 index 0000000000..550361b511 --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/RawLogFormatter.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp.mine; + +/** + * Created by guodongchow on 2017/6/21. + */ +public class RawLogFormatter implements Fomatter { + + public String format(String message) { + return message; + } +} diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/RawWithDateLogFormatter.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/RawWithDateLogFormatter.java new file mode 100644 index 0000000000..80da623d5d --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/RawWithDateLogFormatter.java @@ -0,0 +1,13 @@ +package com.coderising.ood.ocp.mine; + +import java.util.Date; + +/** + * Created by guodongchow on 2017/6/21. + */ +public class RawWithDateLogFormatter implements Fomatter { + public String format(String message) { + String txtDate = new Date().toString(); + return txtDate + ":" + message; + } +} diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/SMSProcessor.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/SMSProcessor.java new file mode 100644 index 0000000000..946c14dea0 --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/ocp/mine/SMSProcessor.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp.mine; + +/** + * Created by guodongchow on 2017/6/21. + */ +public class SMSProcessor implements Processor { + public void process(String message) { + System.out.println("SMS sending message :" + message); + } +} diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..b4cacc1958 --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,74 @@ +package com.coderising.ood.srp; + +import com.coderising.ood.srp.constants.ConfigurationKeys; + +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + + private static Configuration configuration = null; + static Map configurations = new HashMap(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + + + public static Configuration getInstance(){ + + if(configuration == null) { + return new Configuration(); + } + return configuration; + } + + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + + private Configuration() { + setSMTPHost(); + setAltSMTPHost(); + setFromAddress(); + } + + protected void setSMTPHost() + { + smtpHost = getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() + { + altSmtpHost = getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + protected void setFromAddress() { + fromAddress = getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + public String getSmtpHost() { + return smtpHost; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public String getFromAddress() { + return fromAddress; + } +} diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..3f7d7bbee9 --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,89 @@ +package com.coderising.ood.srp; + +import com.coderising.ood.srp.dto.Mail; +import com.coderising.ood.srp.dto.Product; +import com.coderising.ood.srp.dto.User; +import com.coderising.ood.srp.util.DBUtil; +import com.coderising.ood.srp.util.MailUtil; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + protected Product product = new Product(); + + private static Configuration config; + + public static void main(String[] args) throws Exception { + + File f = new File("/Users/guodongchow/Desktop/coding2017/projects/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + + config = Configuration.getInstance(); + + sendEMails(mailDebug, loadMailingList()); + } + + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + product.setProductID(data[0]); + product.setProductDesc(data[1]); + + System.out.println("产品ID = " + product.getProductID()); + System.out.println("产品描述 = " + product.getProductDesc() + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + protected Mail configureEMail(User user, Product product) throws IOException { + return new Mail(user, product); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException { + + System.out.println("开始发送邮件"+ ":\n"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + Mail mail = configureEMail((User) iter.next(), product); + if (mail.getToAddress().length() > 0) + MailUtil.sendEmail(mail, config, debug); + } + + } else { + System.out.println("没有邮件发送"); + + } + } +} diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/constants/ConfigurationKeys.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/constants/ConfigurationKeys.java new file mode 100644 index 0000000000..9932bf60f4 --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/constants/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp.constants; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dto/Mail.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dto/Mail.java new file mode 100644 index 0000000000..e160e39038 --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dto/Mail.java @@ -0,0 +1,43 @@ +package com.coderising.ood.srp.dto; + +import java.io.IOException; + +/** + * Created by guodongchow on 2017/6/15. + */ +public class Mail { + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected void setMessage(User userInfo,Product product) throws IOException + { + + String name = userInfo.getName(); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!" ; + + } + + public Mail(User userInfo,Product product){ + try { + setMessage(userInfo,product); + } catch (IOException e) { + e.printStackTrace(); + } + toAddress = userInfo.getMailAddress(); + } + + public String getToAddress() { + return toAddress; + } + + public String getSubject() { + return subject; + } + + public String getMessage() { + return message; + } +} diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dto/Product.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dto/Product.java new file mode 100644 index 0000000000..0684794a72 --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dto/Product.java @@ -0,0 +1,29 @@ +package com.coderising.ood.srp.dto; + +/** + * Created by guodongchow on 2017/6/15. + */ +public class Product { + + String productID; + String productDesc; + + public void setProductID(String productID) + { + this.productID = productID; + + } + + public void setProductDesc(String desc) { + this.productDesc = desc; + } + + + public String getProductID() { + return productID; + } + + public String getProductDesc() { + return productDesc; + } +} diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dto/User.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dto/User.java new file mode 100644 index 0000000000..89b98d226d --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dto/User.java @@ -0,0 +1,30 @@ +package com.coderising.ood.srp.dto; + +/** + * Created by guodongchow on 2017/6/15. + */ +public class User { + String name; + String mailAddress; + + public User(String name, String mailAddress) { + this.name = name; + this.mailAddress = mailAddress; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getMailAddress() { + return mailAddress; + } + + public void setMailAddress(String mailAddress) { + this.mailAddress = mailAddress; + } +} diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/DBUtil.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/DBUtil.java new file mode 100644 index 0000000000..d2848fe5b1 --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/DBUtil.java @@ -0,0 +1,39 @@ +package com.coderising.ood.srp.util; + +import com.coderising.ood.srp.dto.Product; +import com.coderising.ood.srp.dto.User; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + protected String sendMailQuery = null; + /** + * 应该从数据库读, 但是简化为直接生成。 + * @return + */ + public static List query(){ + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + + userList.add(new User("User"+i,"aa@bb.com")); + } + + return userList; + } + + protected void setLoadQuery( Product product) throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + product.getProductID() + "' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"+ "\n"); + } + + + +} diff --git a/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java new file mode 100644 index 0000000000..5d6ec25bbb --- /dev/null +++ b/students/513274874/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java @@ -0,0 +1,37 @@ +package com.coderising.ood.srp.util; + +import com.coderising.ood.srp.Configuration; +import com.coderising.ood.srp.dto.Mail; + +public class MailUtil { + + public static void sendEmail(Mail mail,Configuration config, + boolean debug) { + + StringBuilder buffer = new StringBuilder(); + try { + //假装发了一封邮件 + buffer.append("With SmtpHost:").append(config.getSmtpHost()).append("\n"); + + }catch (Exception e){ + try { + //假装发了一封邮件 + buffer.append("With AltSmtpHost:").append(config.getAltSmtpHost()).append(":\n"); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + + buffer.append("From:").append(config.getFromAddress()).append("\n"); + buffer.append("To:").append(mail.getToAddress()).append("\n"); + buffer.append("Subject:").append(mail.getSubject()).append("\n"); + buffer.append("Content:").append(mail.getMessage()).append("\n"); + + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/515868058/.gitignore b/students/515868058/.gitignore new file mode 100644 index 0000000000..d1651ea2f6 --- /dev/null +++ b/students/515868058/.gitignore @@ -0,0 +1,16 @@ +/target/ +/bin/ +.classpath +.project +/.project +.idea/libraries/Maven__junit_junit_4_12.xml +.idea/libraries/Maven__org_apache_ant_ant_1_9_6.xml +.idea/libraries/Maven__org_apache_ant_ant_launcher_1_9_6.xml +.idea/libraries/Maven__org_apache_commons_commons_lang3_3_5.xml +.idea/libraries/Maven__org_hamcrest_hamcrest_core_1_3.xml +.idea/libraries/Maven__org_slf4j_slf4j_api_1_7_24.xml +.idea/sonarlint/ +.idea/workspace.xml +logfile.log +logfile1.log +/.idea/ diff --git a/students/515868058/ood-assignment/pom.xml b/students/515868058/ood-assignment/pom.xml new file mode 100644 index 0000000000..1a0471dccc --- /dev/null +++ b/students/515868058/ood-assignment/pom.xml @@ -0,0 +1,44 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..fcaa1dd3e2 --- /dev/null +++ b/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,22 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + + userList.add(new UserInfo("User" + i, "aa@bb.com")); + } + + return userList; + } +} diff --git a/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java b/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java new file mode 100644 index 0000000000..32571d3505 --- /dev/null +++ b/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java @@ -0,0 +1,45 @@ +package com.coderising.ood.srp; + +/** + * Created by James on 6/15/2017. + */ +public class Mail { + + private Configuration config; + + private String smtpHost = null; + private String altSmtpHost = null; + private String fromAddress = null; + + public Mail(Configuration config) { + this.config =config; + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + + } + + protected void setSMTPHost() { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + protected void setFromAddress() { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + public void sendEmail(String toAddress, String subject, String message, boolean debug) throws Exception { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + + + } + + public void sendAltEmail(String toAddress, String subject, String message, boolean debug) throws Exception{ + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + } +} diff --git a/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..9f9e749af7 --- /dev/null +++ b/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java b/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..820f63cacd --- /dev/null +++ b/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,54 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +/** + * Created by James on 6/16/2017. + */ +public class Product { + + + private String productID = null; + private String productDesc = null; + + public Product(String id, String desc) { + this.productID = id; + this.productDesc = desc; + } + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + + public static Product buildProduct(File file) throws IOException { + + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + return new Product(data[0], data[1]); + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + + } +} diff --git a/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..c61f0afdbc --- /dev/null +++ b/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,105 @@ +package com.coderising.ood.srp; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +public class PromotionMail { + private Product product; + private Mail mail = null; + private List mailList; + + + public static void main(String[] args) throws Exception { + + File f = new File(PromotionMail.class.getClassLoader().getResource("product_promotion.txt").getPath()); + + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + pe.sendEMails(emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + mail = new Mail(new Configuration()); + product = Product.buildProduct(file); + + } + + + public void sendEMails(boolean debug) throws IOException { + + System.out.println("开始发送邮件"); + if (getMailList() != null) { + getMailList().forEach( + userInfo -> { + if (userInfo.getEmail().length() > 0) { + try { + mail.sendEmail(userInfo.getEmail(), getSubject(), getMessage(userInfo.getName(), getProduct().getProductDesc()), debug); + } catch (Exception e) { + try { + mail.sendAltEmail(userInfo.getEmail(), getSubject(), getMessage(userInfo.getName(), getProduct().getProductDesc()), debug); + } catch (Exception e1) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e1.getMessage()); + } + } + } + } + ); + } else { + System.out.println("没有邮件发送"); + } + + + } + + private String getSubject() { + return "您关注的产品降价了"; + } + + private String getMessage(String username, String productDesc) { + return "尊敬的 " + username + ", 您关注的产品 " + productDesc + " 降价了,欢迎购买!"; + + } + + public List getMailList() { + if (mailList == null) { + try { + return loadMailingList(loadQuery(getProduct().getProductID())); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } else { + return this.mailList; + } + } + + public Product getProduct() { + return product; + } + + public void setProduct(Product product) { + this.product = product; + } + + private String loadQuery(String productID) throws Exception { + + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID + "' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + return sendMailQuery; + } + + + private List loadMailingList(String queryString) throws Exception { + return DBUtil.query(queryString); + } + +} diff --git a/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/UserInfo.java b/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/UserInfo.java new file mode 100644 index 0000000000..8bbd72f035 --- /dev/null +++ b/students/515868058/ood-assignment/src/main/java/com/coderising/ood/srp/UserInfo.java @@ -0,0 +1,31 @@ +package com.coderising.ood.srp; + +/** + * Created by James on 6/15/2017. + */ +public class UserInfo { + + private String name; + private String email; + + public UserInfo(String name, String email){ + this.name = name; + this.email = email; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/students/515868058/ood-assignment/src/main/resources/product_promotion.txt b/students/515868058/ood-assignment/src/main/resources/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/515868058/ood-assignment/src/main/resources/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/542194147/pom.xml b/students/542194147/pom.xml new file mode 100644 index 0000000000..dfd96c3362 --- /dev/null +++ b/students/542194147/pom.xml @@ -0,0 +1,6 @@ + + 4.0.0 + com.coding2017 + season2 + 0.0.1-SNAPSHOT + \ No newline at end of file diff --git a/students/542194147/src/main/java/com/coderising/ood/srp/config/Configuration.java b/students/542194147/src/main/java/com/coderising/ood/srp/config/Configuration.java new file mode 100644 index 0000000000..8474097a7e --- /dev/null +++ b/students/542194147/src/main/java/com/coderising/ood/srp/config/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp.config; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/542194147/src/main/java/com/coderising/ood/srp/config/ConfigurationKeys.java b/students/542194147/src/main/java/com/coderising/ood/srp/config/ConfigurationKeys.java new file mode 100644 index 0000000000..7fe226d1bd --- /dev/null +++ b/students/542194147/src/main/java/com/coderising/ood/srp/config/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp.config; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/542194147/src/main/java/com/coderising/ood/srp/domain/Email.java b/students/542194147/src/main/java/com/coderising/ood/srp/domain/Email.java new file mode 100644 index 0000000000..85b73ef7a4 --- /dev/null +++ b/students/542194147/src/main/java/com/coderising/ood/srp/domain/Email.java @@ -0,0 +1,55 @@ +package com.coderising.ood.srp.domain; + +import java.io.Serializable; +/** + * 邮件实体类 + * @author 小摩托 + * + */ +public class Email implements Serializable { + + private String smtpHost = null; + private String altSmtpHost = null; + private String fromAddress = null; + private String toAddress = null; + private String subject = null; + private String message = null; + public String getSmtpHost() { + return smtpHost; + } + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + public String getAltSmtpHost() { + return altSmtpHost; + } + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + public String getFromAddress() { + return fromAddress; + } + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + public String getToAddress() { + return toAddress; + } + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + public String getSubject() { + return subject; + } + public void setSubject(String subject) { + this.subject = subject; + } + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + +} diff --git a/students/542194147/src/main/java/com/coderising/ood/srp/domain/Product.java b/students/542194147/src/main/java/com/coderising/ood/srp/domain/Product.java new file mode 100644 index 0000000000..9976f9f09c --- /dev/null +++ b/students/542194147/src/main/java/com/coderising/ood/srp/domain/Product.java @@ -0,0 +1,28 @@ +package com.coderising.ood.srp.domain; + +import java.io.Serializable; + +/** + * 产品实体类 + * @author 小摩托 + * + */ +public class Product implements Serializable { + + private String productID = null; + private String productDesc = null; + public String getProductID() { + return productID; + } + public void setProductID(String productID) { + this.productID = productID; + } + public String getProductDesc() { + return productDesc; + } + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + + +} diff --git a/students/542194147/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/542194147/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/542194147/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/542194147/src/main/java/com/coderising/ood/srp/service/NoticeService.java b/students/542194147/src/main/java/com/coderising/ood/srp/service/NoticeService.java new file mode 100644 index 0000000000..53aa4b77d5 --- /dev/null +++ b/students/542194147/src/main/java/com/coderising/ood/srp/service/NoticeService.java @@ -0,0 +1,89 @@ +package com.coderising.ood.srp.service; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import com.coderising.ood.srp.config.Configuration; +import com.coderising.ood.srp.config.ConfigurationKeys; +import com.coderising.ood.srp.domain.Email; +import com.coderising.ood.srp.domain.Product; +import com.coderising.ood.srp.util.DBUtil; +import com.coderising.ood.srp.util.FileUtil; +import com.coderising.ood.srp.util.MailUtil; + +/** + * 消息发布接口 + * @author 小摩托 + * + */ +public class NoticeService { + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + private static Configuration config = new Configuration();; + + public void sendEMails(File file, boolean mailDebug) throws IOException + { + + String[] data=FileUtil.readFile(file); + Product product=new Product(); + product.setProductID(data[0]); + product.setProductDesc(data[1]); + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + product.getProductID() +"' " + + "and send_mail=1 "; + List list=DBUtil.query(sendMailQuery); + System.out.println("开始发送邮件"); + Email email=new Email(); + if (list != null) { + Iterator iter = list.iterator(); + while (iter.hasNext()) { + Map userInfo=(HashMap) iter.next(); + String toAddress = (String)userInfo.get(EMAIL_KEY); + email.setToAddress(toAddress); + email.setFromAddress(config.getProperty(ConfigurationKeys.EMAIL_ADMIN)); + email.setSmtpHost(config.getProperty(ConfigurationKeys.SMTP_SERVER)); + email.setAltSmtpHost(config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER)); + if (toAddress.length() > 0){ + String name = (String)userInfo.get(NAME_KEY); + email.setSubject("您关注的产品降价了"); + email.setMessage("尊敬的 "+name+", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!"); + } + try + { + if (toAddress.length() > 0) + MailUtil.sendEmail(email); + } + catch (Exception e) + { + try { + MailUtil.sendEmail(email); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } + else { + System.out.println("没有邮件发送"); + + } + + } + public static void main(String[] args) throws Exception { + + File f = new File("C:\\Users\\john\\Documents\\GitHub\\coding2017-2ndSeason\\students\\542194147\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"); + boolean emailDebug = false; + NoticeService ns = new NoticeService(); + ns.sendEMails(f, emailDebug); + + } +} diff --git a/students/542194147/src/main/java/com/coderising/ood/srp/util/DBUtil.java b/students/542194147/src/main/java/com/coderising/ood/srp/util/DBUtil.java new file mode 100644 index 0000000000..886477c678 --- /dev/null +++ b/students/542194147/src/main/java/com/coderising/ood/srp/util/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp.util; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa"+i+"@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/542194147/src/main/java/com/coderising/ood/srp/util/FileUtil.java b/students/542194147/src/main/java/com/coderising/ood/srp/util/FileUtil.java new file mode 100644 index 0000000000..035ec8749f --- /dev/null +++ b/students/542194147/src/main/java/com/coderising/ood/srp/util/FileUtil.java @@ -0,0 +1,26 @@ +package com.coderising.ood.srp.util; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +public class FileUtil { + + public static String[] readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + return data; + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } +} diff --git a/students/542194147/src/main/java/com/coderising/ood/srp/util/MailUtil.java b/students/542194147/src/main/java/com/coderising/ood/srp/util/MailUtil.java new file mode 100644 index 0000000000..817ca96466 --- /dev/null +++ b/students/542194147/src/main/java/com/coderising/ood/srp/util/MailUtil.java @@ -0,0 +1,19 @@ +package com.coderising.ood.srp.util; + +import com.coderising.ood.srp.domain.Email; + +public class MailUtil { + + public static void sendEmail(Email email) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(email.getFromAddress()).append("\n"); + buffer.append("To:").append(email.getToAddress()).append("\n"); + buffer.append("Subject:").append(email.getSubject()).append("\n"); + buffer.append("Content:").append(email.getMessage()).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/dp/bridge/Bridage.java b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/bridge/Bridage.java new file mode 100644 index 0000000000..0b5f606a67 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/bridge/Bridage.java @@ -0,0 +1,32 @@ +package com.github.orajavac.coding2017.ood.dp.bridge; + +public abstract class Bridage { + + private GraphicLibraryInter1 g1; + + public GraphicLibraryInter1 getG1() { + return g1; + } + + public void setG1(GraphicLibraryInter1 g1) { + this.g1 = g1; + } + + public GraphicLibraryInter2 getG2() { + return g2; + } + + public void setG2(GraphicLibraryInter2 g2) { + this.g2 = g2; + } + + private GraphicLibraryInter2 g2; + + public void drawAGraph(){ + + } + + public void drawGraph(){ + + } +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/dp/bridge/GraphicLibrary1.java b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/bridge/GraphicLibrary1.java new file mode 100644 index 0000000000..327caf7645 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/bridge/GraphicLibrary1.java @@ -0,0 +1,10 @@ +package com.github.orajavac.coding2017.ood.dp.bridge; + +public class GraphicLibrary1 implements GraphicLibraryInter1{ + public void draw_a_line(int x1,int y1,int x2,int y2){ + System.out.println("draw_a_line"); + } + public void draw_a_circle(int x,int y, int r){ + System.out.println("draw_a_circle"); + } +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/dp/bridge/GraphicLibrary2.java b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/bridge/GraphicLibrary2.java new file mode 100644 index 0000000000..903f7e8869 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/bridge/GraphicLibrary2.java @@ -0,0 +1,10 @@ +package com.github.orajavac.coding2017.ood.dp.bridge; + +public class GraphicLibrary2 implements GraphicLibraryInter2{ + public void drawLine(int x1,int x2,int y1,int y2){ + System.out.println("drawLine"); + } + public void drawCircle(int x,int y, int r){ + System.out.println("drawCircle"); + } +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/dp/bridge/GraphicLibraryInter1.java b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/bridge/GraphicLibraryInter1.java new file mode 100644 index 0000000000..514ea4362d --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/bridge/GraphicLibraryInter1.java @@ -0,0 +1,6 @@ +package com.github.orajavac.coding2017.ood.dp.bridge; + +public interface GraphicLibraryInter1 { + public void draw_a_line(int x1,int y1,int x2,int y2); + public void draw_a_circle(int x,int y, int r); +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/dp/bridge/GraphicLibraryInter2.java b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/bridge/GraphicLibraryInter2.java new file mode 100644 index 0000000000..55946c6419 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/bridge/GraphicLibraryInter2.java @@ -0,0 +1,6 @@ +package com.github.orajavac.coding2017.ood.dp.bridge; + +public interface GraphicLibraryInter2 { + public void drawLine(int x1,int x2,int y1,int y2); + public void drawCircle(int x,int y, int r); +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/dp/bridge/MyBridge.java b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/bridge/MyBridge.java new file mode 100644 index 0000000000..30762d49f9 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/bridge/MyBridge.java @@ -0,0 +1,14 @@ +package com.github.orajavac.coding2017.ood.dp.bridge; + +public class MyBridge extends Bridage{ + + public void drawAGraph(){ + getG1().draw_a_circle(1,2,3); + getG1().draw_a_line(1, 2,3,4); + } + + public void drawGraph(){ + getG2().drawLine(1,2,3,4); + getG2().drawCircle(1, 2,3); + } +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/dp/builder/TagBuilder.java b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/builder/TagBuilder.java new file mode 100644 index 0000000000..9fa50d3529 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/builder/TagBuilder.java @@ -0,0 +1,38 @@ +package com.github.orajavac.coding2017.ood.dp.builder; + +public class TagBuilder { + + private TagNode rootNode; + private TagNode currentNode; + private TagNode parentNode; + public TagBuilder(String rootTagName){ + rootNode = new TagNode(rootTagName); + currentNode = rootNode; + parentNode = null; + } + + public TagBuilder addChild(String childTagName){ + parentNode = this.currentNode; + this.currentNode = new TagNode(childTagName); + parentNode.add(currentNode); + return this; + } + public TagBuilder addSibling(String siblingTagName){ + + this.currentNode = new TagNode(siblingTagName); + parentNode.add(this.currentNode); + return this; + + } + public TagBuilder setAttribute(String name, String value){ + this.currentNode.setAttribute(name, value); + return this; + } + public TagBuilder setText(String value){ + this.currentNode.setValue(value); + return this; + } + public String toXML(){ + return this.rootNode.toXML(); + } +} \ No newline at end of file diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/dp/builder/TagBuilderTest.java b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/builder/TagBuilderTest.java new file mode 100644 index 0000000000..4922057b53 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/builder/TagBuilderTest.java @@ -0,0 +1,39 @@ +package com.github.orajavac.coding2017.ood.dp.builder; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class TagBuilderTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testToXML() { + +TagBuilder builder = new TagBuilder("order"); + + String xml = builder.addChild("line-items") + .addChild("line-item").setAttribute("pid", "P3677").setAttribute("qty", "3") + .addSibling("line-item").setAttribute("pid", "P9877").setAttribute("qty", "10") + .toXML(); + + String expected = "" + + "" + + "" + + "" + + "" + + ""; + + System.out.println(xml); + assertEquals(expected, xml); + } +} \ No newline at end of file diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/dp/builder/TagNode.java b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/builder/TagNode.java new file mode 100644 index 0000000000..dd305c8c0f --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/builder/TagNode.java @@ -0,0 +1,83 @@ +package com.github.orajavac.coding2017.ood.dp.builder; + +import java.util.ArrayList; +import java.util.List; + +public class TagNode { + private String tagName; + private String tagValue; + private List children = new ArrayList<>(); + private List attributes = new ArrayList<>(); + + public TagNode(String name){ + this.tagName = name; + } + public void add(TagNode child){ + this.children.add(child); + } + public void setAttribute(String name, String value) { + Attribute attr = findAttribute(name); + if(attr != null){ + attr.value = value; + return; + } + + attributes.add(new Attribute(name,value)); + } + private Attribute findAttribute(String name){ + for(Attribute attr : attributes){ + if(attr.name.equals(name)){ + return attr; + } + } + return null; + } + public void setValue(String value) { + this.tagValue = value; + + } + public String getTagName() { + return tagName; + } + public List getChildren() { + return children; + } + + private static class Attribute{ + public Attribute(String name, String value) { + this.name = name; + this.value = value; + } + String name; + String value; + + } + public String toXML(){ + return toXML(this); + } + private String toXML(TagNode node){ + StringBuilder buffer = new StringBuilder(); + buffer.append("<").append(node.tagName); + if(node.attributes.size()> 0){ + for(int i=0;i"); + return buffer.toString(); + } + buffer.append(">"); + for(TagNode childNode : node.children){ + buffer.append(toXML(childNode)); + } + buffer.append(""); + + + return buffer.toString(); + } + private String toXML(Attribute attr){ + return attr.name+"=\""+attr.value + "\""; + } +} \ No newline at end of file diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/dp/composite/Line.java b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/composite/Line.java new file mode 100644 index 0000000000..fd0187f8f7 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/composite/Line.java @@ -0,0 +1,9 @@ +package com.github.orajavac.coding2017.ood.dp.composite; + +public class Line implements Shape{ + @Override + public void draw() { + + + } +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/dp/composite/Rectangle.java b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/composite/Rectangle.java new file mode 100644 index 0000000000..0c48433bd1 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/composite/Rectangle.java @@ -0,0 +1,9 @@ +package com.github.orajavac.coding2017.ood.dp.composite; + +public class Rectangle implements Shape{ + @Override + public void draw() { + // TODO Auto-generated method stub + + } +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/dp/composite/Shape.java b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/composite/Shape.java new file mode 100644 index 0000000000..4760261807 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/composite/Shape.java @@ -0,0 +1,5 @@ +package com.github.orajavac.coding2017.ood.dp.composite; + +public interface Shape { + public void draw(); +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/dp/composite/Square.java b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/composite/Square.java new file mode 100644 index 0000000000..4c722ef6b0 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/composite/Square.java @@ -0,0 +1,9 @@ +package com.github.orajavac.coding2017.ood.dp.composite; + +public class Square implements Shape{ + @Override + public void draw() { + // TODO Auto-generated method stub + + } +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/dp/composite/Text.java b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/composite/Text.java new file mode 100644 index 0000000000..0f964c516e --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/composite/Text.java @@ -0,0 +1,9 @@ +package com.github.orajavac.coding2017.ood.dp.composite; + +public class Text implements Shape{ + @Override + public void draw() { + // TODO Auto-generated method stub + + } +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/dp/decorator/Email.java b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/decorator/Email.java new file mode 100644 index 0000000000..b7ad769be7 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/decorator/Email.java @@ -0,0 +1,5 @@ +package com.github.orajavac.coding2017.ood.dp.decorator; + +public interface Email { + public String getContent(); +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/dp/decorator/EmailDecorator.java b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/decorator/EmailDecorator.java new file mode 100644 index 0000000000..4a441ae7c4 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/decorator/EmailDecorator.java @@ -0,0 +1,14 @@ +package com.github.orajavac.coding2017.ood.dp.decorator; + +public class EmailDecorator implements Email{ + + private Email email; + + public EmailDecorator(Email e){ + this.email = e; + } + + public String getContent(){ + return email.getContent()+",本邮件仅为个人观点,并不代表公司立场"; + } +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/dp/decorator/EmailEncryptDecorator.java b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/decorator/EmailEncryptDecorator.java new file mode 100644 index 0000000000..56c653fcfe --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/dp/decorator/EmailEncryptDecorator.java @@ -0,0 +1,13 @@ +package com.github.orajavac.coding2017.ood.dp.decorator; + +public class EmailEncryptDecorator implements Email{ + private Email email; + + public EmailEncryptDecorator(Email e){ + this.email = e; + } + + public String getContent(){ + return "$a^@ rawlog = new ArrayList(); + for (RawLogger r : rawlog){ + r.log(msg); + } + + List logger = new ArrayList(); + for (Logger l : logger){ + l.send(msg); + } + } +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/ocp/MailUtil.java b/students/562768642/src/com/github/orajavac/coding2017/ood/ocp/MailUtil.java new file mode 100644 index 0000000000..8cfd91064d --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/ocp/MailUtil.java @@ -0,0 +1,8 @@ +package com.github.orajavac.coding2017.ood.ocp; + +public class MailUtil implements Logger{ + public void send(String logMsg) { + // TODO Auto-generated method stub + + } +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/ocp/PrintUtil.java b/students/562768642/src/com/github/orajavac/coding2017/ood/ocp/PrintUtil.java new file mode 100644 index 0000000000..d83397c1d6 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/ocp/PrintUtil.java @@ -0,0 +1,8 @@ +package com.github.orajavac.coding2017.ood.ocp; + +public class PrintUtil implements Logger{ + public void send(String logMsg) { + // TODO Auto-generated method stub + + } +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/ocp/RawLog.java b/students/562768642/src/com/github/orajavac/coding2017/ood/ocp/RawLog.java new file mode 100644 index 0000000000..ad6cbb7510 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/ocp/RawLog.java @@ -0,0 +1,7 @@ +package com.github.orajavac.coding2017.ood.ocp; + +public class RawLog implements RawLogger{ + public void log(String msg){ + String logMsg = msg; + } +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/ocp/RawLogWithDate.java b/students/562768642/src/com/github/orajavac/coding2017/ood/ocp/RawLogWithDate.java new file mode 100644 index 0000000000..f9640769ee --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/ocp/RawLogWithDate.java @@ -0,0 +1,8 @@ +package com.github.orajavac.coding2017.ood.ocp; + +public class RawLogWithDate implements RawLogger{ + public void log(String msg){ + String txtDate = DateUtil.getCurrentDateAsString(); + String logMsg = txtDate + ": " + msg; + } +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/ocp/RawLogger.java b/students/562768642/src/com/github/orajavac/coding2017/ood/ocp/RawLogger.java new file mode 100644 index 0000000000..d4ad9eacd3 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/ocp/RawLogger.java @@ -0,0 +1,5 @@ +package com.github.orajavac.coding2017.ood.ocp; + +public interface RawLogger { + public void log(String msg); +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/ocp/SMSUtil.java b/students/562768642/src/com/github/orajavac/coding2017/ood/ocp/SMSUtil.java new file mode 100644 index 0000000000..82eb15bed9 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/ocp/SMSUtil.java @@ -0,0 +1,8 @@ +package com.github.orajavac.coding2017.ood.ocp; + +public class SMSUtil implements Logger{ + public void send(String logMsg) { + // TODO Auto-generated method stub + + } +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/srp/Configuration.java b/students/562768642/src/com/github/orajavac/coding2017/ood/srp/Configuration.java new file mode 100644 index 0000000000..bf9902bf99 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.github.orajavac.coding2017.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/srp/ConfigurationKeys.java b/students/562768642/src/com/github/orajavac/coding2017/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..94eb56e6e4 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.github.orajavac.coding2017.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/srp/DBUtil.java b/students/562768642/src/com/github/orajavac/coding2017/ood/srp/DBUtil.java new file mode 100644 index 0000000000..528ff9321d --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/srp/DBUtil.java @@ -0,0 +1,35 @@ +package com.github.orajavac.coding2017.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } + + public static void setLoadQuery(String productID) throws Exception { + + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/srp/FileUtil.java b/students/562768642/src/com/github/orajavac/coding2017/ood/srp/FileUtil.java new file mode 100644 index 0000000000..14f6443bbf --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/srp/FileUtil.java @@ -0,0 +1,31 @@ +package com.github.orajavac.coding2017.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +public class FileUtil { + public static Product readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + Product p = new Product(); + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + p.setProductID(data[0]); + p.setProductDesc(data[1]); + + System.out.println("产品ID = " + p.getProductID() + "\n"); + System.out.println("产品描述 = " + p.getProductDesc() + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + return p; + } +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/srp/Mail.java b/students/562768642/src/com/github/orajavac/coding2017/ood/srp/Mail.java new file mode 100644 index 0000000000..46f5a92db1 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/srp/Mail.java @@ -0,0 +1,49 @@ +package com.github.orajavac.coding2017.ood.srp; + +import java.io.IOException; +import java.util.HashMap; + +public class Mail { + private String smtpHost = null; + private String altSmtpHost = null; + private String fromAddress = null; + private String toAddress = null; + private String subject = null; + private String message = null; + public String getSmtpHost() { + return smtpHost; + } + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + public String getAltSmtpHost() { + return altSmtpHost; + } + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + public String getFromAddress() { + return fromAddress; + } + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + public String getToAddress() { + return toAddress; + } + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + public String getSubject() { + return subject; + } + public void setSubject(String subject) { + this.subject = subject; + } + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/srp/MailUtil.java b/students/562768642/src/com/github/orajavac/coding2017/ood/srp/MailUtil.java new file mode 100644 index 0000000000..aa16293062 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/srp/MailUtil.java @@ -0,0 +1,97 @@ +package com.github.orajavac.coding2017.ood.srp; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class MailUtil { + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + public static String setSMTPHost(Configuration config) + { + return config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + public static String setAltSMTPHost(Configuration config) + { + return config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + public static String setFromAddress(Configuration config) + { + return config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + public static void setMessage(HashMap userInfo,Product p,Mail mail) throws IOException + { + + String name = (String) userInfo.get(NAME_KEY); + + mail.setSubject("您关注的产品降价了"); + + String message = "尊敬的 "+name+", 您关注的产品 " + p.getProductDesc() + " 降价了,欢迎购买!" ; + mail.setMessage(message); + + + } + + public static void sendEMails(boolean debug, List mailingList,Product p,Mail mail) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + HashMap userInfo = (HashMap) iter.next(); + String toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo,p,mail); + try + { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, mail.getFromAddress(), mail.getSubject(), mail.getMessage(), mail.getSmtpHost(), debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(toAddress, mail.getFromAddress(), mail.getSubject(), mail.getMessage(), mail.getAltSmtpHost(), debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } + + else { + System.out.println("没有邮件发送"); + + } + + } + +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/srp/Product.java b/students/562768642/src/com/github/orajavac/coding2017/ood/srp/Product.java new file mode 100644 index 0000000000..02345d790c --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/srp/Product.java @@ -0,0 +1,18 @@ +package com.github.orajavac.coding2017.ood.srp; + +public class Product { + private String productID = null; + private String productDesc = null; + public String getProductID() { + return productID; + } + public void setProductID(String productID) { + this.productID = productID; + } + public String getProductDesc() { + return productDesc; + } + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/srp/PromotionMail.java b/students/562768642/src/com/github/orajavac/coding2017/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..53e7e27471 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/srp/PromotionMail.java @@ -0,0 +1,67 @@ +package com.github.orajavac.coding2017.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery = null; + + + protected Mail mail = new Mail(); + + + + private static Configuration config; + + + + + + + public static void main(String[] args) throws Exception { + + File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + Product p = FileUtil.readFile(file); + + + config = new Configuration(); + + mail.setSmtpHost(MailUtil.setSMTPHost(config)); + mail.setAltSmtpHost(MailUtil.setAltSMTPHost(config)); + + + mail.setFromAddress(MailUtil.setFromAddress(config)); + + + DBUtil.setLoadQuery(p.getProductID()); + + MailUtil.sendEMails(mailDebug, loadMailingList(),p,mail); + + + } + + + + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } +} diff --git a/students/562768642/src/com/github/orajavac/coding2017/ood/srp/product_promotion.txt b/students/562768642/src/com/github/orajavac/coding2017/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/562768642/src/com/github/orajavac/coding2017/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/583884851/src/main/java/com/coderising/ood/ocp/DateUtil.java b/students/583884851/src/main/java/com/coderising/ood/ocp/DateUtil.java new file mode 100644 index 0000000000..0d0d01098f --- /dev/null +++ b/students/583884851/src/main/java/com/coderising/ood/ocp/DateUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return null; + } + +} diff --git a/students/583884851/src/main/java/com/coderising/ood/ocp/Logger.java b/students/583884851/src/main/java/com/coderising/ood/ocp/Logger.java new file mode 100644 index 0000000000..aca173e665 --- /dev/null +++ b/students/583884851/src/main/java/com/coderising/ood/ocp/Logger.java @@ -0,0 +1,38 @@ +package com.coderising.ood.ocp; + +public class Logger { + + public final int RAW_LOG = 1; + public final int RAW_LOG_WITH_DATE = 2; + public final int EMAIL_LOG = 1; + public final int SMS_LOG = 2; + public final int PRINT_LOG = 3; + + int type = 0; + int method = 0; + + public Logger(int logType, int logMethod){ + this.type = logType; + this.method = logMethod; + } + public void log(String msg){ + + String logMsg = msg; + + if(this.type == RAW_LOG){ + logMsg = msg; + } else if(this.type == RAW_LOG_WITH_DATE){ + String txtDate = DateUtil.getCurrentDateAsString(); + logMsg = txtDate + ": " + msg; + } + + if(this.method == EMAIL_LOG){ + MailUtil.send(logMsg); + } else if(this.method == SMS_LOG){ + SMSUtil.send(logMsg); + } else if(this.method == PRINT_LOG){ + System.out.println(logMsg); + } + } +} + diff --git a/students/583884851/src/main/java/com/coderising/ood/ocp/MailUtil.java b/students/583884851/src/main/java/com/coderising/ood/ocp/MailUtil.java new file mode 100644 index 0000000000..59d77649a2 --- /dev/null +++ b/students/583884851/src/main/java/com/coderising/ood/ocp/MailUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class MailUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/583884851/src/main/java/com/coderising/ood/ocp/SMSUtil.java b/students/583884851/src/main/java/com/coderising/ood/ocp/SMSUtil.java new file mode 100644 index 0000000000..fab4cd01b7 --- /dev/null +++ b/students/583884851/src/main/java/com/coderising/ood/ocp/SMSUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class SMSUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/583884851/src/main/java/com/coderising/ood/ocp/good/Formatter.java b/students/583884851/src/main/java/com/coderising/ood/ocp/good/Formatter.java new file mode 100644 index 0000000000..b6e2ccbc16 --- /dev/null +++ b/students/583884851/src/main/java/com/coderising/ood/ocp/good/Formatter.java @@ -0,0 +1,7 @@ +package com.coderising.ood.ocp.good; + +public interface Formatter { + + String format(String msg); + +} diff --git a/students/583884851/src/main/java/com/coderising/ood/ocp/good/FormatterFactory.java b/students/583884851/src/main/java/com/coderising/ood/ocp/good/FormatterFactory.java new file mode 100644 index 0000000000..3c2009a674 --- /dev/null +++ b/students/583884851/src/main/java/com/coderising/ood/ocp/good/FormatterFactory.java @@ -0,0 +1,13 @@ +package com.coderising.ood.ocp.good; + +public class FormatterFactory { + public static Formatter createFormatter(int type){ + if(type == 1){ + return new RawFormatter(); + } + if (type == 2){ + return new HtmlFormatter(); + } + return null; + } +} diff --git a/students/583884851/src/main/java/com/coderising/ood/ocp/good/HtmlFormatter.java b/students/583884851/src/main/java/com/coderising/ood/ocp/good/HtmlFormatter.java new file mode 100644 index 0000000000..3d375f5acc --- /dev/null +++ b/students/583884851/src/main/java/com/coderising/ood/ocp/good/HtmlFormatter.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp.good; + +public class HtmlFormatter implements Formatter { + + @Override + public String format(String msg) { + + return null; + } + +} diff --git a/students/583884851/src/main/java/com/coderising/ood/ocp/good/Logger.java b/students/583884851/src/main/java/com/coderising/ood/ocp/good/Logger.java new file mode 100644 index 0000000000..f206472d0d --- /dev/null +++ b/students/583884851/src/main/java/com/coderising/ood/ocp/good/Logger.java @@ -0,0 +1,18 @@ +package com.coderising.ood.ocp.good; + +public class Logger { + + private Formatter formatter; + private Sender sender; + + public Logger(Formatter formatter,Sender sender){ + this.formatter = formatter; + this.sender = sender; + } + public void log(String msg){ + sender.send(formatter.format(msg)) ; + } + + +} + diff --git a/students/583884851/src/main/java/com/coderising/ood/ocp/good/RawFormatter.java b/students/583884851/src/main/java/com/coderising/ood/ocp/good/RawFormatter.java new file mode 100644 index 0000000000..7f1cb4ae30 --- /dev/null +++ b/students/583884851/src/main/java/com/coderising/ood/ocp/good/RawFormatter.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp.good; + +public class RawFormatter implements Formatter { + + @Override + public String format(String msg) { + + return null; + } + +} diff --git a/students/583884851/src/main/java/com/coderising/ood/ocp/good/Sender.java b/students/583884851/src/main/java/com/coderising/ood/ocp/good/Sender.java new file mode 100644 index 0000000000..aaa46c1fb7 --- /dev/null +++ b/students/583884851/src/main/java/com/coderising/ood/ocp/good/Sender.java @@ -0,0 +1,7 @@ +package com.coderising.ood.ocp.good; + +public interface Sender { + + void send(String msg); + +} diff --git a/students/583884851/src/main/java/com/coderising/ood/srp/Configuration.java b/students/583884851/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/583884851/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/583884851/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/583884851/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/583884851/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/583884851/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/583884851/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/583884851/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/583884851/src/main/java/com/coderising/ood/srp/Mail.java b/students/583884851/src/main/java/com/coderising/ood/srp/Mail.java new file mode 100644 index 0000000000..f195417dac --- /dev/null +++ b/students/583884851/src/main/java/com/coderising/ood/srp/Mail.java @@ -0,0 +1,44 @@ +package com.coderising.ood.srp; + +/** + * 邮件类 + * + * @author chengyu + * @version 17/6/20 + */ +public class Mail { + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + public Mail() { + + } + + public Mail(Configuration config) { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + public void send() { + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public void setContent(String subject, String message) { + this.subject = subject; + this.message = message; + } +} diff --git a/students/583884851/src/main/java/com/coderising/ood/srp/Product.java b/students/583884851/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..da05192e51 --- /dev/null +++ b/students/583884851/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,49 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +/** + * @author chengyu + * @version 17/6/20 + */ +public class Product { + protected String productID = null; + protected String productDesc = null; + + public Product() { + } + + public Product(String productID, String productDesc) { + this.productID = productID; + this.productDesc = productDesc; + } + + public static Product of(File file) throws IOException { + BufferedReader br; + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + System.out.println("产品ID = " + data[0] + "\n"); + System.out.println("产品描述 = " + data[1] + "\n"); + return new Product(data[0], data[1]); + } + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git a/students/583884851/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/583884851/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..307cfd3dd9 --- /dev/null +++ b/students/583884851/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,72 @@ +package com.coderising.ood.srp; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + private Product product; + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + public PromotionMail() { + File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + try { + product = Product.of(f); + } catch (IOException e) { + throw new RuntimeException(e.getMessage()); + } + } + + public static void main(String[] args) throws Exception { + PromotionMail pe = new PromotionMail(); + List emailList = pe.loadMailingList(); + pe.sendEMails(emailList); + } + + + protected List loadMailingList() throws Exception { + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + product.getProductID() + "' " + + "and send_mail=1 "; + return DBUtil.query(sendMailQuery); + } + + + protected void sendEMails(List mailingList) throws IOException { + + System.out.println("开始发送邮件"); + Mail mail = new Mail(new Configuration()); + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + HashMap userInfo = (HashMap) iter.next(); + mail.setToAddress((String) userInfo.get(EMAIL_KEY)); + setContent(mail, userInfo, product); + try { + mail.send(); + } catch (Exception e) { + try { + mail.send(); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + } else { + System.out.println("没有邮件发送"); + } + } + + private void setContent(Mail mail, HashMap userInfo, Product product) { + String subject = "您关注的产品降价了"; + String name = (String) userInfo.get(NAME_KEY); + String message = "尊敬的 " + name + ", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!"; + mail.setContent(subject, message); + } +} diff --git a/students/583884851/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/583884851/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/583884851/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/597222089/ood/ood-assignment/pom.xml b/students/597222089/ood/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/597222089/ood/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/Configuration.java b/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/Configuration.java new file mode 100644 index 0000000000..80efc902d7 --- /dev/null +++ b/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp.refactor; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/ConfigurationKeys.java b/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/ConfigurationKeys.java new file mode 100644 index 0000000000..5fa1f5fefb --- /dev/null +++ b/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp.refactor; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/Consumer.java b/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/Consumer.java new file mode 100644 index 0000000000..8bb8774dbd --- /dev/null +++ b/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/Consumer.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp.refactor; + +/** + * Created by walker on 2017/6/20. + */ + +public class Consumer { + private String name; + private String email; + + public Consumer(String name, String email) { + this.name = name; + this.email = email; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } +} diff --git a/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/ConsumerUtils.java b/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/ConsumerUtils.java new file mode 100644 index 0000000000..ad0f4be3d8 --- /dev/null +++ b/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/ConsumerUtils.java @@ -0,0 +1,39 @@ +package com.coderising.ood.srp.refactor; + +import com.coderising.ood.srp.DBUtil; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +/** + * Created by walker on 2017/6/20. + */ + +public class ConsumerUtils { + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + public static List getConsumers() { + List consumers = new ArrayList<>(); + + String sql = ""; + List query = DBUtil.query(sql); + + Iterator iter = query.iterator(); + while (iter.hasNext()) { + + HashMap info = (HashMap) iter.next(); + + String name = info.get(NAME_KEY); + String email = info.get(EMAIL_KEY); + + Consumer consumer = new Consumer(name, email); + + consumers.add(consumer); + } + + return consumers; + } +} diff --git a/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/Email.java b/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/Email.java new file mode 100644 index 0000000000..6d3f1d71f1 --- /dev/null +++ b/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/Email.java @@ -0,0 +1,36 @@ +package com.coderising.ood.srp.refactor; + +/** + * Created by walker on 2017/6/20. + */ + +public class Email { + private String subject; + private String message; + + private String fromAddress = null; + private String toAddress = null; + + public Email(String subject, String message, String fromAddress, String toAddress) { + this.subject = subject; + this.message = message; + this.fromAddress = fromAddress; + this.toAddress = toAddress; + } + + public String getSubject() { + return subject; + } + + public String getMessage() { + return message; + } + + public String getFromAddress() { + return fromAddress; + } + + public String getToAddress() { + return toAddress; + } +} diff --git a/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/EmailUtils.java b/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/EmailUtils.java new file mode 100644 index 0000000000..db90ca1ac6 --- /dev/null +++ b/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/EmailUtils.java @@ -0,0 +1,68 @@ +package com.coderising.ood.srp.refactor; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** + * Created by walker on 2017/6/20. + */ + +public class EmailUtils { + + private static final String SUBJECT = "您关注的产品降价了"; + private static String smtpHost; + private static String altSmtpHost; + private static boolean debug = false; + + private static List getEmails() { + List emails = new ArrayList<>(); + + List consumers = ConsumerUtils.getConsumers(); + Iterator iter = consumers.iterator(); + + Configuration conf = new Configuration(); + + smtpHost = conf.getProperty(ConfigurationKeys.SMTP_SERVER); + altSmtpHost = conf.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + while (iter.hasNext()) { + Consumer consumer = (Consumer) iter.next(); + String message = PhoneUtils.getMessage(consumer.getName()); + String fromAddress = conf.getProperty(ConfigurationKeys.EMAIL_ADMIN); + String toAddress = consumer.getEmail(); + Email email = new Email(SUBJECT, message, fromAddress, toAddress); + emails.add(email); + } + + return emails; + } + + private static void sendEmail(Email email, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(email.getFromAddress()).append("\n"); + buffer.append("To:").append(email.getToAddress()).append("\n"); + buffer.append("Subject:").append(email.getSubject()).append("\n"); + buffer.append("Content:").append(email.getMessage()).append("\n"); + System.out.println(buffer.toString()); + } + + public static void doSendEmail () { + + List emails = getEmails(); + for (Email email : emails) { + try { + sendEmail(email, smtpHost, debug); + } catch (Exception e) { + try { + sendEmail(email, altSmtpHost, debug); + + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + } +} diff --git a/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/MainSend.java b/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/MainSend.java new file mode 100644 index 0000000000..3ae14256b4 --- /dev/null +++ b/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/MainSend.java @@ -0,0 +1,16 @@ +package com.coderising.ood.srp.refactor; + +/** + * Created by walker on 2017/6/20. + */ + +public class MainSend { + + + public static void main(String[] args) { + EmailUtils.doSendEmail(); + } + + + +} diff --git a/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/Phone.java b/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/Phone.java new file mode 100644 index 0000000000..3e0cf3ff32 --- /dev/null +++ b/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/Phone.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp.refactor; + +/** + * Created by walker on 2017/6/19. + */ + +public class Phone { + private String productID = null; + private String productDesc = null; + + public Phone(String productID, String productDesc) { + this.productID = productID; + this.productDesc = productDesc; + } + + public String getProductDesc() { + return productDesc; + } + + public String getProductID() { + return productID; + } +} diff --git a/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/PhoneUtils.java b/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/PhoneUtils.java new file mode 100644 index 0000000000..a128f6bfd1 --- /dev/null +++ b/students/597222089/ood/ood-assignment/src/main/java/com/coderising/ood/srp/refactor/PhoneUtils.java @@ -0,0 +1,71 @@ +package com.coderising.ood.srp.refactor; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + + +public class PhoneUtils { + private static Set getPhones() { + Set phones = new HashSet<>(); + +// Map phoneInfos = readFile("file"); +// +// for (String id : phoneInfos.keySet()) { +// Phone photo = new Phone(); +// photo.setProductID(id); +// photo.setProductDesc(phoneInfos.get(id)); +// phones.add(photo); +// } + phones.add(new Phone("P8756", "iPhone8")); + phones.add(new Phone("P3946", "XiaoMi10")); + phones.add(new Phone("P8904", "Oppo_R15")); + phones.add(new Phone("P4955", "Vivo_X20")); + + return phones; + } + + public static String getMessage(String name) { + StringBuffer infos = new StringBuffer(); + + Set phones = getPhones(); + for (Phone phone : phones) { + infos.append("尊敬的 " + name + ", 您关注的产品 " + phone.getProductDesc() + " 降价了,欢迎购买!"); + } + return infos.toString(); + } + + private static Map readFile (String filePath) { + BufferedReader br = null; + Map phoneMap = new HashMap<>(); + try { + File file = new File(filePath); + br = new BufferedReader(new FileReader(file)); + + String temp; + while (null != (temp = br.readLine())) { + String[] data = temp.split(" "); + + phoneMap.put(data[0], data[1]); + System.out.println("产品ID = " + data[0] + "\n"); + System.out.println("产品描述 = " + data[1] + "\n"); + } + + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + return phoneMap; + } +} diff --git a/students/605159467/ood-assignment/pom.xml b/students/605159467/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/605159467/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/bean/Email.java b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/bean/Email.java new file mode 100644 index 0000000000..b8c16c5091 --- /dev/null +++ b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/bean/Email.java @@ -0,0 +1,98 @@ +package com.coderising.ood.srp.bean; + +import com.coderising.ood.srp.resource.ConfigurationKeys; +import com.coderising.ood.srp.utils.MailUtil; + +/** + * Created with IDEA + * Created by fuyi.ren on 2017/6/17 22:04 + * Description: + */ +public class Email +{ + + + + + + + private String toAddress; + private String fromAddress; + private String subject; + private String message; + private String smtpHost; + + public String getFromAddress() + { + return fromAddress; + } + + public void setFromAddress(String fromAddress) + { + this.fromAddress = fromAddress; + } + public String getToAddress() + { + return toAddress; + } + + public void setToAddress(String toAddress) + { + this.toAddress = toAddress; + } + + public String getSubject() + { + return subject; + } + + public void setSubject(String subject) + { + this.subject = subject; + } + + public String getMessage() + { + return message; + } + + public void setMessage(String message) + { + this.message = message; + } + + public String getSmtpHost() + { + return smtpHost; + } + + public void setSmtpHost(String smtpHost) + { + this.smtpHost = smtpHost; + } + + /** + * 具有发送的行为 + */ + public void sendMessage(){ + MailUtil.sendEmail(this.toAddress, + ConfigurationKeys.EMAIL_ADMIN, + this.subject, + this.message, + ConfigurationKeys.ALT_SMTP_SERVER, + true); + } + + /** + * 备用发送 + */ + public void standbySendMessage(){ + MailUtil.sendEmail(this.toAddress, + ConfigurationKeys.EMAIL_ADMIN, + this.subject, + this.message, + ConfigurationKeys.SMTP_SERVER, + true); + } + +} diff --git a/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/bean/Person.java b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/bean/Person.java new file mode 100644 index 0000000000..942b246154 --- /dev/null +++ b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/bean/Person.java @@ -0,0 +1,43 @@ +package com.coderising.ood.srp.bean; + +/** + * Created with IDEA + * Created by fuyi.ren on 2017/6/17 15:21 + * Description: + */ +public class Person +{ + private Long id; + private String name; + private String email; + + public Long getId() + { + return id; + } + + public void setId(Long id) + { + this.id = id; + } + + public String getName() + { + return name; + } + + public void setName(String name) + { + this.name = name; + } + + public String getEmail() + { + return email; + } + + public void setEmail(String email) + { + this.email = email; + } +} diff --git a/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/bean/Product.java b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/bean/Product.java new file mode 100644 index 0000000000..1fe6c40ef7 --- /dev/null +++ b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/bean/Product.java @@ -0,0 +1,43 @@ +package com.coderising.ood.srp.bean; + +/** + * Created with IDEA + * Created by fuyi.ren on 2017/6/17 11:19 + * Description: 产品实体 + */ +public class Product +{ + private String productID ; + private String productDesc; + + public Product() + { + } + + public Product(String productID, String productDesc) + { + this.productID = productID; + this.productDesc = productDesc; + } + + public String getProductID() + { + return productID; + } + + public void setProductID(String productID) + { + this.productID = productID; + } + + public String getProductDesc() + { + return productDesc; + } + + public void setProductDesc(String productDesc) + { + this.productDesc = productDesc; + } + +} diff --git a/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/dao/PromotionMailDao.java b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/dao/PromotionMailDao.java new file mode 100644 index 0000000000..8b79dfac51 --- /dev/null +++ b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/dao/PromotionMailDao.java @@ -0,0 +1,22 @@ +package com.coderising.ood.srp.dao; + +import java.util.List; + +/** + * Created with IDEA + * Created by fuyi.ren on 2017/6/17 14:07 + * Description: + */ +public interface PromotionMailDao +{ + + /** + * 从数据库中读取信息,人员信息 + */ + public List loadMailingList() throws Exception; + + + + +} + diff --git a/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/dao/PromotionMailDaoImpl.java b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/dao/PromotionMailDaoImpl.java new file mode 100644 index 0000000000..a730c3c188 --- /dev/null +++ b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/dao/PromotionMailDaoImpl.java @@ -0,0 +1,29 @@ +package com.coderising.ood.srp.dao; + +import com.coderising.ood.srp.bean.Person; +import com.coderising.ood.srp.utils.DBUtil; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * Created with IDEA + * Created by fuyi.ren on 2017/6/17 14:48 + * Description: + */ +public class PromotionMailDaoImpl implements PromotionMailDao +{ + public List loadMailingList() throws Exception + { + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + Person person=new Person(); + person.setId(Long.valueOf(i)); + person.setName("User" + i); + person.setEmail("aa@bb.com"); + userList.add(person); + } + return userList; + } +} diff --git a/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/main/PromotionMail.java b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/main/PromotionMail.java new file mode 100644 index 0000000000..e946ece828 --- /dev/null +++ b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/main/PromotionMail.java @@ -0,0 +1,55 @@ +package com.coderising.ood.srp.main; + +import com.coderising.ood.srp.bean.Email; +import com.coderising.ood.srp.bean.Person; +import com.coderising.ood.srp.bean.Product; +import com.coderising.ood.srp.resource.ConfigurationKeys; +import com.coderising.ood.srp.service.PromotionMailService; +import com.coderising.ood.srp.service.PromotionMailServiceImpl; + +import javax.xml.ws.Service; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail +{ + + public static PromotionMailService mailService = new PromotionMailServiceImpl(); + public static void main(String[] args) throws Exception + { + + String src = mailService.getClass().getResource("../resource") + "/product_promotion.txt"; + List productList = mailService.readFile(src); + List personList = mailService.querySendPerons(); + + List emailList=getEmailList(productList,personList); + + mailService.sendMessage(emailList); + } + + private static List getEmailList( List productList, List personList) throws Exception + { + List emailList=new ArrayList(); + for (Person person : personList) + { + for (Product product : productList) + { + Email email = new Email(); + String message=mailService.jointMessage(person, product); + email.setToAddress(person.getEmail()); + email.setMessage(message); + emailList.add(email); + } + } + return emailList; + } + + +} \ No newline at end of file diff --git a/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/resource/ConfigurationKeys.java b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/resource/ConfigurationKeys.java new file mode 100644 index 0000000000..c6fac0201c --- /dev/null +++ b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/resource/ConfigurationKeys.java @@ -0,0 +1,10 @@ +package com.coderising.ood.srp.resource; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + + public static final String EMAIL_ADMIN = "email.admin"; +} diff --git a/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/resource/product_promotion.txt b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/resource/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/resource/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/service/PromotionMailService.java b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/service/PromotionMailService.java new file mode 100644 index 0000000000..f520e17439 --- /dev/null +++ b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/service/PromotionMailService.java @@ -0,0 +1,30 @@ +package com.coderising.ood.srp.service; + +import com.coderising.ood.srp.bean.Email; +import com.coderising.ood.srp.bean.Person; +import com.coderising.ood.srp.bean.Product; + +import java.io.IOException; +import java.util.List; + + +public interface PromotionMailService +{ + + + + + + + + public List readFile(String src) throws IOException; + + + + public List querySendPerons() throws Exception; + + + public String jointMessage(Person person, Product product)throws Exception; + + public void sendMessage(List emailList) throws IOException; +} diff --git a/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/service/PromotionMailServiceImpl.java b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/service/PromotionMailServiceImpl.java new file mode 100644 index 0000000000..ed57cb2e90 --- /dev/null +++ b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/service/PromotionMailServiceImpl.java @@ -0,0 +1,67 @@ +package com.coderising.ood.srp.service; + +import com.coderising.ood.srp.bean.Email; +import com.coderising.ood.srp.bean.Person; +import com.coderising.ood.srp.bean.Product; +import com.coderising.ood.srp.dao.PromotionMailDao; +import com.coderising.ood.srp.dao.PromotionMailDaoImpl; +import com.coderising.ood.srp.utils.FileUtil; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +/** + * Created with IDEA + * Created by fuyi.ren on 2017/6/17 15:04 + * Description: + */ +public class PromotionMailServiceImpl implements PromotionMailService +{ + private static PromotionMailDao promotionMailDao=new PromotionMailDaoImpl(); + private List persons; + private List products; + + + + public void sendMessage(List emailList) throws IOException + { + for (Email email:emailList){ + try + { + email.sendMessage(); + }catch (Exception e){ + + try { + email.standbySendMessage(); + } catch (Exception e2){ + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + + } + } + } + + + public List readFile(String src) throws IOException + { + File file=new File(src); + return FileUtil.readFile(file); // 获得 产品 + } + + public List querySendPerons() throws Exception + { + return promotionMailDao.loadMailingList(); //获得人员 + } + + + public String jointMessage(Person person, Product product) + { + StringBuffer message=new StringBuffer(); + String personName=person.getName(); + String productDesc=product.getProductDesc(); + message.append("您关注的产品降价了").append(" 尊敬的 ").append(personName) + .append(" 您关注的产品").append(productDesc).append("降价了,欢迎购买!"); + return message.toString(); + } +} diff --git a/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/utils/DBUtil.java b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/utils/DBUtil.java new file mode 100644 index 0000000000..2449bf2029 --- /dev/null +++ b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/utils/DBUtil.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp.utils; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + return userList; + } +} diff --git a/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/utils/FileUtil.java b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/utils/FileUtil.java new file mode 100644 index 0000000000..9ee29078b8 --- /dev/null +++ b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/utils/FileUtil.java @@ -0,0 +1,55 @@ +package com.coderising.ood.srp.utils; + +import com.coderising.ood.srp.bean.Product; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Created with IDEA + * Created by fuyi.ren on 2017/6/17 11:08 + * Description: + */ +public class FileUtil +{ + + /** + * 读取文件内容,返回List + * @param file + * @return + * @throws IOException + */ + public static List readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + List list = null; + try + { + br = new BufferedReader(new FileReader(file)); + String line = null; + Product product = null; + list = new ArrayList(); + while ((line = br.readLine()) != null) + { + String[] data = line.split(" "); + product = new Product(); + product.setProductID(data[0]); + product.setProductDesc(data[1]); + + list.add(product); + } + return list; + } catch (IOException e) + { + throw new IOException(e.getMessage()); + } finally + { + br.close(); + } + } + +} diff --git a/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/utils/MailUtil.java b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/utils/MailUtil.java new file mode 100644 index 0000000000..557234d95c --- /dev/null +++ b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/utils/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp.utils; + +public class MailUtil { + + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + } + + + +} diff --git a/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/utils/PropertiesUtil.java b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/utils/PropertiesUtil.java new file mode 100644 index 0000000000..3c1226ffbb --- /dev/null +++ b/students/605159467/ood-assignment/src/main/java/com/coderising/ood/srp/utils/PropertiesUtil.java @@ -0,0 +1,79 @@ +package com.coderising.ood.srp.utils; + +import org.junit.Test; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URI; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +/** + * Created with IDEA + * Created by fuyi.ren on 2017/6/17 16:27 + * Description: + */ +public class PropertiesUtil +{ + private Properties props; + private URI uri; + + public PropertiesUtil(String fileName){ + readProperties(fileName); + } + private void readProperties(String fileName) { + try { + props = new Properties(); + InputStream fis =getClass().getResourceAsStream(fileName); + props.load(fis); + uri = this.getClass().getResource("/dbConfig.properties").toURI(); + } catch (Exception e) { + e.printStackTrace(); + } + } + /** + * 获取某个属性 + */ + public String getProperty(String key){ + return props.getProperty(key); + } + /** + * 获取所有属性,返回一个map,不常用 + * 可以试试props.putAll(t) + */ + public Map getAllProperty(){ + Map map=new HashMap(); + Enumeration enu = props.propertyNames(); + while (enu.hasMoreElements()) { + String key = (String) enu.nextElement(); + String value = props.getProperty(key); + map.put(key, value); + } + return map; + } + /** + * 在控制台上打印出所有属性,调试时用。 + */ + public void printProperties(){ + props.list(System.out); + } + /** + * 写入properties信息 + */ + public void writeProperties(String key, String value) { + try { + OutputStream fos = new FileOutputStream(new File(uri)); + props.setProperty(key, value); + // 将此 Properties 表中的属性列表(键和元素对)写入输出流 + props.store(fos, "『comments』Update key:" + key); + } catch (Exception e) { + e.printStackTrace(); + } + } + + +} diff --git a/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/client/Client.java b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/client/Client.java new file mode 100644 index 0000000000..90785c61a6 --- /dev/null +++ b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/client/Client.java @@ -0,0 +1,16 @@ +package edu.coerscnu.ood.ocp.client; + +import edu.coerscnu.ood.ocp.logger.Logger; +import edu.coerscnu.ood.ocp.logger.method.Mail; +import edu.coerscnu.ood.ocp.logger.method.LogMethod; +import edu.coerscnu.ood.ocp.logger.type.RawWithDate; +import edu.coerscnu.ood.ocp.logger.type.LogType; + +public class Client { + public static void main(String[] args) { + LogType type = new RawWithDate(); + LogMethod method = new Mail(); + Logger logger = new Logger(type, method); + logger.log("Hello World"); + } +} diff --git a/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/Logger.java b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/Logger.java new file mode 100644 index 0000000000..6db868df96 --- /dev/null +++ b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/Logger.java @@ -0,0 +1,21 @@ +package edu.coerscnu.ood.ocp.logger; + +import edu.coerscnu.ood.ocp.logger.method.LogMethod; +import edu.coerscnu.ood.ocp.logger.type.LogType; + +public class Logger { + + public LogType logType; // 日志类型 + public LogMethod logMethod; // 日志方法 + + public Logger(LogType logType, LogMethod logMethod) { + this.logType = logType; + this.logMethod = logMethod; + } + + public void log(String msg) { + String logMsg = msg; + logMsg = logMsg + logType.getMsg(); + logMethod.send(logMsg); + } +} diff --git a/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/method/LogMethod.java b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/method/LogMethod.java new file mode 100644 index 0000000000..13f1e66a6a --- /dev/null +++ b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/method/LogMethod.java @@ -0,0 +1,10 @@ +package edu.coerscnu.ood.ocp.logger.method; + +/** + * 日志方法接口 + * @author xujie + * + */ +public interface LogMethod { + public void send(String logMsg); +} diff --git a/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/method/Mail.java b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/method/Mail.java new file mode 100644 index 0000000000..1468ef48f2 --- /dev/null +++ b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/method/Mail.java @@ -0,0 +1,10 @@ +package edu.coerscnu.ood.ocp.logger.method; + +public class Mail implements LogMethod{ + + @Override + public void send(String logMsg) { + System.out.println("Mail:" + logMsg); + } + +} diff --git a/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/method/Print.java b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/method/Print.java new file mode 100644 index 0000000000..d8c7e08062 --- /dev/null +++ b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/method/Print.java @@ -0,0 +1,9 @@ +package edu.coerscnu.ood.ocp.logger.method; + +public class Print implements LogMethod { + + @Override + public void send(String logMsg) { + System.out.println("Print:" + logMsg); + } +} diff --git a/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/method/Sms.java b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/method/Sms.java new file mode 100644 index 0000000000..8efc05ea7e --- /dev/null +++ b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/method/Sms.java @@ -0,0 +1,10 @@ +package edu.coerscnu.ood.ocp.logger.method; + +public class Sms implements LogMethod{ + + @Override + public void send(String logMsg) { + System.err.println("Sms:" + logMsg); + } + +} diff --git a/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/type/LogType.java b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/type/LogType.java new file mode 100644 index 0000000000..99443d1a97 --- /dev/null +++ b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/type/LogType.java @@ -0,0 +1,11 @@ +package edu.coerscnu.ood.ocp.logger.type; + +/** + * 日志类型接口 + * + * @author xujie + * + */ +public interface LogType { + public String getMsg(); +} diff --git a/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/type/Raw.java b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/type/Raw.java new file mode 100644 index 0000000000..2053abd462 --- /dev/null +++ b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/type/Raw.java @@ -0,0 +1,10 @@ +package edu.coerscnu.ood.ocp.logger.type; + +public class Raw implements LogType{ + + @Override + public String getMsg() { + return ""; + } + +} diff --git a/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/type/RawWithDate.java b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/type/RawWithDate.java new file mode 100644 index 0000000000..3c15b93dfb --- /dev/null +++ b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/logger/type/RawWithDate.java @@ -0,0 +1,12 @@ +package edu.coerscnu.ood.ocp.logger.type; + +import edu.coerscnu.ood.ocp.utils.DateUtil; + +public class RawWithDate implements LogType{ + + @Override + public String getMsg() { + return " " + DateUtil.getCurrentDate(); + } + +} diff --git a/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/utils/DateUtil.java b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/utils/DateUtil.java new file mode 100644 index 0000000000..1cfec691e3 --- /dev/null +++ b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/ocp/utils/DateUtil.java @@ -0,0 +1,16 @@ +package edu.coerscnu.ood.ocp.utils; + +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * 获取当前时间 + * @author xujie + * + */ +public class DateUtil { + public static String getCurrentDate() { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + return sdf.format(new Date()); + } +} diff --git a/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/Configuration.java b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/Configuration.java new file mode 100644 index 0000000000..b6a82c425f --- /dev/null +++ b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/Configuration.java @@ -0,0 +1,25 @@ +package edu.coerscnu.ood.srp; + +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static { + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + configurations.put(ConfigurationKeys.IS_DEBUG, true); + } + + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * + * @param key + * @return + */ + public Object getProperty(String key) { + return configurations.get(key); + } +} diff --git a/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/ConfigurationKeys.java b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..b7cecc897b --- /dev/null +++ b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package edu.coerscnu.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + public static final String IS_DEBUG = "debug"; +} diff --git a/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/DBUtil.java b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/DBUtil.java new file mode 100644 index 0000000000..6632d110fa --- /dev/null +++ b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/DBUtil.java @@ -0,0 +1,26 @@ +package edu.coerscnu.ood.srp; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 获取用户列表,应该从数据库读, 但是简化为直接生成。 + * + * @param sql + * @return + */ + public static List> query(String sql) { + + List> userList = new ArrayList>(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put(UserService.NAME_KEY, "User" + i); + userInfo.put(UserService.MAIL_KEY, i + "aa@bb.com"); + userList.add(userInfo); + } + return userList; + } +} diff --git a/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/FileUtil.java b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/FileUtil.java new file mode 100644 index 0000000000..fd474c2da2 --- /dev/null +++ b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/FileUtil.java @@ -0,0 +1,37 @@ +package edu.coerscnu.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * FileUtil类负责读取.txt文件内容,并以List(产品id,产品描述)形式返回。 + * + * @author xujie + * + */ +public class FileUtil { + + public static List readFile(String path) throws IOException { + BufferedReader br = null; + List list = new ArrayList<>(); + try { + File file = new File(path); + FileReader fr = new FileReader(file); + br = new BufferedReader(fr); + String temp; + while ((temp = br.readLine()) != null) { + String[] data = temp.split(" "); + list.add(data); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + br.close(); + } + return list; + } +} diff --git a/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/MailUtil.java b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/MailUtil.java new file mode 100644 index 0000000000..1dd007b3d5 --- /dev/null +++ b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/MailUtil.java @@ -0,0 +1,73 @@ +package edu.coerscnu.ood.srp; + +/** + * 邮件公共类 1、配置服务器 2、发送邮件 + * + * @author xujie + * + */ +public class MailUtil { + + private static String smtpHost; // 主服务器 + private static String altSmtpHost; // 备用服务器 + private static String fromAddress; // 发件人 + private static boolean isDebug; // 是否为调试环境 + + /** + * 配置服务器 + */ + public static void configureHost() { + Configuration config = new Configuration(); + smtpHost = (String) config.getProperty(ConfigurationKeys.SMTP_SERVER); + altSmtpHost = (String) config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + fromAddress = (String) config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + isDebug = (boolean) config.getProperty(ConfigurationKeys.IS_DEBUG); + } + + /** + * 发送邮件,对外不可见 + * + * @param toAddress + * @param fromAddress + * @param subject + * @param message + * @param smtpHost + * @param debug + */ + private static void sendMail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + // 假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + } + + /** + * 发送邮件,对外可见 + * + * @param toAddress + * @param subject + * @param message + */ + public static void sendMail(String toAddress, String subject, String message) { + configureHost(); + if (isDebug) { + System.out.println("调试环境"); + } else { + System.out.println("正式环境"); + } + if (smtpHost != null) { + System.out.println("使用主服务器发送邮件"); + sendMail(toAddress, fromAddress, subject, message, smtpHost, isDebug); + } else if (altSmtpHost != null) { + System.out.println("使用备用服务器发送邮件"); + sendMail(toAddress, fromAddress, subject, message, altSmtpHost, isDebug); + } else { + System.out.println("服务器异常,无法发送邮件"); + } + + } +} diff --git a/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/Product.java b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/Product.java new file mode 100644 index 0000000000..64cbcc6d0c --- /dev/null +++ b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/Product.java @@ -0,0 +1,33 @@ +package edu.coerscnu.ood.srp; + +/** + * 产品类,包含id和描述两个属性 + * + * @author xujie + * + */ +public class Product { + protected String productID = null; + protected String productDesc = null; + + public Product(String id, String desc) { + productID = id; + productDesc = desc; + } + + public void setProductID(String id) { + productID = id; + } + + public void setProductDesc(String desc) { + productDesc = desc; + } + + public String getProductID() { + return productID; + } + + public String getProductDesc() { + return productDesc; + } +} diff --git a/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/PromotionMail.java b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..5a77a24067 --- /dev/null +++ b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/PromotionMail.java @@ -0,0 +1,97 @@ +package edu.coerscnu.ood.srp; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +/** + * 促销邮件类 + * + * 1、设置邮件主题 + * + * 2、设置邮件正文 + * + * 3、设置邮件收件人列表 + * + * 4、发送邮件 + * + * @author xujie + * + */ +public class PromotionMail { + + protected String subject = null; + protected String message = null; + protected List> mailList; + + public static void main(String[] args) throws Exception { + + // 降价产品文件路径 + String path = "src/edu/coerscnu/ood/srp/product_promotion.txt"; + // 获得降价产品列表 + List productList = FileUtil.readFile(path); + // 对于每个降价产品,挨个向关注该产品的用户发送邮件 + for (String[] prod : productList) { + Product product = new Product(prod[0], prod[1]); + PromotionMail pm = new PromotionMail(); + pm.setMailList(product); + pm.sendMails(product); + } + } + + /** + * 设置邮件主题 + * + * @param subject + */ + public void setSubject(String subject) { + this.subject = subject; + } + + /** + * 设置邮件正文 + * + * @param userInfo + * @param product + * @throws IOException + */ + protected void setMessage(HashMap userInfo, Product product) throws IOException { + String name = (String) userInfo.get(UserService.NAME_KEY); + String desc = product.getProductDesc(); + message = "尊敬的 " + name + ", 您关注的产品 " + desc + " 降价了,欢迎购买!"; + } + + /** + * 设置收件人列表 + * + * @param product + * @throws Exception + */ + protected void setMailList(Product product) throws Exception { + UserService userService = new UserService(); + userService.setLoadQuery(product); + mailList = userService.loadMailingList(); + } + + /** + * 发送邮件 + * + * @throws IOException + */ + protected void sendMails(Product product) throws IOException { + if (mailList != null) { + Iterator> iter = mailList.iterator(); + while (iter.hasNext()) { + HashMap user = iter.next(); + String toAddress = (String) user.get(UserService.MAIL_KEY); + // 用户邮箱地址有效则设置邮件主题和正文,并发送 + if (toAddress.length() > 0) { + setSubject("您关注的产品降价了"); + setMessage(user, product); + MailUtil.sendMail(toAddress, subject, message); + } + } + } + } +} diff --git a/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/UserService.java b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/UserService.java new file mode 100644 index 0000000000..af04bf5709 --- /dev/null +++ b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/UserService.java @@ -0,0 +1,28 @@ +package edu.coerscnu.ood.srp; + +import java.util.HashMap; +import java.util.List; + +/** + * 用户类,获取关注降价产品的客户的名字和邮箱地址 + * + * @author xujie + * + */ +public class UserService { + + protected static final String NAME_KEY = "NAME"; + protected static final String MAIL_KEY = "EMAIL"; + + protected String query = ""; + + protected void setLoadQuery(Product product) { + query = "Select name from subscriptions " + "where product_id= '" + product.getProductID() + "' " + + "and send_mail=1 "; + System.out.println("loadQuery set\n"); + } + + protected List> loadMailingList() throws Exception { + return DBUtil.query(query); + } +} diff --git a/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/product_promotion.txt b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/617314917/ood/ood-assignment/assignment01/src/edu/coerscnu/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/617314917/readme.md b/students/617314917/readme.md new file mode 100644 index 0000000000..d620ba5b0a --- /dev/null +++ b/students/617314917/readme.md @@ -0,0 +1 @@ +这是“广州-许洁”提交代码的qq命名文件夹。 \ No newline at end of file diff --git a/students/63072784/README.md b/students/63072784/README.md new file mode 100644 index 0000000000..f5e57e7b78 --- /dev/null +++ b/students/63072784/README.md @@ -0,0 +1 @@ +这是我的目录 diff --git a/students/63072784/pom.xml b/students/63072784/pom.xml new file mode 100644 index 0000000000..4c78ba51ac --- /dev/null +++ b/students/63072784/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + + com.jimmykwong + coding2017 + 1.0-SNAPSHOT + + + 1.8 + 1.8 + + + \ No newline at end of file diff --git a/students/63072784/src/main/java/ood/srp/Configuration.java b/students/63072784/src/main/java/ood/srp/Configuration.java new file mode 100644 index 0000000000..eb315dd7e3 --- /dev/null +++ b/students/63072784/src/main/java/ood/srp/Configuration.java @@ -0,0 +1,29 @@ +package ood.srp; + +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + + static { + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN_PASSWORD, "admin!"); + configurations.put(ConfigurationKeys.EMAIL_PORT, "25"); + } + + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/63072784/src/main/java/ood/srp/ConfigurationKeys.java b/students/63072784/src/main/java/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..168ee4a304 --- /dev/null +++ b/students/63072784/src/main/java/ood/srp/ConfigurationKeys.java @@ -0,0 +1,11 @@ +package ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + public static final String EMAIL_PORT = "email.port"; + public static final String EMAIL_ADMIN_PASSWORD = "email.admin.password"; + +} diff --git a/students/63072784/src/main/java/ood/srp/DBUtil.java b/students/63072784/src/main/java/ood/srp/DBUtil.java new file mode 100644 index 0000000000..86c9ab9102 --- /dev/null +++ b/students/63072784/src/main/java/ood/srp/DBUtil.java @@ -0,0 +1,23 @@ +package ood.srp; + +import java.util.ArrayList; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * + * @param sql + * @return + */ + public static List query(String sql) { + System.out.printf("执行sql=" + sql); + List userList = new ArrayList<>(); + for (int i = 1; i <= 3; i++) { + UserInfo userInfo = new UserInfo("User" + i, "aa@bb.com"); + userList.add(userInfo); + } + return userList; + } +} diff --git a/students/63072784/src/main/java/ood/srp/Mail.java b/students/63072784/src/main/java/ood/srp/Mail.java new file mode 100644 index 0000000000..db08647d9a --- /dev/null +++ b/students/63072784/src/main/java/ood/srp/Mail.java @@ -0,0 +1,50 @@ +package ood.srp; + +/** + * Created by jimmy on 6/20/2017. + */ +public class Mail { + private MailAccount mailAccount; + private String toAddress; + private String subject; + private String message; + + public Mail(MailAccount mailAccount, String toAddress, String subject, String message) { + this.mailAccount = mailAccount; + this.toAddress = toAddress; + this.subject = subject; + this.message = message; + } + + public MailAccount getMailAccount() { + return mailAccount; + } + + public void setMailAccount(MailAccount mailAccount) { + this.mailAccount = mailAccount; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/students/63072784/src/main/java/ood/srp/MailAccount.java b/students/63072784/src/main/java/ood/srp/MailAccount.java new file mode 100644 index 0000000000..f0aaf3ee49 --- /dev/null +++ b/students/63072784/src/main/java/ood/srp/MailAccount.java @@ -0,0 +1,42 @@ +package ood.srp; + +/** + * Created by jimmy on 6/20/2017. + */ +public class MailAccount { + private String smtpHost; + private String altSmtpHost; + private int port; + private String account; + private String password; + + public static MailAccount buildAccount(Configuration config) { + MailAccount mailAccount = new MailAccount(); + mailAccount.smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + mailAccount.altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + mailAccount.port = Integer.parseInt(config.getProperty(ConfigurationKeys.EMAIL_PORT)); + mailAccount.account = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + mailAccount.password = config.getProperty(ConfigurationKeys.EMAIL_ADMIN_PASSWORD); + return mailAccount; + } + + public String getSmtpHost() { + return smtpHost; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public int getPort() { + return port; + } + + public String getAccount() { + return account; + } + + public String getPassword() { + return password; + } +} diff --git a/students/63072784/src/main/java/ood/srp/MailUtil.java b/students/63072784/src/main/java/ood/srp/MailUtil.java new file mode 100644 index 0000000000..0e4d135252 --- /dev/null +++ b/students/63072784/src/main/java/ood/srp/MailUtil.java @@ -0,0 +1,35 @@ +package ood.srp; + +public class MailUtil { + + public static void sendEmail(Mail mail, boolean debug) { + String toAddress = mail.getToAddress(); + String fromAddress = mail.getMailAccount().getAccount(); + String subject = mail.getSubject(); + String message = mail.getMessage(); + String smtpHost = mail.getMailAccount().getSmtpHost(); + String altSmtpHost = mail.getMailAccount().getAltSmtpHost(); + try { + sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } catch (Exception e) { + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + + } + + private static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + } +} diff --git a/students/63072784/src/main/java/ood/srp/Product.java b/students/63072784/src/main/java/ood/srp/Product.java new file mode 100644 index 0000000000..3e6b36b671 --- /dev/null +++ b/students/63072784/src/main/java/ood/srp/Product.java @@ -0,0 +1,54 @@ +package ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +/** + * Created by jimmy on 6/20/2017. + */ +public class Product { + private String productId; + private String productDesc; + + public static Product getPromotionProduct(File file) throws Exception { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + String productId = data[0]; + String productDesc = data[1]; + + System.out.println("产品ID = " + productId + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + Product product = new Product(); + product.productId = productId; + product.productDesc = productDesc; + return product; + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + public String getProductId() { + return productId; + } + + public void setProductId(String productId) { + this.productId = productId; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git a/students/63072784/src/main/java/ood/srp/PromotionMail.java b/students/63072784/src/main/java/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..f6646fac14 --- /dev/null +++ b/students/63072784/src/main/java/ood/srp/PromotionMail.java @@ -0,0 +1,64 @@ +package ood.srp; + +import java.io.File; +import java.util.List; + +public class PromotionMail { + + + private static final String SUBJECT = "您关注的商品降价了"; + + public static void main(String[] args) throws Exception { + //这里可以做成参数输入 + File f = new File(PromotionMail.class.getClassLoader().getResource("product_promotion.txt").toURI()); + boolean debug = true; + PromotionMail pe = new PromotionMail(); + pe.sendEMails(f, debug); + } + + + public PromotionMail() { + } + + private String buildMessage(UserInfo userInfo, Product product) { + return String.format("尊敬的 %s, 您关注的产品 %s 降价了,欢迎购买!", userInfo.getName(), product.getProductDesc()); + } + + private Mail buildMail(MailAccount mailAccount, UserInfo userInfo, Product product) { + //可以更加详细的检查 + if (mailAccount == null || userInfo == null || product == null) { + return null; + } else { + String message = buildMessage(userInfo, product); + return new Mail(mailAccount, userInfo.getEmailAddress(), SUBJECT, message); + } + } + + + private void sendEMails(File file, boolean debug) throws Exception { + + //构建发送邮件账号 + MailAccount mailAccount = MailAccount.buildAccount(new Configuration()); + + //读取降价列表 + Product product = Product.getPromotionProduct(file); + + //获取订阅用户列表 + List userInfoList = UserInfo.getUserInfo(product.getProductId()); + + System.out.println("开始发送邮件"); + + if (userInfoList != null) { + for (UserInfo userInfo : userInfoList) { + Mail mail = buildMail(mailAccount, userInfo, product); + if (mail == null) { + continue; + } + MailUtil.sendEmail(mail, debug); + } + } else { + System.out.println("没有邮件发送"); + + } + } +} diff --git a/students/63072784/src/main/java/ood/srp/UserInfo.java b/students/63072784/src/main/java/ood/srp/UserInfo.java new file mode 100644 index 0000000000..3387dcb1bc --- /dev/null +++ b/students/63072784/src/main/java/ood/srp/UserInfo.java @@ -0,0 +1,41 @@ +package ood.srp; + +import java.util.List; + +/** + * Created by jimmy on 6/20/2017. + */ +public class UserInfo { + private String name; + private String emailAddress; + + public UserInfo(String name, String emailAddress) { + this.name = name; + this.emailAddress = emailAddress; + } + + private static final String QUERY_PRODUCT = "Select name from subscriptions " + + "where product_id= '%s' " + + "and send_mail=1 "; + + public static List getUserInfo(String productId) { + System.out.println("loadQuery set"); + return DBUtil.query(String.format(QUERY_PRODUCT, productId)); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmailAddress() { + return emailAddress; + } + + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } +} diff --git a/students/63072784/src/main/resources/product_promotion.txt b/students/63072784/src/main/resources/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/63072784/src/main/resources/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/641013587/ood/ood-assignment/pom.xml b/students/641013587/ood/ood-assignment/pom.xml new file mode 100644 index 0000000000..65607712c0 --- /dev/null +++ b/students/641013587/ood/ood-assignment/pom.xml @@ -0,0 +1,47 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.2 + + 1.7 + 1.7 + UTF-8 + + + + + diff --git a/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/constant/CommonConstant.java b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/constant/CommonConstant.java new file mode 100644 index 0000000000..fcba3fc9c2 --- /dev/null +++ b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/constant/CommonConstant.java @@ -0,0 +1,14 @@ +package com.coderising.ood.srp.constant; + +import com.coderising.ood.srp.entity.Product; +import com.coderising.ood.srp.entity.User; + +public class CommonConstant { + + public static final String SUBJECT = "您关注的产品降价了"; + + public static String getProductMessage(User user,Product product){ + return "尊敬的 "+user.getName()+", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!"; + } + +} diff --git a/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dao/UserDao.java b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dao/UserDao.java new file mode 100644 index 0000000000..6b3d11c41b --- /dev/null +++ b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dao/UserDao.java @@ -0,0 +1,26 @@ +package com.coderising.ood.srp.dao; +import java.util.ArrayList; +import java.util.List; + +import com.coderising.ood.srp.entity.User; + +public class UserDao { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public List query(String sql){ + + List userList = new ArrayList<>(); + for (int i = 1; i <= 3; i++) { + User userInfo = new User(); + userInfo.setName("User" + i); + userInfo.setEmail("aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/entity/Msg.java b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/entity/Msg.java new file mode 100644 index 0000000000..8b1bc8b132 --- /dev/null +++ b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/entity/Msg.java @@ -0,0 +1,50 @@ +package com.coderising.ood.srp.entity; + +public class Msg { + + private String smtpHost ; + private String altSmtpHost; + private String fromAddress; + private String toAddress; + private String subject ; + private String message ; + public String getSmtpHost() { + return smtpHost; + } + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + public String getAltSmtpHost() { + return altSmtpHost; + } + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + public String getFromAddress() { + return fromAddress; + } + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + public String getToAddress() { + return toAddress; + } + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + public String getSubject() { + return subject; + } + public void setSubject(String subject) { + this.subject = subject; + } + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + + +} diff --git a/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/entity/Product.java b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/entity/Product.java new file mode 100644 index 0000000000..a721930d75 --- /dev/null +++ b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/entity/Product.java @@ -0,0 +1,21 @@ +package com.coderising.ood.srp.entity; + +public class Product { + private String productID; + private String productDesc; + public String getProductID() { + return productID; + } + public void setProductID(String productID) { + this.productID = productID; + } + public String getProductDesc() { + return productDesc; + } + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + + + +} diff --git a/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/entity/User.java b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/entity/User.java new file mode 100644 index 0000000000..78f83b38a1 --- /dev/null +++ b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/entity/User.java @@ -0,0 +1,20 @@ +package com.coderising.ood.srp.entity; + +public class User { + private String name; + private String email; + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + +} diff --git a/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/main/PromotionMail.java b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/main/PromotionMail.java new file mode 100644 index 0000000000..217a42ceb1 --- /dev/null +++ b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/main/PromotionMail.java @@ -0,0 +1,31 @@ +package com.coderising.ood.srp.main; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import com.coderising.ood.srp.dao.UserDao; +import com.coderising.ood.srp.entity.Product; +import com.coderising.ood.srp.entity.User; +import com.coderising.ood.srp.service.EmailService; +import com.coderising.ood.srp.service.UserService; +import com.coderising.ood.srp.util.FileUtil; +import com.coderising.ood.srp.util.MailUtil; +import com.coderising.ood.srp.util.PropertiesUtil; + +public class PromotionMail { + + public static void main(String[] args) throws Exception { + EmailService emailService = new EmailService(); + UserService userService = new UserService(); + Product product = FileUtil.readRecommendProduct(); + List subscribeUsers = userService.getSubscribeUsers(product); + emailService.sendEMails(false, subscribeUsers, product); + + } + +} diff --git a/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/service/EmailService.java b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/service/EmailService.java new file mode 100644 index 0000000000..0bd0841517 --- /dev/null +++ b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/service/EmailService.java @@ -0,0 +1,49 @@ +package com.coderising.ood.srp.service; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import com.coderising.ood.srp.constant.CommonConstant; +import com.coderising.ood.srp.entity.Msg; +import com.coderising.ood.srp.entity.Product; +import com.coderising.ood.srp.entity.User; +import com.coderising.ood.srp.util.MailUtil; +import com.coderising.ood.srp.util.PropertiesUtil; + +public class EmailService { + + public boolean sendEMails(boolean debug, List mailingList, Product product) throws IOException + { + + System.out.println("开始发送邮件"); + Msg basemsg = PropertiesUtil.BASEMSG; + for (User user : mailingList) { + try + { + basemsg.setToAddress(user.getEmail()); + basemsg.setSubject(CommonConstant.SUBJECT); + basemsg.setMessage(CommonConstant.getProductMessage(user, product)); + if (basemsg.getToAddress().length() > 0) + MailUtil.sendEmail(debug,basemsg); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(debug,basemsg); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + return false; + } + + } + return true; + + } + +} diff --git a/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/service/UserService.java b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/service/UserService.java new file mode 100644 index 0000000000..214442bdcd --- /dev/null +++ b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/service/UserService.java @@ -0,0 +1,17 @@ +package com.coderising.ood.srp.service; + +import java.util.List; + +import com.coderising.ood.srp.dao.UserDao; +import com.coderising.ood.srp.entity.Product; +import com.coderising.ood.srp.entity.User; + +public class UserService { + + private UserDao userDao= new UserDao(); + + public List getSubscribeUsers(Product product){ + return userDao.query("Select name from subscriptions where product_id= '" + product.getProductID() +"' and send_mail=1"); + } + +} diff --git a/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/FileUtil.java b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/FileUtil.java new file mode 100644 index 0000000000..4f2908a2c6 --- /dev/null +++ b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/FileUtil.java @@ -0,0 +1,32 @@ +package com.coderising.ood.srp.util; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +import com.coderising.ood.srp.entity.Product; + +public class FileUtil { + + public static final String FILE_URL="C:\\Users\\Administrator\\git\\coding2017\\students\\641013587\\ood\\ood-assignment\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"; + + public static Product readRecommendProduct() throws IOException{ + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(FILE_URL)); + String temp = br.readLine(); + String[] data = temp.split(" "); + Product product = new Product(); + product.setProductID(data[0]); + product.setProductDesc(data[1]); + System.out.println("产品ID = " + product.getProductID() + "\n"); + System.out.println("产品描述 = " + product.getProductDesc() + "\n"); + return product; + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + +} diff --git a/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java new file mode 100644 index 0000000000..4387e6e73b --- /dev/null +++ b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java @@ -0,0 +1,20 @@ +package com.coderising.ood.srp.util; + +import com.coderising.ood.srp.entity.Msg; + +public class MailUtil { + + public static void sendEmail( + boolean debug,Msg msg) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(msg.getFromAddress()).append("\n"); + buffer.append("To:").append(msg.getToAddress()).append("\n"); + buffer.append("Subject:").append(msg.getSubject()).append("\n"); + buffer.append("Content:").append(msg.getMessage()).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/PropertiesUtil.java b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/PropertiesUtil.java new file mode 100644 index 0000000000..7033920b35 --- /dev/null +++ b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/PropertiesUtil.java @@ -0,0 +1,39 @@ +package com.coderising.ood.srp.util; + +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Properties; + +import com.coderising.ood.srp.entity.Msg; + +public class PropertiesUtil { + public static final Properties pro; + public static final Msg BASEMSG = new Msg(); + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + + + static{ + pro = new Properties(); + FileInputStream in = null ; + try { + in= new FileInputStream("C:\\Users\\Administrator\\git\\coding2017\\students\\641013587\\ood\\ood-assignment\\src\\main\\java\\com\\coderising\\ood\\srp\\values.properties"); + pro.load(in); + BASEMSG.setAltSmtpHost(pro.getProperty(ALT_SMTP_SERVER)); + BASEMSG.setSmtpHost(SMTP_SERVER); + BASEMSG.setFromAddress(EMAIL_ADMIN); + } catch (IOException e) { + e.printStackTrace(); + }finally { + try { + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + +} diff --git a/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/values.properties b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/values.properties new file mode 100644 index 0000000000..1f67810743 --- /dev/null +++ b/students/641013587/ood/ood-assignment/src/main/java/com/coderising/ood/srp/values.properties @@ -0,0 +1,3 @@ +smtp.server = smtp.163.com +alt.smtp.server = smtp1.163.com +email.admin = admin@company.com \ No newline at end of file diff --git a/students/643449856/litejunit/pom.xml b/students/643449856/litejunit/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/643449856/litejunit/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/643449856/litejunit/src/main/java/org/litejunit/Assert.java b/students/643449856/litejunit/src/main/java/org/litejunit/Assert.java new file mode 100644 index 0000000000..9908821a5f --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/litejunit/Assert.java @@ -0,0 +1,225 @@ +package org.litejunit; + +/** + * A set of assert methods. + */ + +public class Assert { + /** + * Protect constructor since it is a static only class + */ + protected Assert() { + } + + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError with the given message. + */ + static public void assertTrue(String message, boolean condition) { + if (!condition) + fail(message); + } + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError. + */ + static public void assertTrue(boolean condition) { + assertTrue(null, condition); + } + /** + * Fails a test with the given message. + */ + static public void fail(String message) { + throw new AssertionFailedError(message); + } + /** + * Fails a test with no message. + */ + static public void fail() { + fail(null); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(String message, Object expected, Object actual) { + if (expected == null && actual == null) + return; + if (expected != null && expected.equals(actual)) + return; + failNotEquals(message, expected, actual); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(Object expected, Object actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, double expected, double actual, double delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Double.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Double(expected), new Double(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) // Because comparison with NaN always returns false + failNotEquals(message, new Double(expected), new Double(actual)); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(double expected, double actual, double delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, float expected, float actual, float delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Float.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Float(expected), new Float(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) + failNotEquals(message, new Float(expected), new Float(actual)); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(float expected, float actual, float delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(String message, long expected, long actual) { + assertEquals(message, new Long(expected), new Long(actual)); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(long expected, long actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(String message, boolean expected, boolean actual) { + assertEquals(message, new Boolean(expected), new Boolean(actual)); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(boolean expected, boolean actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(String message, byte expected, byte actual) { + assertEquals(message, new Byte(expected), new Byte(actual)); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(byte expected, byte actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(String message, char expected, char actual) { + assertEquals(message, new Character(expected), new Character(actual)); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(char expected, char actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(String message, short expected, short actual) { + assertEquals(message, new Short(expected), new Short(actual)); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(short expected, short actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(String message, int expected, int actual) { + assertEquals(message, new Integer(expected), new Integer(actual)); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(int expected, int actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(Object object) { + assertNotNull(null, object); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(String message, Object object) { + assertTrue(message, object != null); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(Object object) { + assertNull(null, object); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(String message, Object object) { + assertTrue(message, object == null); + } + /** + * Asserts that two objects refer to the same object. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertSame(String message, Object expected, Object actual) { + if (expected == actual) + return; + failNotSame(message, expected, actual); + } + /** + * Asserts that two objects refer to the same object. If they are not + * the same an AssertionFailedError is thrown. + */ + static public void assertSame(Object expected, Object actual) { + assertSame(null, expected, actual); + } + + static private void failNotEquals(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected:<"+expected+"> but was:<"+actual+">"); + } + + static private void failNotSame(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected same"); + } +} diff --git a/students/643449856/litejunit/src/main/java/org/litejunit/AssertionFailedError.java b/students/643449856/litejunit/src/main/java/org/litejunit/AssertionFailedError.java new file mode 100644 index 0000000000..6ab9b29ba7 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/litejunit/AssertionFailedError.java @@ -0,0 +1,11 @@ +package org.litejunit; + +public class AssertionFailedError extends Error { +public AssertionFailedError(){ + +} + + public AssertionFailedError(String message) { + super(message); + } +} diff --git a/students/643449856/litejunit/src/main/java/org/litejunit/Test.java b/students/643449856/litejunit/src/main/java/org/litejunit/Test.java new file mode 100644 index 0000000000..862dc01c41 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/litejunit/Test.java @@ -0,0 +1,7 @@ +package org.litejunit; + +public interface Test { + public void run(TestResult testResult); + + public Integer getCaseCount(); +} diff --git a/students/643449856/litejunit/src/main/java/org/litejunit/TestCase.java b/students/643449856/litejunit/src/main/java/org/litejunit/TestCase.java new file mode 100644 index 0000000000..310293885a --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/litejunit/TestCase.java @@ -0,0 +1,69 @@ +package org.litejunit; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +public abstract class TestCase extends Assert implements Test { + private String name; + + public TestCase(String name) { + this.name = name; + } + + @Override + public void run(TestResult testResult) { + testResult.run(this); + } + + public void doRun(TestResult testResult) throws Throwable { + setUp(); + try { + runTest(); + + } finally { + tearDown(); + } + } + + protected void setUp() { + + } + + protected void runTest() throws Throwable { + Class clazz = this.getClass(); + Method method=null; + try { + method = clazz.getDeclaredMethod(name); + + } catch (NoSuchMethodException | SecurityException e1) { + // e1.printStackTrace(); + } + + if(!Modifier.isPublic(method.getModifiers())){ + fail("method "+name+" is not a public menthod!"); + } + + try { + method.invoke(this); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + // e.printStackTrace(); + + Throwable ta = e.getCause(); + throw ta; + // } + + } + + } + + protected void tearDown() { + + } + + @Override + public Integer getCaseCount() { + return 1; + } + +} diff --git a/students/643449856/litejunit/src/main/java/org/litejunit/TestFailure.java b/students/643449856/litejunit/src/main/java/org/litejunit/TestFailure.java new file mode 100644 index 0000000000..5933d1f479 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/litejunit/TestFailure.java @@ -0,0 +1,20 @@ +package org.litejunit; + +public class TestFailure { + + private Test test; + private Throwable throwable; + + public TestFailure(Test test, Throwable throwable) { + this.test = test; + this.throwable = throwable; + } + + public Test getTestCase() { + return this.test; + } + + public Throwable getThrowable() { + return this.throwable; + } +} diff --git a/students/643449856/litejunit/src/main/java/org/litejunit/TestResult.java b/students/643449856/litejunit/src/main/java/org/litejunit/TestResult.java new file mode 100644 index 0000000000..96f76e380c --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/litejunit/TestResult.java @@ -0,0 +1,104 @@ +package org.litejunit; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.litejunit.runner.TestListener; + +public class TestResult { + + private List fails; + private List errs; + private int testCount; + private List listeners; + + public TestResult() { + fails = new ArrayList<>(); + errs = new ArrayList<>(); + listeners = new ArrayList<>(); + testCount = 0; + } + + public int failsCount() { + return fails.size(); + } + + public void run(final TestCase test) { + startTest(test); + try { + test.doRun(this); + } catch (AssertionFailedError e) { + addFail(test, e); + } catch (Throwable e) { + addErr(test, e); + } finally { + endTest(test); + } + } + + private void endTest(Test test) { + for (Iterator iter = listeners(); iter.hasNext();) { + TestListener listener = iter.next(); + listener.endTest(test); + } + } + + private void startTest(Test test) { + testCount += test.getCaseCount(); + + for (Iterator iter = listeners(); iter.hasNext();) { + TestListener listener = iter.next(); + listener.startTest(test); + } + } + + private void addErr(final Test test, Throwable e) { + errs.add(new TestFailure(test, e)); + + for (Iterator iter = listeners(); iter.hasNext();) { + TestListener listener = iter.next(); + listener.addErr(test, e); + } + } + + private void addFail(final Test test, AssertionFailedError e) { + fails.add(new TestFailure(test, e)); + for (Iterator iter = listeners(); iter.hasNext();) { + TestListener listener = iter.next(); + listener.addFail(test, e); + } + } + + public Iterator fails() { + return fails.iterator(); + } + + public Iterator errs() { + return errs.iterator(); + } + + public int errsCount() { + return errs.size(); + } + + public int runCount() { + return testCount; + } + + public boolean isSuccesful() { + return failsCount() == 0 && errsCount() == 0; + } + + public void addListener(TestListener listener) { + listeners.add(listener); + } + + public void removeListener(TestListener listener) { + listeners.remove(listener); + } + + private Iterator listeners() { + return listeners.iterator(); + } +} diff --git a/students/643449856/litejunit/src/main/java/org/litejunit/TestTuite.java b/students/643449856/litejunit/src/main/java/org/litejunit/TestTuite.java new file mode 100644 index 0000000000..187433a27b --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/litejunit/TestTuite.java @@ -0,0 +1,128 @@ +package org.litejunit; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class TestTuite extends Assert implements Test { + List caselist = new ArrayList<>(10); + List namelist = new ArrayList<>(); + private String name; + + public TestTuite(String name) { + this.name = name; + } + + public TestTuite(final Class clazz) { + if (!Modifier.isPublic(clazz.getModifiers())) { + fail("the class " + clazz.getName() + " must be public"); + } + Constructor constructor = getConstructor(clazz); + Method[] arrmethod = clazz.getDeclaredMethods(); + for (Method m : arrmethod) { + addTest(m, constructor); + } + + if (arrmethod.length == 0) { + fail("there is no method to test!"); + } + } + + private Constructor getConstructor(Class clazz) { + Class[] parameterTypes = new Class[] { String.class }; + Constructor constructor = null; + try { + constructor = clazz.getConstructor(parameterTypes); + } catch (NoSuchMethodException | SecurityException e) { + e.printStackTrace(); + } + return constructor; + } + + public void addTest(Method m, Constructor constructor) { + if (!isTestMethod(m)) { + return; + } + String method_name = m.getName(); + if (namelist.contains(method_name)) { + return; + } + namelist.add(method_name); + Object[] initargs = new Object[] { method_name }; + try { + Test t = (Test) constructor.newInstance(initargs); + addTest(t); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException + | InvocationTargetException e) { + e.printStackTrace(); + } + } + + public void addTest(Test t) { + caselist.add(t); + } + + public void addTest(Class clazz) { + Object obj = null; + try { + obj = clazz.newInstance(); + } catch (InstantiationException | IllegalAccessException e1) { + e1.printStackTrace(); + } + + Method method = null; + try { + Class[] args = new Class[0]; + method=clazz.getMethod("tuite", args); + } catch (NoSuchMethodException e) { + e.printStackTrace(); + } catch (SecurityException e) { + e.printStackTrace(); + } + + try { + Test test = (Test) method.invoke(obj); + addTest(test); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } + + } + + private boolean isTestMethod(Method m) { + + return m.getName().startsWith("test") && Modifier.isPublic(m.getModifiers()) + && m.getParameterTypes().length == 0 && m.getReturnType().equals(Void.TYPE); + } + + @Override + public void run(TestResult testResult) { + for (Test tc : caselist) { + tc.run(testResult); + + } + } + + @Override + public Integer getCaseCount() { + int count = 0; + for (Iterator iterator = caselist.iterator(); iterator.hasNext();) { + Test test = iterator.next(); + count += test.getCaseCount(); + } + return count; + } + + public void addTestTuite(Class clazz) { + addTest(new TestTuite(clazz)); + } + +} diff --git a/students/643449856/litejunit/src/main/java/org/litejunit/extension/RepeatedTest.java b/students/643449856/litejunit/src/main/java/org/litejunit/extension/RepeatedTest.java new file mode 100644 index 0000000000..dbce472e8b --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/litejunit/extension/RepeatedTest.java @@ -0,0 +1,26 @@ +package org.litejunit.extension; + +import org.litejunit.Test; +import org.litejunit.TestResult; + +public class RepeatedTest extends TestDecorator { + + private int num; + + public RepeatedTest(Test t, int num) { + super(t); + if (num < 0) { + throw new IllegalArgumentException("num must>0"); + } + this.num = num; + } + + @Override + public void run(TestResult testResult) { + for (int i = 0; i < num; i++) { + super.run(testResult); + } + + } + +} diff --git a/students/643449856/litejunit/src/main/java/org/litejunit/extension/TestDecorator.java b/students/643449856/litejunit/src/main/java/org/litejunit/extension/TestDecorator.java new file mode 100644 index 0000000000..571e1074a7 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/litejunit/extension/TestDecorator.java @@ -0,0 +1,26 @@ +package org.litejunit.extension; + +import org.litejunit.Test; +import org.litejunit.TestResult; + +public class TestDecorator implements Test { + + Test test; + + public TestDecorator(Test test) { + this.test = test; + } + + + + @Override + public void run(TestResult testResult) { + test.run(testResult); + } + + @Override + public Integer getCaseCount() { + return test.getCaseCount(); + } + +} diff --git a/students/643449856/litejunit/src/main/java/org/litejunit/extension/TestSetup.java b/students/643449856/litejunit/src/main/java/org/litejunit/extension/TestSetup.java new file mode 100644 index 0000000000..136da5050d --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/litejunit/extension/TestSetup.java @@ -0,0 +1,27 @@ +package org.litejunit.extension; + +import org.litejunit.Test; +import org.litejunit.TestResult; + +public class TestSetup extends TestDecorator { + + public TestSetup(Test t) { + super(t); + + } + + @Override + public void run(TestResult testResult) { + setup(); + super.run(testResult); + teardown(); + } + + private void teardown() { + } + + private void setup() { + + } + +} diff --git a/students/643449856/litejunit/src/main/java/org/litejunit/runner/TestBaseRunner.java b/students/643449856/litejunit/src/main/java/org/litejunit/runner/TestBaseRunner.java new file mode 100644 index 0000000000..48ca6a24af --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/litejunit/runner/TestBaseRunner.java @@ -0,0 +1,37 @@ +package org.litejunit.runner; + +import java.io.PrintStream; +import java.text.NumberFormat; + +import org.litejunit.AssertionFailedError; +import org.litejunit.Test; + +public class TestBaseRunner implements TestListener { + private PrintStream pStream = System.out; + int column = 0; + + @Override + public synchronized void endTest(Test test) { + } + + @Override + public synchronized void startTest(Test test) { + pStream.print("."); + if (++column > 20) { + pStream.println(); + column = 0; + } + } + + @Override + public synchronized void addErr(Test test, Throwable e) { + } + + @Override + public synchronized void addFail(Test test, AssertionFailedError e) { + } +public String formatNum(long num) { + return NumberFormat.getInstance().format((double)(num/1000)); +} + +} diff --git a/students/643449856/litejunit/src/main/java/org/litejunit/runner/TestListener.java b/students/643449856/litejunit/src/main/java/org/litejunit/runner/TestListener.java new file mode 100644 index 0000000000..8612b9863a --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/litejunit/runner/TestListener.java @@ -0,0 +1,14 @@ +package org.litejunit.runner; + +import org.litejunit.AssertionFailedError; +import org.litejunit.Test; + +public interface TestListener { + public void endTest(Test test); + + public void startTest(Test test); + + public void addErr(final Test test, Throwable e) ; + + public void addFail(final Test test, AssertionFailedError e); +} diff --git a/students/643449856/litejunit/src/main/java/org/litejunit/runner/TestRunner.java b/students/643449856/litejunit/src/main/java/org/litejunit/runner/TestRunner.java new file mode 100644 index 0000000000..422b01183d --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/litejunit/runner/TestRunner.java @@ -0,0 +1,69 @@ +package org.litejunit.runner; + +import java.io.PrintStream; +import java.util.Iterator; + +import org.litejunit.Test; +import org.litejunit.TestFailure; +import org.litejunit.TestResult; +import org.litejunit.sample.AllTest; + +public class TestRunner extends TestBaseRunner { + + private PrintStream ps = System.out; + + public static void main(String[] args) { + + Test test = AllTest.tuite(); + TestResult tr = new TestResult(); + TestRunner runner = new TestRunner(); + tr.addListener(runner); + long t1 = System.currentTimeMillis(); + test.run(tr); + long t2 = System.currentTimeMillis(); + runner.ps.println(); + runner.ps.println("Time:" + runner.formatNum(t2 - t1) + "s"); + + runner.printResult(tr); + + } + + private void printResult(TestResult tr) { + printFails(tr); + printErrs(tr); + printSummary(tr); + } + + private void printSummary(TestResult tr) { + String result = tr.isSuccesful() ? "Success" : "Fail"; + ps.println(result); + ps.println("Test run:" + tr.runCount() + ",Failures:" + tr.failsCount() + ",Errs:" + tr.errsCount()); + } + + private void printErrs(TestResult tr) { + int count = tr.errsCount(); + String s = count > 1 ? "there were " + count + " errs" : "there was " + count + " err"; + ps.println(s); + int i = 1; + for (Iterator iter = tr.errs(); iter.hasNext();) { + TestFailure failure = iter.next(); + ps.print((i++) + ")"); + ps.println(failure.getTestCase()); + ps.println(failure.getThrowable()); + } + } + + private void printFails(TestResult tr) { + int count = tr.failsCount(); + String s = count > 1 ? "there were " + count + " fails" : "there was " + count + " fail"; + ps.println(s); + int i = 1; + for (Iterator iter = tr.fails(); iter.hasNext();) { + TestFailure failure = iter.next(); + ps.print((i++) + ")"); + ps.println(failure.getTestCase()); + ps.println(failure.getThrowable()); + } + } + +} diff --git a/students/643449856/litejunit/src/main/java/org/litejunit/sample/AllTest.java b/students/643449856/litejunit/src/main/java/org/litejunit/sample/AllTest.java new file mode 100644 index 0000000000..edcb87452b --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/litejunit/sample/AllTest.java @@ -0,0 +1,19 @@ +package org.litejunit.sample; + +import org.litejunit.Test; +import org.litejunit.TestTuite; +import org.litejunit.extension.RepeatedTest; +import org.litejunit.sample.caculator.CalculatorTuite; +import org.litejunit.sample.person.PersonTest; + + +public class AllTest { +public static Test tuite() { + TestTuite tuite=new TestTuite("AllTest"); + tuite.addTest(CalculatorTuite.tuite()); + //tuite.addTestTuite(PersonTest.class); + //return tuite; + tuite.addTest(new RepeatedTest(new TestTuite(PersonTest.class), 1)); + return new org.litejunit.extension.TestSetup(tuite); +} +} diff --git a/students/643449856/litejunit/src/main/java/org/litejunit/sample/caculator/CaculatorTestCase.java b/students/643449856/litejunit/src/main/java/org/litejunit/sample/caculator/CaculatorTestCase.java new file mode 100644 index 0000000000..f183f4dc3e --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/litejunit/sample/caculator/CaculatorTestCase.java @@ -0,0 +1,39 @@ +package org.litejunit.sample.caculator; + +import org.litejunit.TestCase; + +public class CaculatorTestCase extends TestCase { + + Calculator calculator = null; + + public CaculatorTestCase(String name) { + super(name); + } + + public void setUp() { + calculator = new Calculator(); + } + + public void tearDown() { + calculator = null; + } + + public void testAdd() { + + calculator.add(10); + int a=0; + int b=1/a; + assertEquals(10, calculator.getResult()); + System.out.println("testadd"); + } + + public void testSubtract() { + calculator.add(10); + calculator.subtract(5); + assertEquals(4, calculator.getResult()); + System.out.println("testSubtract"); + } + + + +} diff --git a/students/643449856/litejunit/src/main/java/org/litejunit/sample/caculator/Calculator.java b/students/643449856/litejunit/src/main/java/org/litejunit/sample/caculator/Calculator.java new file mode 100644 index 0000000000..d0ed088aca --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/litejunit/sample/caculator/Calculator.java @@ -0,0 +1,22 @@ +package org.litejunit.sample.caculator; + +public class Calculator { + + private int result = 0; + public void add(int x){ + result += x; + } + public void subtract(int x){ + result -=x; + } + + public int getResult(){ + return this.result; + } + public static void main(String[] args){ + Calculator calculator = new Calculator(); + calculator.add(10); + calculator.subtract(5); + System.out.println(calculator.getResult()); + } +} diff --git a/students/643449856/litejunit/src/main/java/org/litejunit/sample/caculator/CalculatorTuite.java b/students/643449856/litejunit/src/main/java/org/litejunit/sample/caculator/CalculatorTuite.java new file mode 100644 index 0000000000..0be67ab224 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/litejunit/sample/caculator/CalculatorTuite.java @@ -0,0 +1,12 @@ +package org.litejunit.sample.caculator; + +import org.litejunit.Test; +import org.litejunit.TestTuite; + +public class CalculatorTuite { +public static Test tuite() { + TestTuite tuite=new TestTuite("CalculatorTuite"); + tuite.addTestTuite(CaculatorTestCase.class); + return tuite; +} +} diff --git a/students/643449856/litejunit/src/main/java/org/v3/After.java b/students/643449856/litejunit/src/main/java/org/v3/After.java new file mode 100644 index 0000000000..85dc08ab38 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/After.java @@ -0,0 +1,12 @@ +package org.v3; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface After { +} + diff --git a/students/643449856/litejunit/src/main/java/org/v3/AfterClass.java b/students/643449856/litejunit/src/main/java/org/v3/AfterClass.java new file mode 100644 index 0000000000..e101051002 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/AfterClass.java @@ -0,0 +1,13 @@ +package org.v3; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface AfterClass { +} diff --git a/students/643449856/litejunit/src/main/java/org/v3/Assert.java b/students/643449856/litejunit/src/main/java/org/v3/Assert.java new file mode 100644 index 0000000000..dce024757e --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/Assert.java @@ -0,0 +1,269 @@ +package org.v3; + +/** + * A set of assertion methods useful for writing tests. Only failed assertions are recorded. + * These methods can be used directly: Assert.assertEquals(...), however, they + * read better if they are referenced through static import:
+ * + * import static org.junit.Assert.*;
+ * ...
+ *   assertEquals(...);
+ *
+ */ + +public class Assert { + /** + * Protect constructor since it is a static only class + */ + protected Assert() { + } + + /** + * Asserts that a condition is true. If it isn't it throws an + * AssertionError with the given message. + */ + static public void assertTrue(String message, boolean condition) { + if (!condition) + fail(message); + } + + /** + * Asserts that a condition is true. If it isn't it throws an + * AssertionError. + */ + static public void assertTrue(boolean condition) { + assertTrue(null, condition); + } + + /** + * Asserts that a condition is false. If it isn't it throws an + * AssertionError with the given message. + */ + static public void assertFalse(String message, boolean condition) { + assertTrue(message, !condition); + } + + /** + * Asserts that a condition is false. If it isn't it throws an + * AssertionError. + */ + static public void assertFalse(boolean condition) { + assertFalse(null, condition); + } + + /** + * Fails a test with the given message. + */ + static public void fail(String message) { + throw new AssertionError(message); + } + + /** + * Fails a test with no message. + */ + static public void fail() { + fail(null); + } + + /** + * Asserts that two objects are equal. If they are not, an + * AssertionError is thrown with the given message. + */ + static public void assertEquals(String message, Object expected, Object actual) { + if (expected == null && actual == null) + return; + if (expected != null && expected.equals(actual)) + return; + if (expected instanceof String && actual instanceof String) + throw new ComparisonFailure(message, (String)expected, (String)actual); + else + failNotEquals(message, expected, actual); + } + + /** + * Asserts that two objects are equal. If they are not, an + * AssertionError is thrown. + */ + static public void assertEquals(Object expected, Object actual) { + assertEquals(null, expected, actual); + } + + /** + * Asserts that two object arrays are equal. If they are not, an + * AssertionError is thrown with the given message. + */ + public static void assertEquals(String message, Object[] expecteds, Object[] actuals) { + if (expecteds == actuals) + return; + String header = message == null ? "" : message + ": "; + if (expecteds == null) + fail(header + "expected array was null"); + if (actuals == null) + fail(header + "actual array was null"); + if (actuals.length != expecteds.length) + fail(header + "array lengths differed, expected.length=" + expecteds.length + " actual.length=" + actuals.length); + + for (int i= 0; i < expecteds.length; i++) { + Object o1= expecteds[i]; + Object o2= actuals[i]; + if (o1.getClass().isArray() && o2.getClass().isArray()) { + Object[] expected= (Object[]) o1; + Object[] actual= (Object[]) o2; + assertEquals(header + "arrays first differed at element " + i + ";", expected, actual); + } else + assertEquals(header + "arrays first differed at element [" + i + "];", o1, o2); + } + } + + /** + * Asserts that two object arrays are equal. If they are not, an + * AssertionError is thrown. + */ + public static void assertEquals(Object[] expecteds, Object[] actuals) { + assertEquals(null, expecteds, actuals); + } + + /** + * Asserts that two doubles are equal to within a positive delta. If they + * are not, an AssertionError is thrown with the given message. If the + * expected value is infinity then the delta value is ignored. NaNs are + * considered equal: + * assertEquals(Double.NaN, Double.NaN, *) passes + */ + static public void assertEquals(String message, double expected, double actual, double delta) { + if (Double.compare(expected, actual) == 0) + return; + if (!(Math.abs(expected - actual) <= delta)) + failNotEquals(message, new Double(expected), new Double(actual)); + } + + /** + * Asserts that two doubles are equal to within a positive delta. If they + * are not, an AssertionError is thrown. If the + * expected value is infinity then the delta value is ignored.NaNs are + * considered equal: + * assertEquals(Double.NaN, Double.NaN, *) passes + */ + static public void assertEquals(double expected, double actual, double delta) { + assertEquals(null, expected, actual, delta); + } + + /** + * Asserts that two floats are equal to within a positive delta. If they + * are not, an AssertionError is thrown with the given message. If the + * expected value is infinity then the delta value is ignored.NaNs are + * considered equal: + * assertEquals(Float.NaN, Float.NaN, *) passes + */ + static public void assertEquals(String message, float expected, float actual, float delta) { + if (Float.compare(expected, actual) == 0) + return; + if (!(Math.abs(expected - actual) <= delta)) + failNotEquals(message, new Float(expected), new Float(actual)); + } + + /** + * Asserts that two floats are equal to within a positive delta. If they + * are not, an AssertionError is thrown. If the + * expected value is infinity then the delta value is ignored.NaNs are + * considered equal: + * assertEquals(Float.NaN, Float.NaN, *) passes + */ + static public void assertEquals(float expected, float actual, float delta) { + assertEquals(null, expected, actual, delta); + } + + /** + * Asserts that an object isn't null. If it is an AssertionError is + * thrown with the given message. + */ + static public void assertNotNull(String message, Object object) { + assertTrue(message, object != null); + } + + /** + * Asserts that an object isn't null. If it is an AssertionError is + * thrown. + */ + static public void assertNotNull(Object object) { + assertNotNull(null, object); + } + + /** + * Asserts that an object is null. If it is not, an AssertionError is + * thrown with the given message. + */ + static public void assertNull(String message, Object object) { + assertTrue(message, object == null); + } + + /** + * Asserts that an object is null. If it isn't an AssertionError is + * thrown. + */ + static public void assertNull(Object object) { + assertNull(null, object); + } + + /** + * Asserts that two objects refer to the same object. If they are not, an + * AssertionError is thrown with the given message. + */ + static public void assertSame(String message, Object expected, Object actual) { + if (expected == actual) + return; + failNotSame(message, expected, actual); + } + + /** + * Asserts that two objects refer to the same object. If they are not the + * same, an AssertionError is thrown. + */ + static public void assertSame(Object expected, Object actual) { + assertSame(null, expected, actual); + } + + /** + * Asserts that two objects do not refer to the same object. If they do + * refer to the same object, an AssertionError is thrown with the given + * message. + */ + static public void assertNotSame(String message, Object expected, Object actual) { + if (expected == actual) + failSame(message); + } + + /** + * Asserts that two objects do not refer to the same object. If they do + * refer to the same object, an AssertionError is thrown. + */ + static public void assertNotSame(Object expected, Object actual) { + assertNotSame(null, expected, actual); + } + + static private void failSame(String message) { + String formatted= ""; + if (message != null) + formatted= message + " "; + fail(formatted + "expected not same"); + } + + static private void failNotSame(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message + " "; + fail(formatted + "expected same:<" + expected + "> was not:<" + actual + ">"); + } + + static private void failNotEquals(String message, Object expected, Object actual) { + fail(format(message, expected, actual)); + } + + static String format(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message + " "; + return formatted + "expected:<" + expected + "> but was:<" + actual + ">"; + } + +} diff --git a/students/643449856/litejunit/src/main/java/org/v3/Before.java b/students/643449856/litejunit/src/main/java/org/v3/Before.java new file mode 100644 index 0000000000..55b92777e3 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/Before.java @@ -0,0 +1,13 @@ +package org.v3; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Before { +} + diff --git a/students/643449856/litejunit/src/main/java/org/v3/BeforeClass.java b/students/643449856/litejunit/src/main/java/org/v3/BeforeClass.java new file mode 100644 index 0000000000..3b06fe066b --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/BeforeClass.java @@ -0,0 +1,11 @@ +package org.v3; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface BeforeClass { +} diff --git a/students/643449856/litejunit/src/main/java/org/v3/ComparisonFailure.java b/students/643449856/litejunit/src/main/java/org/v3/ComparisonFailure.java new file mode 100644 index 0000000000..359cc48bef --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/ComparisonFailure.java @@ -0,0 +1,124 @@ +package org.v3; + +/** + * Thrown when an assertEquals(String, String) fails. Create and throw + * a ComparisonFailure manually if you want to show users the difference between two complex + * strings. + * + * Inspired by a patch from Alex Chaffee (alex@purpletech.com) + */ +public class ComparisonFailure extends AssertionError { + private static final int MAX_CONTEXT_LENGTH= 20; + private static final long serialVersionUID= 1L; + + private String fExpected; + private String fActual; + + /** + * Constructs a comparison failure. + * @param message the identifying message or null + * @param expected the expected string value + * @param actual the actual string value + */ + public ComparisonFailure (String message, String expected, String actual) { + super (message); + fExpected= expected; + fActual= actual; + } + + /** + * Returns "..." in place of common prefix and "..." in + * place of common suffix between expected and actual. + * + * @see Throwable#getMessage() + */ + @Override + public String getMessage() { + return new ComparisonCompactor(MAX_CONTEXT_LENGTH, fExpected, fActual).compact(super.getMessage()); + } + + /** + * Returns the actual value + * @return the actual string value + */ + public String getActual() { + return fActual; + } + /** + * Returns the expected value + * @return the expected string value + */ + public String getExpected() { + return fExpected; + } + + private static class ComparisonCompactor { + private static final String ELLIPSIS= "..."; + private static final String DELTA_END= "]"; + private static final String DELTA_START= "["; + + private int fContextLength; + private String fExpected; + private String fActual; + private int fPrefix; + private int fSuffix; + + public ComparisonCompactor(int contextLength, String expected, String actual) { + fContextLength= contextLength; + fExpected= expected; + fActual= actual; + } + + public String compact(String message) { + if (fExpected == null || fActual == null || areStringsEqual()) + return Assert.format(message, fExpected, fActual); + + findCommonPrefix(); + findCommonSuffix(); + String expected= compactString(fExpected); + String actual= compactString(fActual); + return Assert.format(message, expected, actual); + } + + private String compactString(String source) { + String result= DELTA_START + source.substring(fPrefix, source.length() - fSuffix + 1) + DELTA_END; + if (fPrefix > 0) + result= computeCommonPrefix() + result; + if (fSuffix > 0) + result= result + computeCommonSuffix(); + return result; + } + + private void findCommonPrefix() { + fPrefix= 0; + int end= Math.min(fExpected.length(), fActual.length()); + for (; fPrefix < end; fPrefix++) { + if (fExpected.charAt(fPrefix) != fActual.charAt(fPrefix)) + break; + } + } + + private void findCommonSuffix() { + int expectedSuffix= fExpected.length() - 1; + int actualSuffix= fActual.length() - 1; + for (; actualSuffix >= fPrefix && expectedSuffix >= fPrefix; actualSuffix--, expectedSuffix--) { + if (fExpected.charAt(expectedSuffix) != fActual.charAt(actualSuffix)) + break; + } + fSuffix= fExpected.length() - expectedSuffix; + } + + private String computeCommonPrefix() { + return (fPrefix > fContextLength ? ELLIPSIS : "") + fExpected.substring(Math.max(0, fPrefix - fContextLength), fPrefix); + } + + private String computeCommonSuffix() { + int end= Math.min(fExpected.length() - fSuffix + 1 + fContextLength, fExpected.length()); + return fExpected.substring(fExpected.length() - fSuffix + 1, end) + (fExpected.length() - fSuffix + 1 < fExpected.length() - fContextLength ? ELLIPSIS : ""); + } + + private boolean areStringsEqual() { + return fExpected.equals(fActual); + } + } +} \ No newline at end of file diff --git a/students/643449856/litejunit/src/main/java/org/v3/Ignore.java b/students/643449856/litejunit/src/main/java/org/v3/Ignore.java new file mode 100644 index 0000000000..4677b35a2e --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/Ignore.java @@ -0,0 +1,31 @@ +package org.v3; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Sometimes you want to temporarily disable a test. Methods annotated with @Test + * that are also annotated with @Ignore will not be executed as tests. Native JUnit 4 test runners + * should report the number of ignored tests along with the number of tests that ran and the + * number of tests that failed. + *

+ * For example:
+ * + *   @Ignore @Test public void something() { ...
+ *
+ * @Ignore takes an optional default parameter if you want to record why a test is being ignored:
+ * + *   @Ignore("not ready yet") @Test public void something() { ...
+ *
+ * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Ignore { + /** + * The optional reason why the test is ignored. + */ + String value() default ""; +} diff --git a/students/643449856/litejunit/src/main/java/org/v3/Test.java b/students/643449856/litejunit/src/main/java/org/v3/Test.java new file mode 100644 index 0000000000..0902695239 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/Test.java @@ -0,0 +1,62 @@ +package org.v3; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * The Test annotation tells JUnit that the public void method + * to which it is attached can be run as a test case. To run the method, + * JUnit first constructs a fresh instance of the class then invokes the + * annotated method. Any exceptions thrown by the test will be reported + * by JUnit as a failure. If no exceptions are thrown, the test is assumed + * to have succeeded. + *

+ * A simple test looks like this:
+ * + * public class Example {
+ *   @Test public void method() {
+ *     System.out.println("Hello");
+ *   }
+ * } + *
+ *

+ * The Test annotation supports two optional parameters. + * The first, expected, declares that a test method should throw + * an exception. If it doesn't throw an exception or if it throws a different exception + * than the one declared, the test fails. For example, the following test succeeds:
+ * + *   @Test(expected=IndexOutOfBoundsException.class) public void outOfBounds() {
+ *     new ArrayList<Object>().get(1);
+ *   }
+ *
+ *

+ * The second optional parameter, timeout, causes a test to fail if it takes longer than a specified + * amount of clock time (measured in milliseconds). The following test fails:
+ * + *   @Test(timeout=100) public void infinity() {
+ *     for(;;);
+ *   }
+ *
+ */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Test { + static class None extends Throwable { + private static final long serialVersionUID= 1L; + private None() { + } + } + + /** + * Optionally specify expected, a Throwable, to cause a test method to succeed iff + * an exception of the specified class is thrown by the method. + */ + Class expected() default None.class; + + /** + * Optionally specify timeout in milliseconds to cause a test method to fail if it + * takes longer than that number of milliseconds.*/ + long timeout() default 0L; +} diff --git a/students/643449856/litejunit/src/main/java/org/v3/notification/Failure.java b/students/643449856/litejunit/src/main/java/org/v3/notification/Failure.java new file mode 100644 index 0000000000..29f9cf11c1 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/notification/Failure.java @@ -0,0 +1,79 @@ +package org.v3.notification; + +import org.v3.runner.Description; + +import java.io.PrintWriter; +import java.io.StringWriter; + + + +/** + * A Failure holds a description of the failed test and the + * exception that was thrown while running it. In most cases the Description + * will be of a single test. However, if problems are encountered while constructing the + * test (for example, if a @BeforeClass method is not static), it may describe + * something other than a single test. + */ +public class Failure { + private final Description fDescription; + private Throwable fThrownException; + + /** + * Constructs a Failure with the given description and exception. + * @param description a Description of the test that failed + * @param thrownException the exception that was thrown while running the test + */ + public Failure(Description description, Throwable thrownException) { + fThrownException = thrownException; + fDescription= description; + } + + /** + * @return a user-understandable label for the test + */ + public String getTestHeader() { + return fDescription.getDisplayName(); + } + + /** + * @return the raw description of the context of the failure. + */ + public Description getDescription() { + return fDescription; + } + + /** + * @return the exception thrown + */ + + public Throwable getException() { + return fThrownException; + } + + @Override + public String toString() { + StringBuffer buffer= new StringBuffer(); + buffer.append(getTestHeader() + ": "+fThrownException.getMessage()); + return buffer.toString(); + } + + /** + * Convenience method + * @return the printed form of the exception + */ + public String getTrace() { + StringWriter stringWriter= new StringWriter(); + PrintWriter writer= new PrintWriter(stringWriter); + getException().printStackTrace(writer); + StringBuffer buffer= stringWriter.getBuffer(); + return buffer.toString(); + } + + /** + * Convenience method + * @return the message of the thrown exception + */ + public String getMessage() { + return getException().getMessage(); + } +} diff --git a/students/643449856/litejunit/src/main/java/org/v3/notification/RunListener.java b/students/643449856/litejunit/src/main/java/org/v3/notification/RunListener.java new file mode 100644 index 0000000000..2da301b9c4 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/notification/RunListener.java @@ -0,0 +1,53 @@ +package org.v3.notification; + + +import org.v3.runner.Description; +import org.v3.runner.Result; + +public class RunListener { + + /** + * Called before any tests have been run. + * @param description describes the tests to be run + */ + public void testRunStarted(Description description) throws Exception { + } + + /** + * Called when all tests have finished + * @param result the summary of the test run, including all the tests that failed + */ + public void testRunFinished(Result result) throws Exception { + } + + /** + * Called when an atomic test is about to be started. + * @param description the description of the test that is about to be run (generally a class and method name) + */ + public void testStarted(Description description) throws Exception { + } + + /** + * Called when an atomic test has finished, whether the test succeeds or fails. + * @param description the description of the test that just ran + */ + public void testFinished(Description description) throws Exception { + } + + /** + * Called when an atomic test fails. + * @param failure describes the test that failed and the exception that was thrown + */ + public void testFailure(Failure failure) throws Exception { + } + + /** + * Called when a test will not be run, generally because a test method is annotated with @Ignored. + * @param description describes the test that will not be run + */ + public void testIgnored(Description description) throws Exception { + } + +} + + diff --git a/students/643449856/litejunit/src/main/java/org/v3/notification/RunNotifier.java b/students/643449856/litejunit/src/main/java/org/v3/notification/RunNotifier.java new file mode 100644 index 0000000000..3566b1f46f --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/notification/RunNotifier.java @@ -0,0 +1,141 @@ +package org.v3.notification; + +import org.v3.runner.Description; +import org.v3.runner.Result; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + + + + + +/** + * If you write custom runners, you may need to notify JUnit of your progress running tests. + * Do this by invoking the RunNotifier passed to your implementation of + * Runner.run(RunNotifier notifier). Future evolution of this class is likely to + * move fireTestRunStarted() and fireTestRunFinished() + * to a separate class since they should only be called once per run. + */ +public class RunNotifier { + private List fListeners= new ArrayList(); + private boolean fPleaseStop= false; + + /** Internal use only + */ + public void addListener(RunListener listener) { + fListeners.add(listener); + } + + /** Internal use only + */ + public void removeListener(RunListener listener) { + fListeners.remove(listener); + } + + private abstract class SafeNotifier { + void run() { + for (Iterator all= fListeners.iterator(); all.hasNext();) { + try { + notifyListener(all.next()); + } catch (Exception e) { + all.remove(); // Remove the offending listener first to avoid an infinite loop + fireTestFailure(new Failure(Description.TEST_MECHANISM, e)); + } + } + } + + abstract protected void notifyListener(RunListener each) throws Exception; + } + + /** + * Do not invoke. + */ + public void fireTestRunStarted(final Description description) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testRunStarted(description); + }; + }.run(); + } + + /** + * Do not invoke. + */ + public void fireTestRunFinished(final Result result) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testRunFinished(result); + }; + }.run(); + } + + /** + * Invoke to tell listeners that an atomic test is about to start. + * @param description the description of the atomic test (generally a class and method name) + * @throws StoppedByUserException thrown if a user has requested that the test run stop + */ + public void fireTestStarted(final Description description) throws StoppedByUserException { + if (fPleaseStop) + throw new StoppedByUserException(); + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testStarted(description); + }; + }.run(); + } + + /** + * Invoke to tell listeners that an atomic test failed. + * @param failure the description of the test that failed and the exception thrown + */ + public void fireTestFailure(final Failure failure) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testFailure(failure); + }; + }.run(); + } + + /** + * Invoke to tell listeners that an atomic test was ignored. + * @param description the description of the ignored test + */ + public void fireTestIgnored(final Description description) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testIgnored(description); + }; + }.run(); + } + + /** + * Invoke to tell listeners that an atomic test finished. Always invoke fireTestFinished() + * if you invoke fireTestStarted() as listeners are likely to expect them to come in pairs. + * @param description the description of the test that finished + */ + public void fireTestFinished(final Description description) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testFinished(description); + }; + }.run(); + } + + /** + * Ask that the tests run stop before starting the next test. Phrased politely because + * the test currently running will not be interrupted. It seems a little odd to put this + * functionality here, but the RunNotifier is the only object guaranteed + * to be shared amongst the many runners involved. + */ + public void pleaseStop() { + fPleaseStop= true; + } +} \ No newline at end of file diff --git a/students/643449856/litejunit/src/main/java/org/v3/notification/StoppedByUserException.java b/students/643449856/litejunit/src/main/java/org/v3/notification/StoppedByUserException.java new file mode 100644 index 0000000000..a820b0ab44 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/notification/StoppedByUserException.java @@ -0,0 +1,11 @@ +package org.v3.notification; + +/** + * Thrown when a user has requested that the test run stop. Writers of + * test running GUIs should be prepared to catch a StoppedByUserException. + * + * @see org.junit.runner.notification.RunNotifier + */ +public class StoppedByUserException extends RuntimeException { + private static final long serialVersionUID= 1L; +} diff --git a/students/643449856/litejunit/src/main/java/org/v3/requests/ClassRequest.java b/students/643449856/litejunit/src/main/java/org/v3/requests/ClassRequest.java new file mode 100644 index 0000000000..4ac6356a71 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/requests/ClassRequest.java @@ -0,0 +1,48 @@ +/** + * + */ +package org.v3.requests; + +import java.lang.reflect.Constructor; + +import org.v3.runner.Request; +import org.v3.runner.Runner; +import org.v3.runners.TestClassRunner; + + +public class ClassRequest extends Request { + private final Class fTestClass; + + public ClassRequest(Class each) { + fTestClass= each; + } + + @Override + public Runner getRunner() { + Class runnerClass= getRunnerClass(fTestClass); + try { + Constructor constructor= runnerClass.getConstructor(Class.class); // TODO good error message if no such constructor + Runner runner= (Runner) constructor + .newInstance(new Object[] { fTestClass }); + return runner; + } catch (Exception e) { + return null; + //return Request.errorReport(fTestClass, e).getRunner(); + } + } + + Class getRunnerClass(Class testClass) { + /*RunWith annotation= testClass.getAnnotation(RunWith.class); + if (annotation != null) { + return annotation.value(); + } else if (isPre4Test(testClass)) { + return OldTestClassRunner.class; + } else {*/ + return TestClassRunner.class; + /*}*/ + } + + /*boolean isPre4Test(Class testClass) { + return junit.framework.TestCase.class.isAssignableFrom(testClass); + }*/ +} \ No newline at end of file diff --git a/students/643449856/litejunit/src/main/java/org/v3/runner/Description.java b/students/643449856/litejunit/src/main/java/org/v3/runner/Description.java new file mode 100644 index 0000000000..991d9471af --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/runner/Description.java @@ -0,0 +1,127 @@ +package org.v3.runner; + +import java.util.ArrayList; + +/** + * A Description describes a test which is to be run or has been run. Descriptions can + * be atomic (a single test) or compound (containing children tests). Descriptions are used + * to provide feedback about the tests that are about to run (for example, the tree view + * visible in many IDEs) or tests that have been run (for example, the failures view).

+ * Descriptions are implemented as a single class rather than a Composite because + * they are entirely informational. They contain no logic aside from counting their tests.

+ * In the past, we used the raw junit.framework.TestCases and junit.framework.TestSuites + * to display the tree of tests. This was no longer viable in JUnit 4 because atomic tests no longer have a superclass below Object. + * We needed a way to pass a class and name together. Description emerged from this. + * + * @see org.junit.runner.Request + * @see org.junit.runner.Runner + */ +public class Description { + + /** + * Create a Description named name. + * Generally, you will add children to this Description. + * @param name The name of the Description + * @return A Description named name + */ + public static Description createSuiteDescription(String name) { + return new Description(name); + } + + /** + * Create a Description of a single test named name in the class clazz. + * Generally, this will be a leaf Description. + * @param clazz The class of the test + * @param name The name of the test (a method name for test annotated with @Test) + * @return A Description named name + */ + public static Description createTestDescription(Class clazz, String name) { + return new Description(String.format("%s(%s)", name, clazz.getName())); + } + + /** + * Create a generic Description that says there are tests in testClass. + * This is used as a last resort when you cannot precisely describe the individual tests in the class. + * @param testClass A Class containing tests + * @return A Description of testClass + */ + public static Description createSuiteDescription(Class testClass) { + return new Description(testClass.getName()); + } + + public static Description TEST_MECHANISM = new Description("Test mechanism"); + private final ArrayList fChildren= new ArrayList(); + private final String fDisplayName; + + //TODO we seem to be using the static factories exclusively + private Description(final String displayName) { + fDisplayName= displayName; + } + + /** + * @return a user-understandable label + */ + public String getDisplayName() { + return fDisplayName; + } + + /** + * Add description as a child of the receiver. + * @param description The soon-to-be child. + */ + public void addChild(Description description) { + getChildren().add(description); + } + + /** + * @return the receiver's children, if any + */ + public ArrayList getChildren() { + return fChildren; + } + + /** + * @return true if the receiver is a suite + */ + public boolean isSuite() { + return !isTest(); + } + + /** + * @return true if the receiver is an atomic test + */ + public boolean isTest() { + return getChildren().isEmpty(); + } + + /** + * @return the total number of atomic tests in the receiver + */ + public int testCount() { + if (isTest()) + return 1; + int result= 0; + for (Description child : getChildren()) + result+= child.testCount(); + return result; + } + + @Override + public int hashCode() { + return getDisplayName().hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof Description)) + return false; + Description d = (Description) obj; + return getDisplayName().equals(d.getDisplayName()) + && getChildren().equals(d.getChildren()); + } + + @Override + public String toString() { + return getDisplayName(); + } +} diff --git a/students/643449856/litejunit/src/main/java/org/v3/runner/JUnitCore.java b/students/643449856/litejunit/src/main/java/org/v3/runner/JUnitCore.java new file mode 100644 index 0000000000..adb7469365 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/runner/JUnitCore.java @@ -0,0 +1,167 @@ +package org.v3.runner; + +import java.util.ArrayList; +import java.util.List; + +import org.v3.notification.RunListener; +import org.v3.notification.RunNotifier; +import org.v3.runners.InitializationError; +import org.v3.runners.TestClassRunner; +import org.v3.runners.TextListener; + + + +/** + * JUnitCore is a facade for running tests. It supports running JUnit 4 tests, + * JUnit 3.8.2 tests, and mixtures. To run tests from the command line, run java org.junit.runner.JUnitCore TestClass1 TestClass2 .... + * For one-shot test runs, use the static method runClasses(Class... classes) + * . If you want to add special listeners, + * create an instance of JUnitCore first and use it to run the tests. + * + * @see org.junit.runner.Result + * @see org.junit.runner.notification.RunListener + * @see org.junit.runner.Request + */ +public class JUnitCore { + + private RunNotifier notifier; + + /** + * Create a new JUnitCore to run tests. + */ + public JUnitCore() { + notifier= new RunNotifier(); + } + + /** + * Run the tests contained in the classes named in the args. + * If all tests run successfully, exit with a status of 0. Otherwise exit with a status of 1. + * Write feedback while tests are running and write + * stack traces for all failed tests after the tests all complete. + * @param args names of classes in which to find tests to run + */ + /*public static void main(String... args) { + Class clz = null; + try { + clz = Class.forName(args[0]); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + return; + } + + Request request = Request.aClass(clz); + + new JUnitCore().run(request); + + Result result= new JUnitCore().runMain(args); + killAllThreads(result); + }*/ + public static void runClass(Class clz){ + try { + TestClassRunner runner = new TestClassRunner(clz); + JUnitCore core = new JUnitCore(); + core.addListener(new TextListener()); + Result result = core.run(runner); + + } catch (InitializationError e) { + + e.printStackTrace(); + } + + } + /*private static void killAllThreads(Result result) { + System.exit(result.wasSuccessful() ? 0 : 1); + }*/ + + /** + * Run the tests contained in classes. Write feedback while the tests + * are running and write stack traces for all failed tests after all tests complete. This is + * similar to main(), but intended to be used programmatically. + * @param classes Classes in which to find tests + * @return a Result describing the details of the test run and the failed tests. + */ + /*public static Result runClasses(Class... classes) { + return new JUnitCore().run(classes); + }*/ + + /** + * Do not use. Testing purposes only. + */ + /*public Result runMain(String... args) { + + List classes= new ArrayList(); + for (String each : args) + try { + classes.add(Class.forName(each)); + } catch (ClassNotFoundException e) { + System.out.println("Could not find class: " + each); + } + RunListener listener= new TextListener(); + addListener(listener); + return run(classes.toArray(new Class[0])); + }*/ + + + + /** + * Run all the tests in classes. + * @param classes the classes containing tests + * @return a Result describing the details of the test run and the failed tests. + */ + /*public Result run(Class... classes) { + return run(Request.classes("All", classes)); + }*/ + + /** + * Run all the tests contained in request. + * @param request the request describing tests + * @return a Result describing the details of the test run and the failed tests. + */ + /*public Result run(Request request) { + return run(request.getRunner()); + }*/ + + /** + * Run all the tests contained in JUnit 3.8.x test. Here for backward compatibility. + * @param test the old-style test + * @return a Result describing the details of the test run and the failed tests. + */ + /*public Result run(junit.framework.Test test) { + return run(new OldTestClassRunner(test)); + } + */ + /** + * Do not use. Testing purposes only. + */ + public Result run(Runner runner) { + Result result= new Result(); + RunListener listener= result.createListener(); + addListener(listener); + + try { + notifier.fireTestRunStarted(runner.getDescription()); + runner.run(notifier); + notifier.fireTestRunFinished(result); + } finally { + removeListener(listener); + } + return result; + } + + /** + * Add a listener to be notified as the tests run. + * @param listener the listener + * @see org.junit.runner.notification.RunListener + */ + public void addListener(RunListener listener) { + notifier.addListener(listener); + } + + /** + * Remove a listener. + * @param listener the listener to remove + */ + public void removeListener(RunListener listener) { + notifier.removeListener(listener); + } +} diff --git a/students/643449856/litejunit/src/main/java/org/v3/runner/Request.java b/students/643449856/litejunit/src/main/java/org/v3/runner/Request.java new file mode 100644 index 0000000000..0c99aba8f7 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/runner/Request.java @@ -0,0 +1,86 @@ +package org.v3.runner; + +import org.v3.requests.ClassRequest; + + + +/** + * A Request is an abstract description of tests to be run. Older versions of + * JUnit did not need such a concept--tests to be run were described either by classes containing + * tests or a tree of Tests. However, we want to support filtering and sorting, + * so we need a more abstract specification than the tests themselves and a richer + * specification than just the classes. + *

+ * The flow when JUnit runs tests is that a Request specifies some tests to be run -> + * a Runner is created for each class implied by the Request -> the Runner + * returns a detailed Description which is a tree structure of the tests to be run. + */ +public abstract class Request { + /** + * Create a Request that, when processed, will run a single test. + * This is done by filtering out all other tests. This method is used to support rerunning + * single tests. + * @param clazz the class of the test + * @param methodName the name of the test + * @return a Request that will cause a single test be run + */ + /*public static Request method(Class clazz, String methodName) { + Description method= Description.createTestDescription(clazz, methodName); + return Request.aClass(clazz).filterWith(method); + }*/ + + /** + * Create a Request that, when processed, will run all the tests + * in a class. The odd name is necessary because class is a reserved word. + * @param clazz the class containing the tests + * @return a Request that will cause all tests in the class to be run + */ + public static Request aClass(Class clazz) { + return new ClassRequest(clazz); + } + + /** + * Create a Request that, when processed, will run all the tests + * in a set of classes. + * @param collectionName a name to identify this suite of tests + * @param classes the classes containing the tests + * @return a Request that will cause all tests in the classes to be run + */ + /*public static Request classes(String collectionName, Class... classes) { + return new ClassesRequest(collectionName, classes); + }*/ + + /*public static Request errorReport(Class klass, Throwable cause) { + return new ErrorReportingRequest(klass, cause); + }*/ + + public abstract Runner getRunner(); + + /*public Request filterWith(Filter filter) { + return new FilterRequest(this, filter); + } + + public Request filterWith(final Description desiredDescription) { + return filterWith(new Filter() { + @Override + public boolean shouldRun(Description description) { + // TODO: test for equality even if we have children? + if (description.isTest()) + return desiredDescription.equals(description); + for (Description each : description.getChildren()) + if (shouldRun(each)) + return true; + return false; + } + + @Override + public String describe() { + return String.format("Method %s", desiredDescription.getDisplayName()); + } + }); + } + + public Request sortWith(Comparator comparator) { + return new SortingRequest(this, comparator); + }*/ +} diff --git a/students/643449856/litejunit/src/main/java/org/v3/runner/Result.java b/students/643449856/litejunit/src/main/java/org/v3/runner/Result.java new file mode 100644 index 0000000000..d31f986b68 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/runner/Result.java @@ -0,0 +1,98 @@ +package org.v3.runner; + +import java.util.ArrayList; +import java.util.List; + +import org.v3.notification.Failure; +import org.v3.notification.RunListener; + + +/** + * A Result collects and summarizes information from running multiple + * tests. Since tests are expected to run correctly, successful tests are only noted in + * the count of tests that ran. + */ +public class Result { + private int fCount= 0; + private int fIgnoreCount= 0; + private List fFailures= new ArrayList(); + private long fRunTime= 0; + private long fStartTime; + + /** + * @return the number of tests run + */ + public int getRunCount() { + return fCount; + } + + /** + * @return the number of tests that failed during the run + */ + public int getFailureCount() { + return fFailures.size(); + } + + /** + * @return the number of milliseconds it took to run the entire suite to run + */ + public long getRunTime() { + return fRunTime; + } + + /** + * @return the Failures describing tests that failed and the problems they encountered + */ + public List getFailures() { + return fFailures; + } + + /** + * @return the number of tests ignored during the run + */ + public int getIgnoreCount() { + return fIgnoreCount; + } + + /** + * @return true if all tests succeeded + */ + public boolean wasSuccessful() { + return getFailureCount() == 0; + } + + private class Listener extends RunListener { + @Override + public void testRunStarted(Description description) throws Exception { + fStartTime= System.currentTimeMillis(); + } + + @Override + public void testRunFinished(Result result) throws Exception { + long endTime= System.currentTimeMillis(); + fRunTime+= endTime - fStartTime; + } + + @Override + public void testStarted(Description description) throws Exception { + fCount++; + } + + @Override + public void testFailure(Failure failure) throws Exception { + fFailures.add(failure); + } + + @Override + public void testIgnored(Description description) throws Exception { + fIgnoreCount++; + } + } + + /** + * Internal use only. + */ + public RunListener createListener() { + return new Listener(); + } +} diff --git a/students/643449856/litejunit/src/main/java/org/v3/runner/ResultPrinter.java b/students/643449856/litejunit/src/main/java/org/v3/runner/ResultPrinter.java new file mode 100644 index 0000000000..af5f10dda7 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/runner/ResultPrinter.java @@ -0,0 +1,72 @@ +package org.v3.runner; + +import java.io.PrintStream; +import java.text.NumberFormat; + +import org.v3.notification.Failure; + +public class ResultPrinter { + + private final PrintStream fWriter; + + public ResultPrinter(){ + fWriter = System.out; + } + + public void print(Result result) { + printHeader(result.getRunTime()); + printFailures(result); + printFooter(result); + } + protected void printHeader(long runTime) { + getWriter().println(); + getWriter().println("Time: " + elapsedTimeAsString(runTime)); + } + + protected void printFailures(Result result) { + if (result.getFailureCount() == 0) + return; + if (result.getFailureCount() == 1) + getWriter().println("There was " + result.getFailureCount() + " failure:"); + else + getWriter().println("There were " + result.getFailureCount() + " failures:"); + int i= 1; + for (Failure each : result.getFailures()) + printFailure(each, i++); + } + + protected void printFailure(Failure failure, int count) { + printFailureHeader(failure, count); + printFailureTrace(failure); + } + + protected void printFailureHeader(Failure failure, int count) { + getWriter().println(count + ") " + failure.getTestHeader()); + } + + protected void printFailureTrace(Failure failure) { + getWriter().print(failure.getTrace()); + } + + protected void printFooter(Result result) { + if (result.wasSuccessful()) { + getWriter().println(); + getWriter().print("OK"); + getWriter().println(" (" + result.getRunCount() + " test" + (result.getRunCount() == 1 ? "" : "s") + ")"); + + } else { + getWriter().println(); + getWriter().println("FAILURES!!!"); + getWriter().println("Tests run: " + result.getRunCount() + ", Failures: " + result.getFailureCount()); + } + getWriter().println(); + } + protected String elapsedTimeAsString(long runTime) { + return NumberFormat.getInstance().format((double) runTime / 1000); + } + private PrintStream getWriter() { + return fWriter; + } + + +} diff --git a/students/643449856/litejunit/src/main/java/org/v3/runner/RunWith.java b/students/643449856/litejunit/src/main/java/org/v3/runner/RunWith.java new file mode 100644 index 0000000000..57f5f4f640 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/runner/RunWith.java @@ -0,0 +1,24 @@ +package org.v3.runner; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +//TODO add simple exampel +/** + * When you annotate a class with @RunWith, JUnit will invoke + * the class it references to run the tests in that class instead of the runner + * built into JUnit. We added this feature late in development. While it + * seems powerful we expect the runner API to change as we learn how people + * really use it. Some of the classes that are currently internal will likely be refined + * and become public. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface RunWith { + /** + * @return a Runner class (must have a constructor that takes a single Class to run) + */ + Class value(); +} diff --git a/students/643449856/litejunit/src/main/java/org/v3/runner/Runner.java b/students/643449856/litejunit/src/main/java/org/v3/runner/Runner.java new file mode 100644 index 0000000000..1b1afc80a8 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/runner/Runner.java @@ -0,0 +1,24 @@ +package org.v3.runner; + +import org.v3.notification.RunNotifier; + + +public abstract class Runner { + /** + * @return a Description showing the tests to be run by the receiver + */ + public abstract Description getDescription(); + + /** + * Run the tests for this runner. + * @param notifier will be notified of events while tests are being run--tests being started, finishing, and failing + */ + public abstract void run(RunNotifier notifier); + + /** + * @return the number of tests to be run by the receiver + */ + public int testCount() { + return getDescription().testCount(); + } +} \ No newline at end of file diff --git a/students/643449856/litejunit/src/main/java/org/v3/runners/BeforeAndAfterRunner.java b/students/643449856/litejunit/src/main/java/org/v3/runners/BeforeAndAfterRunner.java new file mode 100644 index 0000000000..e23a1e7cca --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/runners/BeforeAndAfterRunner.java @@ -0,0 +1,75 @@ +package org.v3.runners; + +import java.lang.annotation.Annotation; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; + +public abstract class BeforeAndAfterRunner { + private static class FailedBefore extends Exception { + private static final long serialVersionUID= 1L; + } + + private final Class beforeAnnotation; + + private final Class afterAnnotation; + + private TestIntrospector testIntrospector; + + private Object test; + + public BeforeAndAfterRunner(Class testClass, + Class beforeAnnotation, + Class afterAnnotation, + Object test) { + this.beforeAnnotation= beforeAnnotation; + this.afterAnnotation= afterAnnotation; + this.testIntrospector= new TestIntrospector(testClass); + this.test= test; + } + + public void runProtected() { + try { + runBefores(); + runUnprotected(); + } catch (FailedBefore e) { + } finally { + runAfters(); + } + } + + protected abstract void runUnprotected(); + + protected abstract void addFailure(Throwable targetException); + + // Stop after first failed @Before + private void runBefores() throws FailedBefore { + try { + List befores= testIntrospector.getTestMethods(beforeAnnotation); + for (Method before : befores) + invokeMethod(before); + } catch (InvocationTargetException e) { + addFailure(e.getTargetException()); + throw new FailedBefore(); + } catch (Throwable e) { + addFailure(e); + throw new FailedBefore(); + } + } + + private void runAfters() { + List afters= testIntrospector.getTestMethods(afterAnnotation); + for (Method after : afters) + try { + invokeMethod(after); + } catch (InvocationTargetException e) { + addFailure(e.getTargetException()); + } catch (Throwable e) { + addFailure(e); // Untested, but seems impossible + } + } + + private void invokeMethod(Method method) throws Exception { + method.invoke(test); + } +} diff --git a/students/643449856/litejunit/src/main/java/org/v3/runners/InitializationError.java b/students/643449856/litejunit/src/main/java/org/v3/runners/InitializationError.java new file mode 100644 index 0000000000..a7b4bf87fc --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/runners/InitializationError.java @@ -0,0 +1,25 @@ +package org.v3.runners; + +import java.util.Arrays; +import java.util.List; + +public class InitializationError extends Exception { + private static final long serialVersionUID= 1L; + private final List fErrors; + + public InitializationError(List errors) { + fErrors= errors; + } + + public InitializationError(Throwable... errors) { + this(Arrays.asList(errors)); + } + + public InitializationError(String string) { + this(new Exception(string)); + } + + public List getCauses() { + return fErrors; + } +} diff --git a/students/643449856/litejunit/src/main/java/org/v3/runners/TestClassMethodsRunner.java b/students/643449856/litejunit/src/main/java/org/v3/runners/TestClassMethodsRunner.java new file mode 100644 index 0000000000..0ff73d816d --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/runners/TestClassMethodsRunner.java @@ -0,0 +1,78 @@ +package org.v3.runners; + +import java.lang.reflect.Method; +import java.util.List; + +import org.v3.Test; +import org.v3.notification.Failure; +import org.v3.notification.RunNotifier; +import org.v3.runner.Description; +import org.v3.runner.Runner; + + + +public class TestClassMethodsRunner extends Runner { + private final List testMethods; + private final Class testClass; + + public TestClassMethodsRunner(Class klass) { + testClass= klass; + testMethods= new TestIntrospector(testClass).getTestMethods(Test.class); + } + + @Override + public void run(RunNotifier notifier) { + /*if (testMethods.isEmpty()) + testAborted(notifier, getDescription());*/ + for (Method method : testMethods) + invokeTestMethod(method, notifier); + } + + + + @Override + public Description getDescription() { + Description spec= Description.createSuiteDescription(getName()); + List testMethods= this.testMethods; + for (Method method : testMethods) + spec.addChild(methodDescription(method)); + return spec; + } + + protected String getName() { + return getTestClass().getName(); + } + + protected Object createTest() throws Exception { + return getTestClass().getConstructor().newInstance(); + } + + protected void invokeTestMethod(Method method, RunNotifier notifier) { + Object test; + try { + test= createTest(); + } catch (Exception e) { + //testAborted(notifier, methodDescription(method)); + return; + } + createMethodRunner(test, method, notifier).run(); + } + + protected TestMethodRunner createMethodRunner(Object test, Method method, RunNotifier notifier) { + return new TestMethodRunner(test, method, notifier, methodDescription(method)); + } + + protected String testName(Method method) { + return method.getName(); + } + + protected Description methodDescription(Method method) { + return Description.createTestDescription(getTestClass(), testName(method)); + } + + + + protected Class getTestClass() { + return testClass; + } +} \ No newline at end of file diff --git a/students/643449856/litejunit/src/main/java/org/v3/runners/TestClassRunner.java b/students/643449856/litejunit/src/main/java/org/v3/runners/TestClassRunner.java new file mode 100644 index 0000000000..c79ec0ffdb --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/runners/TestClassRunner.java @@ -0,0 +1,53 @@ +package org.v3.runners; + +import org.v3.AfterClass; +import org.v3.BeforeClass; +import org.v3.notification.Failure; +import org.v3.notification.RunNotifier; +import org.v3.runner.Description; +import org.v3.runner.Runner; + +public class TestClassRunner extends Runner { + protected final Runner enclosedRunner; + private final Class testClass; + + public TestClassRunner(Class klass) throws InitializationError { + this(klass, new TestClassMethodsRunner(klass)); + } + + public TestClassRunner(Class klass, Runner runner) throws InitializationError { + testClass= klass; + enclosedRunner= runner; + + } + + + + @Override + public void run(final RunNotifier notifier) { + BeforeAndAfterRunner runner = new BeforeAndAfterRunner(getTestClass(), + BeforeClass.class, AfterClass.class, null) { + @Override + protected void runUnprotected() { + enclosedRunner.run(notifier); + } + + // TODO: looks very similar to other method of BeforeAfter, now + @Override + protected void addFailure(Throwable targetException) { + notifier.fireTestFailure(new Failure(getDescription(), targetException)); + } + }; + + runner.runProtected(); + } + + @Override + public Description getDescription() { + return enclosedRunner.getDescription(); + } + + protected Class getTestClass() { + return testClass; + } +} diff --git a/students/643449856/litejunit/src/main/java/org/v3/runners/TestIntrospector.java b/students/643449856/litejunit/src/main/java/org/v3/runners/TestIntrospector.java new file mode 100644 index 0000000000..ba51b21c9b --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/runners/TestIntrospector.java @@ -0,0 +1,74 @@ +package org.v3.runners; + + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.v3.Before; +import org.v3.BeforeClass; +import org.v3.Ignore; +import org.v3.Test; +import org.v3.Test.None; + + + +public class TestIntrospector { + private final Class< ?> testClass; + + public TestIntrospector(Class testClass) { + this.testClass= testClass; + } + + public List getTestMethods(Class annotationClass) { + List results= new ArrayList(); + + //for (Class eachClass : getSuperClasses(testClass)) { + Method[] methods= testClass.getDeclaredMethods(); + for (Method method : methods) { + Annotation annotation= method.getAnnotation(annotationClass); + if (annotation != null && ! isShadowed(method, results)) + results.add(method); + } + //} + if (runsTopToBottom(annotationClass)) + Collections.reverse(results); + return results; + } + + public boolean isIgnored(Method eachMethod) { + return eachMethod.getAnnotation(Ignore.class) != null; + } + + private boolean runsTopToBottom(Class< ? extends Annotation> annotation) { + return annotation.equals(Before.class) || annotation.equals(BeforeClass.class); + } + + private boolean isShadowed(Method method, List results) { + for (Method m : results) { + if (m.getName().equals(method.getName())) + return true; + } + return false; + } + + + + long getTimeout(Method method) { + Test annotation= method.getAnnotation(Test.class); + long timeout= annotation.timeout(); + return timeout; + } + + Class expectedException(Method method) { + Test annotation= method.getAnnotation(Test.class); + if (annotation.expected() == None.class) + return null; + else + return annotation.expected(); + } + +} + diff --git a/students/643449856/litejunit/src/main/java/org/v3/runners/TestMethodRunner.java b/students/643449856/litejunit/src/main/java/org/v3/runners/TestMethodRunner.java new file mode 100644 index 0000000000..777c98cb1c --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/runners/TestMethodRunner.java @@ -0,0 +1,86 @@ +package org.v3.runners; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + + +import org.v3.After; +import org.v3.Before; +import org.v3.notification.Failure; +import org.v3.notification.RunNotifier; +import org.v3.runner.Description; + + + +public class TestMethodRunner extends BeforeAndAfterRunner { + private final Object test; + private final Method method; + private final RunNotifier notifier; + private final TestIntrospector testIntrospector; + private final Description description; + + public TestMethodRunner(Object test, Method method, RunNotifier notifier, Description description) { + super(test.getClass(), Before.class, After.class, test); + this.test= test; + this.method= method; + this.notifier= notifier; + testIntrospector= new TestIntrospector(test.getClass()); + this.description= description; + } + + public void run() { + /*if (testIntrospector.isIgnored(method)) { + notifier.fireTestIgnored(description); + return; + }*/ + notifier.fireTestStarted(description); + try { + /*long timeout= testIntrospector.getTimeout(method); + if (timeout > 0) + runWithTimeout(timeout); + else*/ + runMethod(); + } finally { + notifier.fireTestFinished(description); + } + } + + + + private void runMethod() { + runProtected(); + } + + @Override + protected void runUnprotected() { + try { + executeMethodBody(); + /*if (expectsException()) + addFailure(new AssertionError("Expected exception: " + expectedException().getName()));*/ + } catch (InvocationTargetException e) { + addFailure(e); + /*Throwable actual= e.getTargetException(); + if (!expectsException()) + addFailure(actual); + else if (isUnexpected(actual)) { + String message= "Unexpected exception, expected<" + expectedException().getName() + "> but was<" + + actual.getClass().getName() + ">"; + addFailure(new Exception(message, actual)); + }*/ + } catch (Throwable e) { + addFailure(e); + } + } + + protected void executeMethodBody() throws IllegalAccessException, InvocationTargetException { + method.invoke(test); + } + + @Override + protected void addFailure(Throwable e) { + notifier.fireTestFailure(new Failure(description, e)); + } + + +} + diff --git a/students/643449856/litejunit/src/main/java/org/v3/runners/TextListener.java b/students/643449856/litejunit/src/main/java/org/v3/runners/TextListener.java new file mode 100644 index 0000000000..b52d6fc024 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/runners/TextListener.java @@ -0,0 +1,103 @@ +package org.v3.runners; + +import java.io.PrintStream; +import java.text.NumberFormat; + +import org.v3.notification.Failure; +import org.v3.notification.RunListener; +import org.v3.runner.Description; +import org.v3.runner.Result; + + + +public class TextListener extends RunListener { + + private final PrintStream writer; + + public TextListener() { + this(System.out); + } + + public TextListener(PrintStream writer) { + this.writer= writer; + } + + @Override + public void testRunFinished(Result result) { + printHeader(result.getRunTime()); + printFailures(result); + printFooter(result); + } + + @Override + public void testStarted(Description description) { + writer.append('.'); + } + + @Override + public void testFailure(Failure failure) { + writer.append('E'); + } + + @Override + public void testIgnored(Description description) { + writer.append('I'); + } + + /* + * Internal methods + */ + + private PrintStream getWriter() { + return writer; + } + + protected void printHeader(long runTime) { + getWriter().println(); + getWriter().println("Time: " + elapsedTimeAsString(runTime)); + } + + protected void printFailures(Result result) { + if (result.getFailureCount() == 0) + return; + if (result.getFailureCount() == 1) + getWriter().println("There was " + result.getFailureCount() + " failure:"); + else + getWriter().println("There were " + result.getFailureCount() + " failures:"); + int i= 1; + for (Failure each : result.getFailures()) + printFailure(each, i++); + } + + protected void printFailure(Failure failure, int count) { + printFailureHeader(failure, count); + printFailureTrace(failure); + } + + protected void printFailureHeader(Failure failure, int count) { + getWriter().println(count + ") " + failure.getTestHeader()); + } + + protected void printFailureTrace(Failure failure) { + getWriter().print(failure.getTrace()); + } + + protected void printFooter(Result result) { + if (result.wasSuccessful()) { + getWriter().println(); + getWriter().print("OK"); + getWriter().println(" (" + result.getRunCount() + " test" + (result.getRunCount() == 1 ? "" : "s") + ")"); + + } else { + getWriter().println(); + getWriter().println("FAILURES!!!"); + getWriter().println("Tests run: " + result.getRunCount() + ", Failures: " + result.getFailureCount()); + } + getWriter().println(); + } + + + protected String elapsedTimeAsString(long runTime) { + return NumberFormat.getInstance().format((double) runTime / 1000); + } +} diff --git a/students/643449856/litejunit/src/main/java/org/v3/sample/Calculator.java b/students/643449856/litejunit/src/main/java/org/v3/sample/Calculator.java new file mode 100644 index 0000000000..7bd3759dc1 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/sample/Calculator.java @@ -0,0 +1,22 @@ +package org.v3.sample; + +public class Calculator { + + private int result = 0; + public void add(int x){ + result += x; + } + public void subtract(int x){ + result -=x; + } + + public int getResult(){ + return this.result; + } + public static void main(String[] args){ + Calculator calculator = new Calculator(); + calculator.add(10); + calculator.subtract(5); + System.out.println(calculator.getResult()); + } +} diff --git a/students/643449856/litejunit/src/main/java/org/v3/sample/CalculatorTest.java b/students/643449856/litejunit/src/main/java/org/v3/sample/CalculatorTest.java new file mode 100644 index 0000000000..0dbbaf7cc5 --- /dev/null +++ b/students/643449856/litejunit/src/main/java/org/v3/sample/CalculatorTest.java @@ -0,0 +1,52 @@ +package org.v3.sample; + +import org.v3.After; +import org.v3.AfterClass; +import org.v3.Before; +import org.v3.BeforeClass; +import org.v3.Test; +import org.v3.runner.JUnitCore; +import static org.v3.Assert.assertEquals; + +/** + * @author neng + * + */ +public class CalculatorTest { + + Calculator calculator =null; + @Before + public void prepare(){ + calculator = new Calculator(); + } + @After + public void clean(){ + calculator = null; + } + @Test + public void testAdd(){ + + calculator.add(10); + assertEquals(15,calculator.getResult()); + } + @Test + public void testSubtract(){ + calculator.add(10); + calculator.subtract(5); + assertEquals(5,calculator.getResult()); + } + @BeforeClass + public static void prepareGlobalResouce(){ + System.err.println("准备所有的资源"); + } + @AfterClass + public static void cleanGlobalResouce(){ + System.err.println("清楚所有的资源"); + } + + + public static void main(String[] args){ + JUnitCore.runClass(CalculatorTest.class); + + } +} diff --git a/students/643449856/ood-assignment/pom.xml b/students/643449856/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/643449856/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..16fab6a29c --- /dev/null +++ b/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,33 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + + public Configuration() { + this.smtpHost = ConfigurationKeys.SMTP_SERVER; + this.altSmtpHost = ConfigurationKeys.ALT_SMTP_SERVER; + this.fromAddress = ConfigurationKeys.EMAIL_ADMIN; + } + + static Map configurations = new HashMap(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..20f1e74cfe --- /dev/null +++ b/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,46 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + private static String sendMailQuery = null; + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } + + public static String setLoadQuery(String productID) throws Exception { + + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + return sendMailQuery; + } + + + static List loadMailingList() throws Exception { + return DBUtil.query(sendMailQuery); + } + + +} diff --git a/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtil.java b/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtil.java new file mode 100644 index 0000000000..0ebb9c014e --- /dev/null +++ b/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtil.java @@ -0,0 +1,35 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +/** + * Created by nengneng on 2017/6/19. + */ +public class FileUtil { + + + static void readFile(File file,Product product) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + product.setProductID(data[0]); + product.setProductDesc(data[1]); + + System.out.println("产品ID = " + product.getProductID() + "\n"); + System.out.println("产品描述 = " + product.getProductDesc() + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + +} diff --git a/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java b/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java new file mode 100644 index 0000000000..e7ad19ce67 --- /dev/null +++ b/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java @@ -0,0 +1,87 @@ +package com.coderising.ood.srp; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +/** + * Created by nengneng on 2017/6/19. + */ +public class Mail { + + private String fromAddress; + private String toAddress; + private String subject; + private String message; + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + public Mail(){ + + } + + public Mail(String fromAddress, String toAddress, String subject, String message) { + this.fromAddress = fromAddress; + this.toAddress = toAddress; + this.subject = subject; + this.message = message; + } + + public static String getNameKey() { + return NAME_KEY; + } + + public static String getEmailKey() { + return EMAIL_KEY; + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + private void setMessage(HashMap userInfo, Product product) throws IOException + { + String name = (String) userInfo.get(NAME_KEY); + this.subject = "您关注的产品降价了"; + this.message = "尊敬的 "+name+", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!" ; + } + + + + + + + + +} diff --git a/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..453707bbf0 --- /dev/null +++ b/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,84 @@ +package com.coderising.ood.srp; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class MailUtil { + + + + + public static void sendEmail(Mail mail,String smtpHost,HashMap userInfo, + Product product, boolean debug) throws IOException { + mail.setMessage(userInfo, product); + String email = encapsulation(mail); + System.out.println(email.toString()); + } + + private static String encapsulation(Mail mail) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(mail.getFromAddress()).append("\n"); + buffer.append("To:").append(mail.getToAddress()).append("\n"); + buffer.append("Subject:").append(mail.getSubject()).append("\n"); + buffer.append("Content:").append(mail.getMessage()).append("\n"); + return buffer.toString(); + + } + + public void configureEMail(HashMap userInfo,Mail mail) throws IOException + { + mail.getToAddress() = (String) userInfo.get(Mail.getEmailKey()); + if (toAddress.length() > 0) + setMessage(userInfo.toString()); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + + send(mailingList); + + } + + else { + System.out.println("没有邮件发送"); + + } + + } + + public void send(List mailingList,Mail mail){ + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + Mail.configureEMail((HashMap) iter.next()); + try + { + if (toAddress.length() > 0) + MailUtil.sendEmail(mail, smtpHost, debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } + + +} diff --git a/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java b/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..c13f0cc294 --- /dev/null +++ b/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,34 @@ +package com.coderising.ood.srp; + +/** + * Created by nengneng on 2017/6/19. + */ +public class Product { + + private String productID; + private String productDesc; + + public Product(String productID, String productDesc) { + this.productID = productID; + this.productDesc = productDesc; + } + + public Product() { + } + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git a/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..7670f87c29 --- /dev/null +++ b/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,61 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + private static Configuration config; + + + + + + + public static void main(String[] args) throws Exception { + + File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, Product product,boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + FileUtil.readFile(file, product); + config = new Configuration(); + DBUtil.setLoadQuery(product.getProductID()); + sendEMails(mailDebug, DBUtil.loadMailingList()); + + + } + + + + + + + + + + + + + + + + + + + + + +} diff --git a/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/643449856/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/643449856/payrolla/pom.xml b/students/643449856/payrolla/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/643449856/payrolla/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/643449856/payrolla/src/main/java/com/Affiliation/NonAffiliation.java b/students/643449856/payrolla/src/main/java/com/Affiliation/NonAffiliation.java new file mode 100644 index 0000000000..07d0b186a4 --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/Affiliation/NonAffiliation.java @@ -0,0 +1,20 @@ +package com.Affiliation; + +import com.pojo.Affiliation; +import com.pojo.Paycheck; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 20:20 + * + * 没有联系 + */ +public class NonAffiliation implements Affiliation { + + + @Override + public double calculateDeductions(Paycheck pc) { + return 0.0; + } +} diff --git a/students/643449856/payrolla/src/main/java/com/Affiliation/UnionAffiliation.java b/students/643449856/payrolla/src/main/java/com/Affiliation/UnionAffiliation.java new file mode 100644 index 0000000000..cb22e697f3 --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/Affiliation/UnionAffiliation.java @@ -0,0 +1,18 @@ +package com.Affiliation; + +import com.pojo.Affiliation; +import com.pojo.Paycheck; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 20:21 + */ +public class UnionAffiliation implements Affiliation { + + + @Override + public double calculateDeductions(Paycheck pc) { + return 0; + } +} diff --git a/students/643449856/payrolla/src/main/java/com/Classification/CommissionedClassification.java b/students/643449856/payrolla/src/main/java/com/Classification/CommissionedClassification.java new file mode 100644 index 0000000000..6979d8a513 --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/Classification/CommissionedClassification.java @@ -0,0 +1,46 @@ +package com.Classification; + +import com.pojo.Paycheck; +import com.pojo.PaymentClassification; +import com.util.DateUtil; +import com.pojo.SalesReceipt; + +import java.util.Date; +import java.util.Map; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 20:22 + * + * 销售 + */ +public class CommissionedClassification implements PaymentClassification { + + double salary; + double rate; + + Map receipts; + + + + + public CommissionedClassification(double salary , double rate){ + this.salary = salary; + this.rate = rate; + } + + + + @Override + public double calculatePay(Paycheck pc) { + double commission = 0.0; + for(SalesReceipt sr : receipts.values()){ + if(DateUtil.between(sr.getSaleDate(), pc.getPayPeriodStartDate(), + pc.getPayPeriodEndDate())){ + commission += sr.getAmount() * rate; + } + } + return salary + commission; + } +} diff --git a/students/643449856/payrolla/src/main/java/com/Classification/HourlyClassification.java b/students/643449856/payrolla/src/main/java/com/Classification/HourlyClassification.java new file mode 100644 index 0000000000..d3de75ce52 --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/Classification/HourlyClassification.java @@ -0,0 +1,59 @@ +package com.Classification; + +import com.pojo.Paycheck; +import com.pojo.PaymentClassification; +import com.pojo.TimeCard; +import com.util.DateUtil; + +import java.util.Date; +import java.util.Map; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 20:39 + *

+ * 小时工 + */ +public class HourlyClassification implements PaymentClassification { + + + private double rate; + + private Map timeCards; + + + + public HourlyClassification(double hourlyRate) { + this.rate = hourlyRate; + } + + @Override + + public double calculatePay(Paycheck pc) { + + double totalPay = 0; + for (TimeCard t : timeCards.values()) { + if(DateUtil.between(t.getDate(), pc.getPayPeriodStartDate(), + pc.getPayPeriodEndDate())){ + totalPay += calculatePayForTimeCard(t); + } + } + return 0; + } + + public void addTimeCard(TimeCard tc){ + timeCards.put(tc.getDate(), tc); + } + + + private double calculatePayForTimeCard(TimeCard tc) { + int hours = tc.getHours(); + + if(hours > 8){ + return 8*rate + (hours-8) * rate * 1.5; + } else{ + return 8*rate; + } + } +} diff --git a/students/643449856/payrolla/src/main/java/com/Classification/SalariedClassification.java b/students/643449856/payrolla/src/main/java/com/Classification/SalariedClassification.java new file mode 100644 index 0000000000..6abda7048d --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/Classification/SalariedClassification.java @@ -0,0 +1,25 @@ +package com.Classification; + +import com.pojo.Paycheck; +import com.pojo.PaymentClassification; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 20:57 + * + * 雇佣工 + */ +public class SalariedClassification implements PaymentClassification { + + private double salary; + public SalariedClassification(double salary){ + this.salary = salary; + } + + + @Override + public double calculatePay(Paycheck pc) { + return salary; + } +} diff --git a/students/643449856/payrolla/src/main/java/com/PaymentMethod/BankMethod.java b/students/643449856/payrolla/src/main/java/com/PaymentMethod/BankMethod.java new file mode 100644 index 0000000000..92622b437a --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/PaymentMethod/BankMethod.java @@ -0,0 +1,21 @@ +package com.PaymentMethod; + +import com.pojo.Paycheck; +import com.pojo.PaymentMethod; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 20:18 + * + * 从银行直接取 + * + */ +public class BankMethod implements PaymentMethod { + + + @Override + public void pay(Paycheck pc) { + + } +} diff --git a/students/643449856/payrolla/src/main/java/com/PaymentMethod/HoldMethod.java b/students/643449856/payrolla/src/main/java/com/PaymentMethod/HoldMethod.java new file mode 100644 index 0000000000..b0120bab7e --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/PaymentMethod/HoldMethod.java @@ -0,0 +1,24 @@ +package com.PaymentMethod; + +import com.pojo.Paycheck; +import com.pojo.PaymentMethod; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 20:18 + * + * 从银行直接取 + * + */ +public class HoldMethod implements PaymentMethod { + + + @Override + public void pay(Paycheck pc) { + System.out.println("工资保存在财务那,可随时支取"); + System.out.println("应付" + pc.getGrossPay()); + System.out.println("扣除" + pc.getDeductions()); + System.out.println("实付" + pc.getNetPay()); + } +} diff --git a/students/643449856/payrolla/src/main/java/com/PaymentMethod/MailMethod.java b/students/643449856/payrolla/src/main/java/com/PaymentMethod/MailMethod.java new file mode 100644 index 0000000000..dffcedcf03 --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/PaymentMethod/MailMethod.java @@ -0,0 +1,30 @@ +package com.PaymentMethod; + +import com.pojo.Paycheck; +import com.pojo.PaymentMethod; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 20:18 + * + * 从银行直接取 + * + */ +public class MailMethod implements PaymentMethod { + private String address = ""; + + + public MailMethod(String address) { + super(); + this.address = address; + } + + @Override + public void pay(Paycheck pc) { + System.out.println("已将支票邮寄到"+address); + System.out.println("应付" + pc.getGrossPay()); + System.out.println("扣除" + pc.getDeductions()); + System.out.println("实付" + pc.getNetPay()); + } +} diff --git a/students/643449856/payrolla/src/main/java/com/PayrollService.java b/students/643449856/payrolla/src/main/java/com/PayrollService.java new file mode 100644 index 0000000000..349c7bbf1d --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/PayrollService.java @@ -0,0 +1,82 @@ +package com; + +import com.Classification.CommissionedClassification; +import com.Classification.HourlyClassification; +import com.Classification.SalariedClassification; +import com.PaymentMethod.BankMethod; +import com.PaymentMethod.MailMethod; +import com.Schedule.BiweeklySchedule; +import com.Schedule.MonthlySchedule; +import com.Schedule.WeeklySchedule; +import com.pojo.Employee; +import com.PaymentMethod.HoldMethod; +import com.pojo.Paycheck; + +import java.util.List; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 21:11 + */ +public class PayrollService { + + + public List getAllEmployees(){ + return null; + } + + public void savePaycheck(Paycheck pc){ + + } + + /** + * 添加小时工 + * @param name + * @param address + * @param hourlyRate + * @return + */ + public Employee addHourlyEmployee(String name, String address, double hourlyRate){ + Employee e = new Employee(name, address); + e.setClassification(new HourlyClassification(hourlyRate)); + e.setSchedule(new WeeklySchedule()); + e.setPaymentMethod(new HoldMethod()); + return e; + } + + + /** + * 添加固定工资员工 + * @param name + * @param address + * @param salary + * @return + */ + public Employee addSalariedEmployee(String name, String address, double salary){ + Employee e = new Employee(name, address); + e.setClassification(new SalariedClassification(salary)); + e.setSchedule(new MonthlySchedule()); + e.setPaymentMethod(new BankMethod()); + return e; + } + + + /** + * 添加销售员工 + * @param name + * @param address + * @param salary + * @param saleRate + * @return + */ + public Employee addCommissionedEmployee(String name, String address, double salary, double saleRate){ + Employee e = new Employee(name, address); + e.setClassification(new CommissionedClassification(salary, saleRate)); + e.setSchedule(new BiweeklySchedule()); + e.setPaymentMethod(new MailMethod()); + return e; + } + + +} diff --git a/students/643449856/payrolla/src/main/java/com/Schedule/BiweeklySchedule.java b/students/643449856/payrolla/src/main/java/com/Schedule/BiweeklySchedule.java new file mode 100644 index 0000000000..b256862b19 --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/Schedule/BiweeklySchedule.java @@ -0,0 +1,49 @@ +package com.Schedule; + +import com.pojo.PaymentSchedule; +import com.util.DateUtil; + +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 20:29 + * + * 每隔一周支付 + */ +public class BiweeklySchedule implements PaymentSchedule { + + + /** + * 上一次支付的日期 + */ + Date firstPayableFriday = DateUtil.parseDate("2017-6-2"); + + + @Override + public boolean isPayDay(Date date) { + long interval = DateUtil.getDaysBetween(firstPayableFriday, date); + return interval % 14 == 0; + } + + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.add(payPeriodEndDate, -13); + } + + + public static void main(String [] args) throws Exception{ + BiweeklySchedule schedule = new BiweeklySchedule(); + + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); + Date d = sdf.parse("2017-06-30"); + + System.out.println(schedule.isPayDay(d)); + + System.out.println(DateUtil.isFriday(d)); + + System.out.println(schedule.getPayPeriodStartDate(d)); + } +} diff --git a/students/643449856/payrolla/src/main/java/com/Schedule/MonthlySchedule.java b/students/643449856/payrolla/src/main/java/com/Schedule/MonthlySchedule.java new file mode 100644 index 0000000000..f3535d6246 --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/Schedule/MonthlySchedule.java @@ -0,0 +1,27 @@ +package com.Schedule; + +import com.pojo.PaymentSchedule; +import com.util.DateUtil; + +import java.util.Date; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 20:33 + * + * 每月的最后一天支付 + */ +public class MonthlySchedule implements PaymentSchedule { + + + @Override + public boolean isPayDay(Date date) { + return DateUtil.isLastDayOfMonth(date); + } + + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.getFirstDay(payPeriodEndDate); + } +} diff --git a/students/643449856/payrolla/src/main/java/com/Schedule/WeeklySchedule.java b/students/643449856/payrolla/src/main/java/com/Schedule/WeeklySchedule.java new file mode 100644 index 0000000000..46945e649a --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/Schedule/WeeklySchedule.java @@ -0,0 +1,27 @@ +package com.Schedule; + +import com.pojo.PaymentSchedule; +import com.util.DateUtil; + +import java.util.Date; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 20:35 + * + * 每周五支付 + */ +public class WeeklySchedule implements PaymentSchedule { + + + @Override + public boolean isPayDay(Date date) { + return DateUtil.isFriday(date); + } + + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.add(payPeriodEndDate, -6); + } +} diff --git a/students/643449856/payrolla/src/main/java/com/pojo/Affiliation.java b/students/643449856/payrolla/src/main/java/com/pojo/Affiliation.java new file mode 100644 index 0000000000..1ba6f8b642 --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/pojo/Affiliation.java @@ -0,0 +1,15 @@ +package com.pojo; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 20:07 + *

+ * 从属关系 + */ + + +public interface Affiliation { + + public double calculateDeductions(Paycheck pc); +} diff --git a/students/643449856/payrolla/src/main/java/com/pojo/Employee.java b/students/643449856/payrolla/src/main/java/com/pojo/Employee.java new file mode 100644 index 0000000000..18ff043561 --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/pojo/Employee.java @@ -0,0 +1,118 @@ +package com.pojo; + +import java.util.Date; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 17:22 + */ +public class Employee { + + private String id; + private String name; + private String address; + private Affiliation affiliation; + + + private PaymentClassification classification; + private PaymentSchedule schedule; + private PaymentMethod paymentMethod; + + public Employee(String name, String address){ + this.name = name; + this.address = address; + } + + + /** + * 是不是支付日 + * @param d + * @return + */ + public boolean isPayDay(Date d) { + return this.schedule.isPayDay(d); + } + + + /** + * 得到支付开始的日期 + * @param d + * @return + */ + public Date getPayPeriodStartDate(Date d) { + return this.schedule.getPayPeriodStartDate(d); + } + + + /** + * 计算工资 + * @param pc + */ + public void payDay(Paycheck pc){ + double grossPay = classification.calculatePay(pc); + double deductions = affiliation.calculateDeductions(pc); + double netPay = grossPay - deductions; + pc.setGrossPay(grossPay); + pc.setDeductions(deductions); + pc.setNetPay(netPay); + paymentMethod.pay(pc); + } + + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public Affiliation getAffiliation() { + return affiliation; + } + + public void setAffiliation(Affiliation affiliation) { + this.affiliation = affiliation; + } + + public PaymentClassification getClassification() { + return classification; + } + + public void setClassification(PaymentClassification classification) { + this.classification = classification; + } + + public PaymentSchedule getSchedule() { + return schedule; + } + + public void setSchedule(PaymentSchedule schedule) { + this.schedule = schedule; + } + + public PaymentMethod getPaymentMethod() { + return paymentMethod; + } + + public void setPaymentMethod(PaymentMethod paymentMethod) { + this.paymentMethod = paymentMethod; + } +} diff --git a/students/643449856/payrolla/src/main/java/com/pojo/Paycheck.java b/students/643449856/payrolla/src/main/java/com/pojo/Paycheck.java new file mode 100644 index 0000000000..de903ca166 --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/pojo/Paycheck.java @@ -0,0 +1,84 @@ +package com.pojo; + +import java.util.Date; +import java.util.Map; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 20:07 + * 薪水 + */ +public class Paycheck { + + private Date payPeriodStart; + private Date payPeriodEnd; + private double grossPay; // 应发工资 + private double netPay; // 实付工资 + private double deductions; // 扣除工资 + private Map itsFields; + + public Paycheck(Date payPeriodStart, Date payPeriodEnd){ + this.payPeriodStart = payPeriodStart; + this.payPeriodEnd = payPeriodEnd; + } + + public void setGrossPay(double grossPay) { + this.grossPay = grossPay; + + } + + public void setDeductions(double deductions) { + this.deductions = deductions; + } + + public void setNetPay(double netPay){ + this.netPay = netPay; + } + + public Date getPayPeriodEndDate() { + + return this.payPeriodEnd; + } + public Date getPayPeriodStartDate() { + + return this.payPeriodStart; + } + + + public Date getPayPeriodStart() { + return payPeriodStart; + } + + public void setPayPeriodStart(Date payPeriodStart) { + this.payPeriodStart = payPeriodStart; + } + + public Date getPayPeriodEnd() { + return payPeriodEnd; + } + + public void setPayPeriodEnd(Date payPeriodEnd) { + this.payPeriodEnd = payPeriodEnd; + } + + public double getGrossPay() { + return grossPay; + } + + public double getNetPay() { + return netPay; + } + + public double getDeductions() { + return deductions; + } + + public Map getItsFields() { + return itsFields; + } + + public void setItsFields(Map itsFields) { + this.itsFields = itsFields; + } +} diff --git a/students/643449856/payrolla/src/main/java/com/pojo/PaymentClassification.java b/students/643449856/payrolla/src/main/java/com/pojo/PaymentClassification.java new file mode 100644 index 0000000000..0c83ad56ab --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/pojo/PaymentClassification.java @@ -0,0 +1,18 @@ +package com.pojo; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 20:17 + * + * 付款分类 + */ +public interface PaymentClassification { + + /** + * 计算应该支付的工资 + * @param pc + * @return + */ + public double calculatePay(Paycheck pc); +} diff --git a/students/643449856/payrolla/src/main/java/com/pojo/PaymentMethod.java b/students/643449856/payrolla/src/main/java/com/pojo/PaymentMethod.java new file mode 100644 index 0000000000..d805f0413e --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/pojo/PaymentMethod.java @@ -0,0 +1,14 @@ +package com.pojo; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 20:15 + * 付款方法 + */ +public interface PaymentMethod { + + public void pay(Paycheck pc); + + +} diff --git a/students/643449856/payrolla/src/main/java/com/pojo/PaymentSchedule.java b/students/643449856/payrolla/src/main/java/com/pojo/PaymentSchedule.java new file mode 100644 index 0000000000..7d3c7a78d8 --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/pojo/PaymentSchedule.java @@ -0,0 +1,21 @@ +package com.pojo; + +import java.util.Date; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 20:14 + *

+ * 付款日期表 + */ +public interface PaymentSchedule { + + /** + * 是否是付款日 + * @param date + * @return + */ + public boolean isPayDay(Date date); + public Date getPayPeriodStartDate( Date payPeriodEndDate); +} diff --git a/students/643449856/payrolla/src/main/java/com/pojo/SalesReceipt.java b/students/643449856/payrolla/src/main/java/com/pojo/SalesReceipt.java new file mode 100644 index 0000000000..f9700bca80 --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/pojo/SalesReceipt.java @@ -0,0 +1,22 @@ +package com.pojo; + +import java.util.Date; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 20:13 + *

+ * 销售数据 + */ +public class SalesReceipt { + + private Date saleDate; + private double amount; + public Date getSaleDate() { + return saleDate; + } + public double getAmount() { + return amount; + } +} diff --git a/students/643449856/payrolla/src/main/java/com/pojo/TimeCard.java b/students/643449856/payrolla/src/main/java/com/pojo/TimeCard.java new file mode 100644 index 0000000000..b581e0bf87 --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/pojo/TimeCard.java @@ -0,0 +1,23 @@ +package com.pojo; + +import java.util.Date; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 20:13 + * 时间卡片 + */ +public class TimeCard { + + + private Date date; + private int hours; + + public Date getDate() { + return date; + } + public int getHours() { + return hours; + } +} diff --git a/students/643449856/payrolla/src/main/java/com/transaction/AddEmployeeTransaction.java b/students/643449856/payrolla/src/main/java/com/transaction/AddEmployeeTransaction.java new file mode 100644 index 0000000000..bef6a08e20 --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/transaction/AddEmployeeTransaction.java @@ -0,0 +1,42 @@ +package com.transaction; + +import com.PaymentMethod.HoldMethod; +import com.pojo.Employee; +import com.pojo.PaymentClassification; +import com.pojo.PaymentMethod; +import com.pojo.PaymentSchedule; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 21:24 + */ +public abstract class AddEmployeeTransaction { + + private String name; + private String address; + public AddEmployeeTransaction(String name,String address){ + this.name = name; + this.address = address; + } + + + public abstract PaymentClassification getClassification(); + + public abstract PaymentSchedule getSchedule(); + + + public void execute(){ + PaymentClassification pc = getClassification(); + PaymentSchedule ps = getSchedule(); + PaymentMethod pm = new HoldMethod(); + Employee e = new Employee(name, address); + e.setClassification(pc); + e.setSchedule(ps); + e.setPaymentMethod(pm); + } + + + + +} diff --git a/students/643449856/payrolla/src/main/java/com/transaction/AddHourlyEmployeeTransaction.java b/students/643449856/payrolla/src/main/java/com/transaction/AddHourlyEmployeeTransaction.java new file mode 100644 index 0000000000..1442672485 --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/transaction/AddHourlyEmployeeTransaction.java @@ -0,0 +1,33 @@ +package com.transaction; + +import com.Classification.HourlyClassification; +import com.Schedule.WeeklySchedule; +import com.pojo.PaymentClassification; +import com.pojo.PaymentSchedule; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 21:25 + */ +public class AddHourlyEmployeeTransaction extends AddEmployeeTransaction { + + + private double rate; + + AddHourlyEmployeeTransaction(String name, String address, double hourlyRate) { + super(name, address); + this.rate = hourlyRate; + } + + @Override + public PaymentClassification getClassification() { + return new HourlyClassification(rate); + } + + @Override + public PaymentSchedule getSchedule() { + + return new WeeklySchedule(); + } +} \ No newline at end of file diff --git a/students/643449856/payrolla/src/main/java/com/util/DateUtil.java b/students/643449856/payrolla/src/main/java/com/util/DateUtil.java new file mode 100644 index 0000000000..3a270aa0f4 --- /dev/null +++ b/students/643449856/payrolla/src/main/java/com/util/DateUtil.java @@ -0,0 +1,67 @@ +package com.util; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +/** + * Created by nengneng + * Date: 2017/9/15 + * Time: 20:25 + * + * + */ +public class DateUtil { + + + public static long getDaysBetween(Date d1, Date d2){ + + return (d2.getTime() - d1.getTime())/(24*60*60*1000); + } + + public static Date parseDate(String txtDate){ + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); + try { + return sdf.parse(txtDate); + } catch (ParseException e) { + e.printStackTrace(); + return null; + } + } + public static boolean isFriday(Date d){ + Calendar calendar = Calendar.getInstance(); + return calendar.get(Calendar.DAY_OF_WEEK) == 5; + } + + public static Date add(Date d, int days){ + Calendar calendar = Calendar.getInstance(); + calendar.setTime(d); + calendar.add(Calendar.DATE, days); + return calendar.getTime(); + } + + public static boolean isLastDayOfMonth(Date d){ + Calendar calendar=Calendar.getInstance(); + calendar.setTime(d); + return calendar.get(Calendar.DATE)==calendar.getActualMaximum(Calendar.DAY_OF_MONTH); + } + public static Date getFirstDay(Date d){ + Calendar calendar=Calendar.getInstance(); + calendar.setTime(d); + int day = calendar.get(Calendar.DATE); + calendar.add(Calendar.DATE, -(day-1)); + return calendar.getTime(); + } + public static void main(String [] args) throws Exception{ + System.out.println(DateUtil.isLastDayOfMonth(DateUtil.parseDate("2017-6-29"))); + + System.out.println(DateUtil.getFirstDay(DateUtil.parseDate("2017-6-30"))); + } + + public static boolean between(Date d, Date date1, Date date2){ + return d.after(date1) && d.before(date2); + } + + +} diff --git a/students/643449856/readme.md b/students/643449856/readme.md new file mode 100644 index 0000000000..b8e87ead7c --- /dev/null +++ b/students/643449856/readme.md @@ -0,0 +1 @@ +first pull request \ No newline at end of file diff --git a/students/675554906/readme.md b/students/675554906/readme.md new file mode 100644 index 0000000000..a51b977d60 --- /dev/null +++ b/students/675554906/readme.md @@ -0,0 +1 @@ +第一次提交 仅为学习 \ No newline at end of file diff --git a/students/675554906/src/lilei/com/cn/Configuration.java b/students/675554906/src/lilei/com/cn/Configuration.java new file mode 100644 index 0000000000..c8020595fd --- /dev/null +++ b/students/675554906/src/lilei/com/cn/Configuration.java @@ -0,0 +1,27 @@ +package lilei.com.cn; +import java.util.HashMap; +import java.util.Map; +/** + * Configuration 读取/获取配置信息类 + * 唯一能引起此类变化的是配置文件的改变 + * + * */ +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/675554906/src/lilei/com/cn/ConfigurationKeys.java b/students/675554906/src/lilei/com/cn/ConfigurationKeys.java new file mode 100644 index 0000000000..ddcaeb4def --- /dev/null +++ b/students/675554906/src/lilei/com/cn/ConfigurationKeys.java @@ -0,0 +1,13 @@ +package lilei.com.cn; +/** + * ConfigurationKeys 配置信息定义类 + * 个人理解,唯一能引发变化的是“需求”比如,要增加一个KEY + * + * */ +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/675554906/src/lilei/com/cn/DBUtil.java b/students/675554906/src/lilei/com/cn/DBUtil.java new file mode 100644 index 0000000000..9ae43cc7dc --- /dev/null +++ b/students/675554906/src/lilei/com/cn/DBUtil.java @@ -0,0 +1,29 @@ +package lilei.com.cn; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + /** + * DBUtil 连接数据库,获取数据 + * 个人理解,此类只是负责数据库的连接,和数据的读取,存储,修改 + * + * */ +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/675554906/src/lilei/com/cn/MailAssemble.java b/students/675554906/src/lilei/com/cn/MailAssemble.java new file mode 100644 index 0000000000..8c17e5f3bf --- /dev/null +++ b/students/675554906/src/lilei/com/cn/MailAssemble.java @@ -0,0 +1,100 @@ +package lilei.com.cn; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +/** + * MailAssemble 组装邮件类 + * 个人理解, 此类的职责是组装邮件,而邮件是根据Configuration(配置信息类)、ReadFile(读取信息类)来组成的,这两个类也是引起变化的因素 + * + * */ +public class MailAssemble { + protected String sendMailQuery = null; + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + protected String productID = null; + protected String productDesc = null; + + private static Configuration config = new Configuration(); + private static ReadFile rf = new ReadFile();; + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + //组装信息 + public void assembleMail() throws Exception{ + String data[] = rf.readFile(); + setProductID(data[0]); + setProductDesc(data[1]); + setSMTPHost(); + setAltSMTPHost(); + setFromAddress(); + setLoadQuery(); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + protected void configureEMail(HashMap userInfo) throws IOException + { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected void setFromAddress() + { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setMessage(HashMap userInfo) throws IOException + { + String name = (String) userInfo.get(NAME_KEY); + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + } + + + protected void setProductID(String productID) + { + this.productID = productID; + + } + + protected String getproductID() + { + return productID; + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected void setSMTPHost() + { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() + { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + private void setProductDesc(String desc) { + this.productDesc = desc; + } +} diff --git a/students/675554906/src/lilei/com/cn/MailUtil.java b/students/675554906/src/lilei/com/cn/MailUtil.java new file mode 100644 index 0000000000..2bd129dc75 --- /dev/null +++ b/students/675554906/src/lilei/com/cn/MailUtil.java @@ -0,0 +1,60 @@ +package lilei.com.cn; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +/** + * MailUtil 邮件方法类 + * 个人理解,唯一引起变化的就是邮件发送方法的改变 + * + * */ +public class MailUtil { + + private static MailAssemble assembleMail = new MailAssemble(); + + public static void sendEmail(MailAssemble assembleMail , boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(assembleMail.fromAddress).append("\n"); + buffer.append("To:").append(assembleMail.toAddress).append("\n"); + buffer.append("Subject:").append(assembleMail.subject).append("\n"); + buffer.append("Content:").append(assembleMail.message).append("\n"); + System.out.println(buffer.toString()); + + } + + protected void sendEMails(boolean debug) throws Exception + { + assembleMail.assembleMail(); + List mailingList = assembleMail.loadMailingList(); + System.out.println("开始发送邮件"); + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + assembleMail.configureEMail((HashMap) iter.next()); + try + { + if (assembleMail.toAddress.length() > 0) + sendEmail(assembleMail, debug); + } + catch (Exception e) + { + + try { + sendEmail(assembleMail, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + } + + else { + System.out.println("没有邮件发送"); + } + } +} diff --git a/students/675554906/src/lilei/com/cn/PromotionMail.java b/students/675554906/src/lilei/com/cn/PromotionMail.java new file mode 100644 index 0000000000..7522bab6b1 --- /dev/null +++ b/students/675554906/src/lilei/com/cn/PromotionMail.java @@ -0,0 +1,29 @@ +package lilei.com.cn; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +/** + * PromotionMail 推送邮件类 + * 个人理解, 此类唯一能引起变化的就是发送邮件的方法变化 + * + * */ +public class PromotionMail { + + private static MailUtil mailUtil; + public static void main(String[] args) throws Exception { + + boolean emailDebug = false; + PromotionMail pe = new PromotionMail(emailDebug); + } + + public PromotionMail(boolean mailDebug) throws Exception { + mailUtil = new MailUtil(); + mailUtil.sendEMails(mailDebug); + } +} diff --git a/students/675554906/src/lilei/com/cn/ReadFile.java b/students/675554906/src/lilei/com/cn/ReadFile.java new file mode 100644 index 0000000000..e13a9d644e --- /dev/null +++ b/students/675554906/src/lilei/com/cn/ReadFile.java @@ -0,0 +1,33 @@ +package lilei.com.cn; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +/** + * ReadFile 读取文件类 + * 个人理解, 唯一能引发变化的就是文件路径的变动 + * + * */ +public class ReadFile { + + private File file; + private String filePath = "F:\\product_promotion.txt"; + + protected String[] readFile() throws IOException // @02C + { + BufferedReader br = null; + try { + file = new File(filePath); + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + return data; + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } +} diff --git a/students/675554906/src/lilei/com/cn/product_promotion.txt b/students/675554906/src/lilei/com/cn/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/675554906/src/lilei/com/cn/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/702282822/2_assignment/course/bad/Course.java b/students/702282822/2_assignment/course/bad/Course.java new file mode 100644 index 0000000000..436d092f58 --- /dev/null +++ b/students/702282822/2_assignment/course/bad/Course.java @@ -0,0 +1,24 @@ +package com.coderising.ood.course.bad; + +import java.util.List; + +public class Course { + private String id; + private String desc; + private int duration ; + + List prerequisites; + + public List getPrerequisites() { + return prerequisites; + } + + + public boolean equals(Object o){ + if(o == null || !(o instanceof Course)){ + return false; + } + Course c = (Course)o; + return (c != null) && c.id.equals(id); + } +} diff --git a/students/702282822/2_assignment/course/bad/CourseOffering.java b/students/702282822/2_assignment/course/bad/CourseOffering.java new file mode 100644 index 0000000000..e24bcd2062 --- /dev/null +++ b/students/702282822/2_assignment/course/bad/CourseOffering.java @@ -0,0 +1,24 @@ +package com.coderising.ood.course.bad; + +import java.util.ArrayList; +import java.util.List; + + +public class CourseOffering { + private Course course; + private String location; + private String teacher; + private int maxStudents; + + List students = new ArrayList(); + + public void addStudent(Student st) + { + if(st.canAttend(course) && maxStudents > students.size()) + { + students.add(st); + } + } + + +} diff --git a/students/702282822/2_assignment/course/bad/CourseService.java b/students/702282822/2_assignment/course/bad/CourseService.java new file mode 100644 index 0000000000..3d06149ca2 --- /dev/null +++ b/students/702282822/2_assignment/course/bad/CourseService.java @@ -0,0 +1,12 @@ +package com.coderising.ood.course.bad; + + + +public class CourseService { + + public void chooseCourse(Student student, CourseOffering sc){ + //如果学生上过该科目的先修科目,并且该课程还未满, 则学生可以加入该课程 + sc.addStudent(student); + } + +} diff --git a/students/702282822/2_assignment/course/bad/Student.java b/students/702282822/2_assignment/course/bad/Student.java new file mode 100644 index 0000000000..6629b60bfb --- /dev/null +++ b/students/702282822/2_assignment/course/bad/Student.java @@ -0,0 +1,20 @@ +package com.coderising.ood.course.bad; + +import java.util.ArrayList; +import java.util.List; + +public class Student { + private String id; + private String name; + private List coursesAlreadyTaken = new ArrayList(); + + public List getCoursesAlreadyTaken() { + return coursesAlreadyTaken; + } + public boolean canAttend(Course course){ + return getCoursesAlreadyTaken().containsAll( + course.getPrerequisites()); + } + + +} diff --git a/students/702282822/2_assignment/course/good/Course.java b/students/702282822/2_assignment/course/good/Course.java new file mode 100644 index 0000000000..aefc9692bb --- /dev/null +++ b/students/702282822/2_assignment/course/good/Course.java @@ -0,0 +1,18 @@ +package com.coderising.ood.course.good; + +import java.util.List; + +public class Course { + private String id; + private String desc; + private int duration ; + + List prerequisites; + + public List getPrerequisites() { + return prerequisites; + } + +} + + diff --git a/students/702282822/2_assignment/course/good/CourseOffering.java b/students/702282822/2_assignment/course/good/CourseOffering.java new file mode 100644 index 0000000000..8660ec8109 --- /dev/null +++ b/students/702282822/2_assignment/course/good/CourseOffering.java @@ -0,0 +1,34 @@ +package com.coderising.ood.course.good; + +import java.util.ArrayList; +import java.util.List; + +public class CourseOffering { + private Course course; + private String location; + private String teacher; + private int maxStudents; + + List students = new ArrayList(); + + public List getStudents() { + return students; + } + public int getMaxStudents() { + return maxStudents; + } + public Course getCourse() { + return course; + } + + + // 第二步: 把主要逻辑移动到CourseOffering 中 + public void addStudent(Student student){ + + if(student.canAttend(course) + && this.maxStudents > students.size()){ + students.add(student); + } + } + // 第三步: 重构CourseService +} diff --git a/students/702282822/2_assignment/course/good/CourseService.java b/students/702282822/2_assignment/course/good/CourseService.java new file mode 100644 index 0000000000..22ba4a5450 --- /dev/null +++ b/students/702282822/2_assignment/course/good/CourseService.java @@ -0,0 +1,14 @@ +package com.coderising.ood.course.good; + + + +public class CourseService { + + public void chooseCourse(Student student, CourseOffering sc){ + //第一步:重构: canAttend , 但是还有问题 + if(student.canAttend(sc.getCourse()) + && sc.getMaxStudents() > sc.getStudents().size()){ + sc.getStudents().add(student); + } + } +} diff --git a/students/702282822/2_assignment/course/good/Student.java b/students/702282822/2_assignment/course/good/Student.java new file mode 100644 index 0000000000..2c7e128b2a --- /dev/null +++ b/students/702282822/2_assignment/course/good/Student.java @@ -0,0 +1,21 @@ +package com.coderising.ood.course.good; + +import java.util.ArrayList; +import java.util.List; + +public class Student { + private String id; + private String name; + private List coursesAlreadyTaken = new ArrayList(); + + public List getCoursesAlreadyTaken() { + return coursesAlreadyTaken; + } + + public boolean canAttend(Course course){ + return this.coursesAlreadyTaken.containsAll( + course.getPrerequisites()); + } +} + + diff --git a/students/702282822/2_assignment/ocp/DateUtil.java b/students/702282822/2_assignment/ocp/DateUtil.java new file mode 100644 index 0000000000..b6cf28c096 --- /dev/null +++ b/students/702282822/2_assignment/ocp/DateUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return null; + } + +} diff --git a/students/702282822/2_assignment/ocp/Deliver.java b/students/702282822/2_assignment/ocp/Deliver.java new file mode 100644 index 0000000000..377fcf3a64 --- /dev/null +++ b/students/702282822/2_assignment/ocp/Deliver.java @@ -0,0 +1,5 @@ + +public interface Dilever +{ + public void process(string str); +} diff --git a/students/702282822/2_assignment/ocp/DeliveryFactory.java b/students/702282822/2_assignment/ocp/DeliveryFactory.java new file mode 100644 index 0000000000..daf562759e --- /dev/null +++ b/students/702282822/2_assignment/ocp/DeliveryFactory.java @@ -0,0 +1,20 @@ + +public interface DeliveryFactory +{ + public static Deliver createDelivery(int type) + { + if(type == 1) + { + return new Email_Deliver(); + } + else if(type == 2) + { + return new SMS_Deliver(); + } + else if(type == 3) + { + return new Print_Deliver(); + } + } + +} diff --git a/students/702282822/2_assignment/ocp/Email_Deliver.java b/students/702282822/2_assignment/ocp/Email_Deliver.java new file mode 100644 index 0000000000..c4eee88ded --- /dev/null +++ b/students/702282822/2_assignment/ocp/Email_Deliver.java @@ -0,0 +1,9 @@ + +public class Email_Deliver implements dileverMsg +{ + public void process(string str) + { + MailUtil.send(logMsg); + } + +} diff --git a/students/702282822/2_assignment/ocp/Formatter.java b/students/702282822/2_assignment/ocp/Formatter.java new file mode 100644 index 0000000000..35cf0bf4e3 --- /dev/null +++ b/students/702282822/2_assignment/ocp/Formatter.java @@ -0,0 +1,4 @@ +public interface Formatter +{ + public string format(string msg); +} diff --git a/students/702282822/2_assignment/ocp/FormatterFactory.java b/students/702282822/2_assignment/ocp/FormatterFactory.java new file mode 100644 index 0000000000..1f9ef348fd --- /dev/null +++ b/students/702282822/2_assignment/ocp/FormatterFactory.java @@ -0,0 +1,14 @@ + +public class FormatterFactory { + public static Formatter createFormate(int type) + { + if(type == 1) + { + return new Raw_log(); + } + else if(type == 2) + { + return new Raw_log_withDate(); + } + } +} diff --git a/students/702282822/2_assignment/ocp/Logger.java b/students/702282822/2_assignment/ocp/Logger.java new file mode 100644 index 0000000000..839c8d74cd --- /dev/null +++ b/students/702282822/2_assignment/ocp/Logger.java @@ -0,0 +1,18 @@ +package com.coderising.ood.ocp; + +public class Logger { + + private Formatter formatter; + private Dilever deliver; + public Logger(Formatter formatter, Dilever deliver) + { + this.formatter = formatter; + this.deliver = deliver; + } + public void log(String msg) + { + String message = formatter.formate(msg); + deliver.process(message); + } +} + diff --git a/students/702282822/2_assignment/ocp/MailUtil.java b/students/702282822/2_assignment/ocp/MailUtil.java new file mode 100644 index 0000000000..ec54b839c5 --- /dev/null +++ b/students/702282822/2_assignment/ocp/MailUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class MailUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/702282822/2_assignment/ocp/Print_Deliver.java b/students/702282822/2_assignment/ocp/Print_Deliver.java new file mode 100644 index 0000000000..10c31ba398 --- /dev/null +++ b/students/702282822/2_assignment/ocp/Print_Deliver.java @@ -0,0 +1,8 @@ + +public class Print_Deliver +{ + public void process(string str) + { + System.out.print(str); + } +} diff --git a/students/702282822/2_assignment/ocp/Raw_log.java b/students/702282822/2_assignment/ocp/Raw_log.java new file mode 100644 index 0000000000..5f6af6cf2c --- /dev/null +++ b/students/702282822/2_assignment/ocp/Raw_log.java @@ -0,0 +1,8 @@ + +public class Raw_log implements Formatter +{ + public string format(string msg) + { + return msg; + } +} diff --git a/students/702282822/2_assignment/ocp/Raw_log_withDate.java b/students/702282822/2_assignment/ocp/Raw_log_withDate.java new file mode 100644 index 0000000000..3458923e3f --- /dev/null +++ b/students/702282822/2_assignment/ocp/Raw_log_withDate.java @@ -0,0 +1,12 @@ + +public class Raw_log_withDate implements Raw_log +{ + public string format(string msg) + { + string msg = super.format(msg); + String txtDate = DateUtil.getCurrentDateAsString(); + return txtDate + ": " + msg; + } + + +} diff --git a/students/702282822/2_assignment/ocp/SMSUtil.java b/students/702282822/2_assignment/ocp/SMSUtil.java new file mode 100644 index 0000000000..13cf802418 --- /dev/null +++ b/students/702282822/2_assignment/ocp/SMSUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class SMSUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/702282822/2_assignment/ocp/SMS_Deliver.java b/students/702282822/2_assignment/ocp/SMS_Deliver.java new file mode 100644 index 0000000000..047cf55b28 --- /dev/null +++ b/students/702282822/2_assignment/ocp/SMS_Deliver.java @@ -0,0 +1,10 @@ + +public class SMS_Deliver implements dileverMsg +{ + public void process(string str) + { + SMSUtil.send(str); + } + + +} diff --git a/students/702282822/ood-assignment/pom.xml b/students/702282822/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/702282822/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/702282822/ood-assignment/product_promotion.txt b/students/702282822/ood-assignment/product_promotion.txt new file mode 100644 index 0000000000..a98917f829 --- /dev/null +++ b/students/702282822/ood-assignment/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo R15 +P4955 Vivo X20 \ No newline at end of file diff --git a/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..44e38129c8 --- /dev/null +++ b/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,26 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + static final String NAME_KEY = "NAME"; + static final String EMAIL_KEY = "EMAIL"; + + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public static String getProperty(String key) + { + return configurations.get(key); + } + +} diff --git a/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..d131ff0c73 --- /dev/null +++ b/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..97909cf560 --- /dev/null +++ b/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,29 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } + + + + +} diff --git a/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/FileProdUtil.java b/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/FileProdUtil.java new file mode 100644 index 0000000000..4e3a7d2373 --- /dev/null +++ b/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/FileProdUtil.java @@ -0,0 +1,36 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.LinkedList; + +public class FileProdUtil { + //if other files, need polymorphically present file reading + public static void readFile(File file, LinkedList themes) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String sCurrentLine = ""; + + while ((sCurrentLine = br.readLine()) != null) + { + Theme prod = new Product(); + String[] data = sCurrentLine.split(" "); + prod.setID(data[0]); + prod.setDesc(data[1]); + + System.out.println("产品ID = " + prod.getID() + "\n"); + System.out.println("产品描述 = " + prod.getDesc() + "\n"); + themes.add(prod); + } + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + +} diff --git a/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java b/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java new file mode 100644 index 0000000000..4820d10a12 --- /dev/null +++ b/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java @@ -0,0 +1,128 @@ +package com.coderising.ood.srp; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +public abstract class Mail { + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + protected String sendMailQuery = null; + protected LinkedList theme; + public Mail(File file, boolean emailDebug) throws Exception + { + theme = new LinkedList<>(); + FileProdUtil.readFile(file, theme); + setSMTPHost(); + setAltSMTPHost(); + setFromAddress(); + sendEMails(emailDebug, theme); + } + //protected abstract void readFile(File fie, LinkedList theme) throws IOException; + + protected void setSMTPHost() + { + smtpHost = Configuration.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() + { + altSmtpHost = Configuration.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + } + + + protected void setFromAddress() + { + fromAddress = Configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setToAddress(HashMap userInfo){ + toAddress = (String) userInfo.get(Configuration.EMAIL_KEY); + } + + protected List loadMailingList() throws Exception { //user information, name and email address + return DBUtil.query(this.sendMailQuery); + } + + + //protected abstract void setMessage(String name) throws IOException; + + abstract protected void setSendMailQuery(Theme theme) throws Exception; + + + abstract protected void setMessage(String name, Theme theme) throws IOException; + + + protected void emailProcessing(List mailingList, boolean debug, Theme theme) throws Exception + { + if (mailingList != null) + { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) + { + HashMap userInfo = (HashMap) iter.next(); + setToAddress(userInfo); + if (toAddress.length() > 0) + setMessage((String)userInfo.get(Configuration.NAME_KEY), theme); + + try + { + if (toAddress.length() > 0) + sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } + catch (Exception e) + { + + try { + sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + } + else { + System.out.println("没有邮件发送"); + } + } + + + + protected void sendEMails(boolean debug, LinkedList theme) throws Exception + { + for(Theme topic : theme) + { + setSendMailQuery(topic); + List mailingList = loadMailingList(); //persons + + System.out.println("开始发送邮件"); + emailProcessing(mailingList, debug, topic); + } + } + + public void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java b/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..1f84e2f087 --- /dev/null +++ b/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,8 @@ +package com.coderising.ood.srp; + +public class Product extends Theme { + + + + +} diff --git a/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..d6ef4b8c26 --- /dev/null +++ b/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,37 @@ +package com.coderising.ood.srp; + +import java.io.File; +import java.io.IOException; + +public class PromotionMail extends Mail { //inheritance from mail + + + + public static void main(String[] args) throws Exception { + + File f = new File("./product_promotion.txt"); + boolean emailDebug = false; + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + public PromotionMail(File file, boolean mailDebug) throws Exception + { + super(file, mailDebug); + } + + protected void setSendMailQuery(Theme theme) throws Exception { + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + theme.getID() +"' " + + "and send_mail=1 "; + + System.out.println("loadQuery set"); + } + + + protected void setMessage(String name, Theme theme) throws IOException + { + subject = "您关注的产品降价了"; + message = "尊敬的 "+ name +", 您关注的产品 " + theme.getDesc() + " 降价了,欢迎购买!" ; + } +} diff --git a/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/Theme.java b/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/Theme.java new file mode 100644 index 0000000000..e2bf2f5e00 --- /dev/null +++ b/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/Theme.java @@ -0,0 +1,31 @@ +/** + * + */ +package com.coderising.ood.srp; + +/** + * @author funkyxym + * + */ +public abstract class Theme { + private String ID = ""; + private String Desc = ""; + + protected void setID(String ID) + { + this.ID = ID; + } + + protected String getID() + { + return ID; + } + + protected void setDesc(String desc) { + this.Desc = desc; + } + + protected String getDesc(){ + return Desc; + } +} diff --git a/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..a98917f829 --- /dev/null +++ b/students/702282822/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo R15 +P4955 Vivo X20 \ No newline at end of file diff --git "a/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/Configuration.java" "b/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/Configuration.java" new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ "b/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/Configuration.java" @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git "a/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/ConfigurationKeys.java" "b/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/ConfigurationKeys.java" new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ "b/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/ConfigurationKeys.java" @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git "a/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/DBUtil.java" "b/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/DBUtil.java" new file mode 100644 index 0000000000..c3107056d5 --- /dev/null +++ "b/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/DBUtil.java" @@ -0,0 +1,41 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + private String sql; + + + public void setLoadQuery(String productID) throws Exception { + + String sql = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + this.setSql(sql); + System.out.println("loadQuery set"); + } + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public List queryForList(){ + String query=this.getSql(); + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + User userInfo = new User(); + userInfo.setNAME("User" + i); + userInfo.setEMAIL("aa@bb.com"); + userList.add(userInfo); + } + return userList; + } + public String getSql() { + return sql; + } + public void setSql(String sql) { + this.sql = sql; + } +} diff --git "a/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/EMail.java" "b/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/EMail.java" new file mode 100644 index 0000000000..53834eba04 --- /dev/null +++ "b/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/EMail.java" @@ -0,0 +1,48 @@ +package com.coderising.ood.srp; + +import java.util.HashMap; + +public class EMail { + + private String fromAddress; + private String toAddress; + private String subject; + private String message; + + + + public EMail(String fromAddress, String toAddress, String subject, String message) { + this.fromAddress = fromAddress; + this.toAddress = toAddress; + this.subject = subject; + this.message = message; + } + + + public String getFromAddress() { + return fromAddress; + } + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + public String getToAddress() { + return toAddress; + } + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + public String getSubject() { + return subject; + } + public void setSubject(String subject) { + this.subject = subject; + } + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message=message; + } + + +} diff --git "a/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/MailUtil.java" "b/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/MailUtil.java" new file mode 100644 index 0000000000..86def76810 --- /dev/null +++ "b/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/MailUtil.java" @@ -0,0 +1,20 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git "a/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/Product.java" "b/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/Product.java" new file mode 100644 index 0000000000..93ec68aae0 --- /dev/null +++ "b/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/Product.java" @@ -0,0 +1,60 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +/** + * 产品类 + * @author Administrator + * + */ +public class Product { + + /** + * 产品ID + */ + private String productID; + + /** + * 产品描述 + */ + private String productDesc; + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + + public static Product readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + Product product = new Product(); + product.setProductID(data[0]); + product.setProductDesc(data[1]); + System.out.println("产品ID = " + product.getProductID() + "\n"); + System.out.println("产品描述 = " + product.getProductDesc() + "\n"); + return product; + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } +} diff --git "a/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/PromotionMail.java" "b/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/PromotionMail.java" new file mode 100644 index 0000000000..1c6225abdb --- /dev/null +++ "b/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/PromotionMail.java" @@ -0,0 +1,80 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery = null; + + private static Configuration config; + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + boolean emailDebug = false; + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + Product product=Product.readFile(file); + config = new Configuration(); + Server server =new Server(); + server.setSmtpHost(config.getProperty(ConfigurationKeys.SMTP_SERVER)); + server.setAltSmtpHost(config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER)); + DBUtil dbUtil = new DBUtil(); + dbUtil.setLoadQuery(product.getProductID()); + List mailingList= dbUtil.queryForList(); + if (mailingList != null) { + System.out.println("开始发送邮件"); + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + HashMap userInfo = (HashMap) iter.next(); + String toAddress = (String) userInfo.get(EMAIL_KEY); + String name = (String) userInfo.get(NAME_KEY); + String subject = "您关注的产品降价了"; + String message = "尊敬的 "+name+", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!" ; + String fromAddress=config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + EMail eMail = new EMail(toAddress,fromAddress,subject,message); + sendEMails(eMail,server,mailDebug); + } + }else{ + System.out.println("没有邮件发送"); + } + } + + protected void sendEMails(EMail eMail,Server server,boolean debug) throws IOException { + try + { + if (eMail.getToAddress().length() > 0) + MailUtil.sendEmail(eMail.getToAddress(), eMail.getFromAddress(), eMail.getSubject(), eMail.getMessage(), server.getSmtpHost(), debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(eMail.getToAddress(), eMail.getFromAddress(), eMail.getSubject(), eMail.getMessage(), server.getAltSmtpHost(), debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } +} + diff --git "a/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/Server.java" "b/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/Server.java" new file mode 100644 index 0000000000..37776d9aa6 --- /dev/null +++ "b/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/Server.java" @@ -0,0 +1,20 @@ +package com.coderising.ood.srp; + + +public class Server { + + private String smtpHost; + private String altSmtpHost; + public String getSmtpHost() { + return smtpHost; + } + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + public String getAltSmtpHost() { + return altSmtpHost; + } + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } +} diff --git "a/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/User.java" "b/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/User.java" new file mode 100644 index 0000000000..69d9010247 --- /dev/null +++ "b/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/User.java" @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; + +public class User { + + private String NAME; + + private String EMAIL; + + public String getNAME() { + return NAME; + } + + public void setNAME(String nAME) { + NAME = nAME; + } + + public String getEMAIL() { + return EMAIL; + } + + public void setEMAIL(String eMAIL) { + EMAIL = eMAIL; + } + +} diff --git "a/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/product_promotion.txt" "b/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/product_promotion.txt" new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ "b/students/706097141/\347\254\254\344\270\200\346\254\241\344\275\234\344\270\232/product_promotion.txt" @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git "a/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/DateUtil.java" "b/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/DateUtil.java" new file mode 100644 index 0000000000..b6cf28c096 --- /dev/null +++ "b/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/DateUtil.java" @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return null; + } + +} diff --git "a/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/EmailLogger.java" "b/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/EmailLogger.java" new file mode 100644 index 0000000000..7a51f98c23 --- /dev/null +++ "b/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/EmailLogger.java" @@ -0,0 +1,9 @@ +package com.coderising.ood.ocp; + +public class EmailLogger extends Logger{ + + public void log(String msg){ + MailUtil.send(msg); + } + +} diff --git "a/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/LogOutput.java" "b/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/LogOutput.java" new file mode 100644 index 0000000000..caf9986293 --- /dev/null +++ "b/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/LogOutput.java" @@ -0,0 +1,8 @@ +package com.coderising.ood.ocp; + +public abstract class LogOutput { + + + public abstract void logOutput(String msg,Logger logger); + +} diff --git "a/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/Logger.java" "b/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/Logger.java" new file mode 100644 index 0000000000..8913377e5a --- /dev/null +++ "b/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/Logger.java" @@ -0,0 +1,7 @@ +package com.coderising.ood.ocp; + +public abstract class Logger { + + public abstract void log(String msg); +} + diff --git "a/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/MailUtil.java" "b/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/MailUtil.java" new file mode 100644 index 0000000000..ec54b839c5 --- /dev/null +++ "b/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/MailUtil.java" @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class MailUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git "a/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/PrintLogger.java" "b/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/PrintLogger.java" new file mode 100644 index 0000000000..6960fb9af3 --- /dev/null +++ "b/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/PrintLogger.java" @@ -0,0 +1,9 @@ +package com.coderising.ood.ocp; + +public class PrintLogger extends Logger{ + +public void log(String msg){ + System.out.println(msg); + } + +} diff --git "a/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/RawLogOutput.java" "b/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/RawLogOutput.java" new file mode 100644 index 0000000000..9603d16687 --- /dev/null +++ "b/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/RawLogOutput.java" @@ -0,0 +1,9 @@ +package com.coderising.ood.ocp; + +public class RawLogOutput extends LogOutput{ + + public void logOutput(String msg,Logger logger) { + logger.log(msg); + } + +} diff --git "a/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/RawLogWithDateOutput.java" "b/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/RawLogWithDateOutput.java" new file mode 100644 index 0000000000..5f414d992d --- /dev/null +++ "b/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/RawLogWithDateOutput.java" @@ -0,0 +1,12 @@ +package com.coderising.ood.ocp; + +public class RawLogWithDateOutput extends LogOutput{ + + @Override + public void logOutput(String msg,Logger logger) { + String txtDate = DateUtil.getCurrentDateAsString(); + String logMsg = txtDate + ": " + msg; + logger.log(logMsg); + } + +} diff --git "a/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/SMSUtil.java" "b/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/SMSUtil.java" new file mode 100644 index 0000000000..13cf802418 --- /dev/null +++ "b/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/SMSUtil.java" @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class SMSUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git "a/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/SmsLogger.java" "b/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/SmsLogger.java" new file mode 100644 index 0000000000..8a22e52e78 --- /dev/null +++ "b/students/706097141/\347\254\254\344\272\214\346\254\241\344\275\234\344\270\232/ocp/SmsLogger.java" @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp; + +public class SmsLogger extends Logger{ + + + public void log(String msg){ + + SMSUtil.send(msg); + } + +} diff --git a/students/709960951/ood/ood-assignment/pom.xml b/students/709960951/ood/ood-assignment/pom.xml new file mode 100644 index 0000000000..837d9eeed1 --- /dev/null +++ b/students/709960951/ood/ood-assignment/pom.xml @@ -0,0 +1,25 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + junit + junit + 3.8.1 + test + + + diff --git a/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigProductRepository.java b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigProductRepository.java new file mode 100644 index 0000000000..b31c6040a8 --- /dev/null +++ b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigProductRepository.java @@ -0,0 +1,40 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import com.coderising.ood.srp.domainlogic.Product; +import com.coderising.ood.srp.domainlogic.ProductRepository; + +public class ConfigProductRepository extends ProductRepository { + + private static final String PRODUCT_PROMOTION_FILE = "com/coderising/ood/srp/product_promotion.txt"; + @Override + public List getPromotionProducts() throws IOException { + BufferedReader br = null; + List products = new ArrayList<>(); + try { + String fileName = Thread.currentThread().getContextClassLoader().getResource(PRODUCT_PROMOTION_FILE) + .getFile(); + br = new BufferedReader(new FileReader(fileName)); + String temp = br.readLine(); + String[] data = temp.split(" "); + Product product = new Product(); + product.setProductID(data[0]); + product.setProductDesc(data[1]); + products.add(product); + System.out.println("产品ID = " + product.getProductID() + "\n"); + System.out.println("产品描述 = " + product.getProductDesc() + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + return products; + } + +} diff --git a/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..868a03ff83 --- /dev/null +++ b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/EmailServiceImpl.java b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/EmailServiceImpl.java new file mode 100644 index 0000000000..b47406cc11 --- /dev/null +++ b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/EmailServiceImpl.java @@ -0,0 +1,52 @@ +package com.coderising.ood.srp; + +import com.coderising.ood.srp.domainlogic.Email; +import com.coderising.ood.srp.domainlogic.EmailService; + +public class EmailServiceImpl implements EmailService { + private boolean debugMode = false; // 调试模式,默认关闭 + private String priorSmtpHost; + private String altSmtpHost; + + public EmailServiceImpl(String priorSmtpHost, String altSmtpHost) { + this.priorSmtpHost = priorSmtpHost; + this.altSmtpHost = altSmtpHost; + } + + @Override + public void sendEmail(Email email) { + + try { + sendEmail(email, priorSmtpHost); + } catch (Exception e) { + + try { + sendEmail(email, altSmtpHost); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + private void sendEmail(Email email,String smtpHost) + { + // TODO: send email + if (isDebugMode()) { + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(email.getFromAddress()).append("\n"); + buffer.append("To:").append(email.getToAddress()).append("\n"); + buffer.append("Subject:").append(email.getSubject()).append("\n"); + buffer.append("Content:").append(email.getMessage()).append("\n"); + System.out.println(buffer.toString()); + } + } + + public boolean isDebugMode() { + return debugMode; + } + + public void setDebugMode(boolean debugMode) { + this.debugMode = debugMode; + } + +} diff --git a/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MockUserRepository.java b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MockUserRepository.java new file mode 100644 index 0000000000..98c70a6ff0 --- /dev/null +++ b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MockUserRepository.java @@ -0,0 +1,24 @@ +package com.coderising.ood.srp; + +import java.util.ArrayList; +import java.util.List; + +import com.coderising.ood.srp.domainlogic.User; +import com.coderising.ood.srp.domainlogic.UserRepository; + +public class MockUserRepository extends UserRepository { + + @Override + public List getPromotionUsers() { + List userList = new ArrayList<>(); + for (int i = 1; i <= 3; i++) { + User user = new User(); + user.setName("User" + i); + user.setEmail("aa@bb.com"); + userList.add(user); + } + + return userList; + } + +} diff --git a/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..f57df29b3d --- /dev/null +++ b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,34 @@ +package com.coderising.ood.srp; + +import java.util.Properties; + +import com.coderising.ood.srp.domainlogic.PromotionEmailService; + +public class PromotionMail { + + private static final String EMAIL_CONFIG = "com/coderising/ood/srp/emailconfig.properties"; + + public static void main(String[] args) throws Exception { + // 读取email配置文件 + Properties emailConfig = new Properties(); + emailConfig.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(EMAIL_CONFIG)); + // 获取配置项 + String priorSmtpHost = ConfigurationKeys.SMTP_SERVER; + String altSmtpHost = ConfigurationKeys.ALT_SMTP_SERVER; + String fromEmailAddress = ConfigurationKeys.SMTP_SERVER; + // 邮件服务的实现 + EmailServiceImpl emailService = new EmailServiceImpl(priorSmtpHost, altSmtpHost); + emailService.setDebugMode(true); + // 从配置文件中获取产品信息 + ConfigProductRepository configProductRepository = new ConfigProductRepository(); + // 模拟生成邮件的目标用户 + MockUserRepository mockUserRepository = new MockUserRepository(); + + // 促销邮件发送服务 + PromotionEmailService pes = new PromotionEmailService(emailService, configProductRepository, + mockUserRepository); + pes.setFromAddress(fromEmailAddress); + System.out.println("开始发送邮件"); + pes.sendEmail(); + } +} diff --git a/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domainlogic/Email.java b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domainlogic/Email.java new file mode 100644 index 0000000000..4c018874e5 --- /dev/null +++ b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domainlogic/Email.java @@ -0,0 +1,47 @@ +package com.coderising.ood.srp.domainlogic; + +/** + * The Email domain model + * + * @author silencehe09 + * + */ +public class Email { + private String fromAddress; + private String toAddress; + private String subject; + private String message; + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + +} diff --git a/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domainlogic/EmailService.java b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domainlogic/EmailService.java new file mode 100644 index 0000000000..9b8f9ac6ae --- /dev/null +++ b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domainlogic/EmailService.java @@ -0,0 +1,11 @@ +package com.coderising.ood.srp.domainlogic; + +/** + * the interface of email service. + * + * @author silencehe09 + * + */ +public interface EmailService { + void sendEmail(Email email); +} diff --git a/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domainlogic/Product.java b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domainlogic/Product.java new file mode 100644 index 0000000000..ae1d2353ce --- /dev/null +++ b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domainlogic/Product.java @@ -0,0 +1,29 @@ +package com.coderising.ood.srp.domainlogic; + +/** + * The Product domain model + * + * @author silencehe09 + * + */ +public class Product { + private String productID; + private String productDesc; + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + +} diff --git a/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domainlogic/ProductRepository.java b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domainlogic/ProductRepository.java new file mode 100644 index 0000000000..0d1e2d2ac7 --- /dev/null +++ b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domainlogic/ProductRepository.java @@ -0,0 +1,8 @@ +package com.coderising.ood.srp.domainlogic; + +import java.io.IOException; +import java.util.List; + +public abstract class ProductRepository { + public abstract List getPromotionProducts() throws IOException; +} diff --git a/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domainlogic/PromotionEmailService.java b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domainlogic/PromotionEmailService.java new file mode 100644 index 0000000000..e5b5852774 --- /dev/null +++ b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domainlogic/PromotionEmailService.java @@ -0,0 +1,51 @@ +package com.coderising.ood.srp.domainlogic; + +import java.io.IOException; +import java.util.List; + +/** + * 促销邮件发送服务,实现具体的邮件发送业务逻辑 + * + * @author silencehe09 + * + */ +public class PromotionEmailService { + private EmailService emailService; + private ProductRepository productRepository; + private UserRepository userRepository; + private String fromAddress; + + public PromotionEmailService(EmailService emailService, ProductRepository productRepository, + UserRepository userRepository) { + this.emailService = emailService; + this.productRepository = productRepository; + this.userRepository = userRepository; + } + + public void sendEmail() throws IOException { + List users = userRepository.getPromotionUsers(); + List products = productRepository.getPromotionProducts(); + for (Product product : products) { + for (User user : users) { + Email email = new Email(); + email.setFromAddress(fromAddress); + email.setToAddress(user.getEmail()); + email.setSubject(getEmailSubject()); + email.setMessage(getEmailMessage(user, product)); + emailService.sendEmail(email); + } + } + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + private String getEmailSubject() { + return "您关注的产品降价了"; + } + + private String getEmailMessage(User user, Product product) { + return "尊敬的 " + user.getName() + ", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!"; + } +} diff --git a/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domainlogic/User.java b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domainlogic/User.java new file mode 100644 index 0000000000..1dbe849d39 --- /dev/null +++ b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domainlogic/User.java @@ -0,0 +1,29 @@ +package com.coderising.ood.srp.domainlogic; + +/** + * The User domain model + * + * @author silencehe09 + * + */ +public class User { + private String name; + private String email; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + +} diff --git a/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domainlogic/UserRepository.java b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domainlogic/UserRepository.java new file mode 100644 index 0000000000..55274b79f6 --- /dev/null +++ b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domainlogic/UserRepository.java @@ -0,0 +1,7 @@ +package com.coderising.ood.srp.domainlogic; + +import java.util.List; + +public abstract class UserRepository { + public abstract List getPromotionUsers(); +} diff --git a/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/emailconfig.properties b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/emailconfig.properties new file mode 100644 index 0000000000..6f5615d18b --- /dev/null +++ b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/emailconfig.properties @@ -0,0 +1,3 @@ +smtp.server=smtp.163.com +alt.smtp.server=smtp1.163.com +email.admin=admin@company.com \ No newline at end of file diff --git a/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/709960951/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/724222786/ood/ood-assignment/.gitignore b/students/724222786/ood/ood-assignment/.gitignore new file mode 100644 index 0000000000..c948edfead --- /dev/null +++ b/students/724222786/ood/ood-assignment/.gitignore @@ -0,0 +1,4 @@ +.settings\ +target\ +.classpath +.project \ No newline at end of file diff --git a/students/724222786/ood/ood-assignment/pom.xml b/students/724222786/ood/ood-assignment/pom.xml new file mode 100644 index 0000000000..a4d92e7f05 --- /dev/null +++ b/students/724222786/ood/ood-assignment/pom.xml @@ -0,0 +1,38 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + org.apache.logging.log4j + log4j-core + 2.8.2 + + + + + diff --git a/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/Test.java b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/Test.java new file mode 100644 index 0000000000..8dc90b701e --- /dev/null +++ b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/Test.java @@ -0,0 +1,23 @@ +package com.coderising.ood.answer; + +import java.util.List; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import com.coderising.ood.answer.entity.Product; +import com.coderising.ood.answer.service.MailService; +import com.coderising.ood.answer.utils.FileUtils; +import com.coderising.ood.answer.utils.ProductUtils; + +public class Test { + private static final Logger log = LogManager.getLogger(Test.class); + public static void main(String[] args) { + MailService service = new MailService(); + List list = ProductUtils.getList(FileUtils.readFile()); + service.sendMail(list); + + } + + +} diff --git a/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/config/config.properties b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/config/config.properties new file mode 100644 index 0000000000..b798e9274a --- /dev/null +++ b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/config/config.properties @@ -0,0 +1,5 @@ +smtp.server=smtp.163.com +alt.smtp.server=smtp1.163.com +email.admin=admin@company.com + +product.txt=com/coderising/ood/answer/config/product_promotion.txt \ No newline at end of file diff --git a/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/config/product_promotion.txt b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/config/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/config/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/entity/MailMessage.java b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/entity/MailMessage.java new file mode 100644 index 0000000000..cb95f6296c --- /dev/null +++ b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/entity/MailMessage.java @@ -0,0 +1,63 @@ +package com.coderising.ood.answer.entity; + +import java.io.Serializable; + +import com.coderising.ood.answer.utils.ConfigUtils; + +/** + * 邮件类 + * @author readke + * + */ +public class MailMessage implements Serializable{ + + private static final long serialVersionUID = -3221160075625357827L; + + private String toAddr; + private String fromAddr; + private String subject; + private String content; + + public static MailMessage getMessage(String from,String subject,String content,Product p,User u){ + MailMessage m = new MailMessage(); + if(content != null && !content.isEmpty()) + content = "尊敬的 "+u.getName()+", 您关注的产品 " + p.getpDec() + " 降价了,欢迎购买!" ; + if(subject != null && !subject.isEmpty()){ + subject = "您关注的产品降价了"; + } + if(from != null && !from.isEmpty()){ + from = ConfigUtils.getProperty("smtp.server"); + } + m.setFromAddr(from); + m.setToAddr(u.getEmail()); + m.setSubject(subject); + m.setContent(content); + return m; + } + + public String getToAddr() { + return toAddr; + } + public void setToAddr(String toAddr) { + this.toAddr = toAddr; + } + public String getFromAddr() { + return fromAddr; + } + public void setFromAddr(String fromAddr) { + this.fromAddr = fromAddr; + } + public String getSubject() { + return subject; + } + public void setSubject(String subject) { + this.subject = subject; + } + public String getContent() { + return content; + } + public void setContent(String content) { + this.content = content; + } + +} diff --git a/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/entity/Product.java b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/entity/Product.java new file mode 100644 index 0000000000..2b4a81535e --- /dev/null +++ b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/entity/Product.java @@ -0,0 +1,38 @@ +package com.coderising.ood.answer.entity; + +import java.io.Serializable; + +/** + * 产品类 + * @author readke + * + */ +public class Product implements Serializable{ + private static final long serialVersionUID = 409352331475497580L; + + private String pId; + private String pDec; + + public Product() { + + } + public Product(String pId, String pDec) { + super(); + this.pId = pId; + this.pDec = pDec; + } + public String getpId() { + return pId; + } + public void setpId(String pId) { + this.pId = pId; + } + public String getpDec() { + return pDec; + } + public void setpDec(String pDec) { + this.pDec = pDec; + } + + +} diff --git a/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/entity/User.java b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/entity/User.java new file mode 100644 index 0000000000..dd71a8e26f --- /dev/null +++ b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/entity/User.java @@ -0,0 +1,35 @@ +package com.coderising.ood.answer.entity; + +import java.io.Serializable; + +/** + * 用户类 + * @author readke + * + */ +public class User implements Serializable{ + private static final long serialVersionUID = -7916484660512326120L; + + private String id; + private String name; + private String email; + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + +} diff --git a/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/service/MailService.java b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/service/MailService.java new file mode 100644 index 0000000000..cb63b8a2d1 --- /dev/null +++ b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/service/MailService.java @@ -0,0 +1,27 @@ +package com.coderising.ood.answer.service; + +import java.util.List; + +import com.coderising.ood.answer.entity.MailMessage; +import com.coderising.ood.answer.entity.Product; +import com.coderising.ood.answer.entity.User; +import com.coderising.ood.answer.utils.DBUtils; +import com.coderising.ood.answer.utils.MailUtils; + +/** + * 邮件发送服务 + * @author readke + * + */ +public class MailService { + public void sendMail(List list){ + + for(Product p: list){ + List uList = DBUtils.queryByProductID(p.getpId()); + for(User u : uList){ + MailMessage m = MailMessage.getMessage("","", "", p, u); + MailUtils.sendMail(m); + } + } + } +} diff --git a/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/utils/ConfigUtils.java b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/utils/ConfigUtils.java new file mode 100644 index 0000000000..3b67cbf5fb --- /dev/null +++ b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/utils/ConfigUtils.java @@ -0,0 +1,48 @@ +package com.coderising.ood.answer.utils; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +/** + * 配置文件读取工具 + * @author readke + * + */ +public class ConfigUtils { + + private static final Logger log = LogManager.getLogger(ConfigUtils.class); + private static Properties prop = null; + + static { + InputStream in = ConfigUtils.class.getResourceAsStream("../config/config.properties"); + prop = new Properties(); + //System.out.println(in); + try { + prop.load(in); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + }finally { + if(in != null){ + try { + in.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + } + + public static String getProperty(String key){ + return prop.getProperty(key); + } + + public static void main(String[] args) { + log.info(ConfigUtils.getProperty("smtp.server")); + } +} diff --git a/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/utils/DBUtils.java b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/utils/DBUtils.java new file mode 100644 index 0000000000..757098ef6c --- /dev/null +++ b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/utils/DBUtils.java @@ -0,0 +1,32 @@ +package com.coderising.ood.answer.utils; + +import java.util.ArrayList; +import java.util.List; + +import com.coderising.ood.answer.entity.User; + +/** + * db工具 + * @author readke + * + */ +public class DBUtils { + + public static List queryByProductID(String productID){ + /** + * sql = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + */ + List userList = new ArrayList(); + + for (int i = 1; i <= 3; i++) { + User userInfo = new User(); + userInfo.setName("User" + i); + userInfo.setEmail("aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/utils/FileUtils.java b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/utils/FileUtils.java new file mode 100644 index 0000000000..03dfcfe66d --- /dev/null +++ b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/utils/FileUtils.java @@ -0,0 +1,39 @@ +package com.coderising.ood.answer.utils; + +import java.io.BufferedReader; +import java.io.File; +import java.net.URI; +import java.net.URL; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +/** + * 文件读取工具 + * @author readke + * + */ +public class FileUtils { + private static final Logger log = LogManager.getLogger(FileUtils.class); + public static File readFile(){ + + File file = null; + BufferedReader br = null; + + try { + URL url = FileUtils.class.getClassLoader().getResource(ConfigUtils.getProperty("product.txt")); + log.info(url.getPath()); + URI uri = url.toURI(); + file = new File(uri); + + }catch (Exception e) { + // TODO: handle exception + e.printStackTrace(); + } + return file; + } + + public static void main(String[] args) { + readFile(); + } +} diff --git a/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/utils/MailUtils.java b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/utils/MailUtils.java new file mode 100644 index 0000000000..6d08cd7968 --- /dev/null +++ b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/utils/MailUtils.java @@ -0,0 +1,49 @@ +package com.coderising.ood.answer.utils; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import com.coderising.ood.answer.entity.MailMessage; + +/** + * 邮件发送工具 + * @author readke + * + */ +public class MailUtils { + private static final Logger log = LogManager.getLogger(MailUtils.class); + + private static final String SMTP_SERVER = ConfigUtils.getProperty("smtp.server"); + private static final String ALT_SMTP_SERVER = ConfigUtils.getProperty("alt.smtp.server"); + + public static void sendMail(MailMessage email){ + try{ + sendMail(email, SMTP_SERVER); + log.info("使用主服务器发送邮件"); + log.info("发送成功"); + }catch (Exception e) { + try{ + sendMail(email, ALT_SMTP_SERVER); + log.info("使用备用服务器发送邮件"); + }catch (Exception e1){ + log.error("发送失败"); + } + } + } + + public static void sendMail(MailMessage email,String server) throws Exception{ + sendMail(email.getFromAddr(), email.getToAddr(), + server, email.getSubject(), email.getContent()); + } + + public static void sendMail(String from,String to,String server,String subject,String content) throws Exception{ + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(from).append("\n"); + buffer.append("To:").append(to).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(content).append("\n"); + System.out.println(buffer.toString()); + } + + +} diff --git a/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/utils/ProductUtils.java b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/utils/ProductUtils.java new file mode 100644 index 0000000000..1b854bfeb7 --- /dev/null +++ b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/answer/utils/ProductUtils.java @@ -0,0 +1,52 @@ +package com.coderising.ood.answer.utils; + +import java.io.BufferedInputStream; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import com.coderising.ood.answer.entity.Product; + +/** + * 产品工具 + * @author readke + * + */ +public class ProductUtils { + private static final Logger log = LogManager.getLogger(ProductUtils.class); + + public static List getList(File file){ + List list = null; + BufferedReader br = null; + + try { + list = new ArrayList<>(); + br = new BufferedReader(new FileReader(file)); + while(br.ready()){ + Product p = new Product(); + String temp = br.readLine(); + String[] data = temp.split(" "); + p.setpId(data[0]); + p.setpDec(data[1]); + list.add(p); + } + + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return list; + } + +} diff --git a/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..9f9e749af7 --- /dev/null +++ b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..781587a846 --- /dev/null +++ b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,199 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery = null; + + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected String productID = null; + protected String productDesc = null; + + private static Configuration config; + + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + + + config = new Configuration(); + + setSMTPHost(); + setAltSMTPHost(); + + + setFromAddress(); + + + setLoadQuery(); + + sendEMails(mailDebug, loadMailingList()); + + + } + + + + + protected void setProductID(String productID) + { + this.productID = productID; + + } + + protected String getproductID() + { + return productID; + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected void setSMTPHost() + { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() + { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + protected void setFromAddress() + { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setMessage(HashMap userInfo) throws IOException + { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + + + + } + + + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + private void setProductDesc(String desc) { + this.productDesc = desc; + } + + + protected void configureEMail(HashMap userInfo) throws IOException + { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try + { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } + + else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/724222786/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/724222786/ood/ood-assignment/src/main/java/log4j2.xml b/students/724222786/ood/ood-assignment/src/main/java/log4j2.xml new file mode 100644 index 0000000000..6fc38d8b1b --- /dev/null +++ b/students/724222786/ood/ood-assignment/src/main/java/log4j2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/students/727171008/src/com/coderising/ood/ocp/Formatter.java b/students/727171008/src/com/coderising/ood/ocp/Formatter.java new file mode 100644 index 0000000000..07391dacab --- /dev/null +++ b/students/727171008/src/com/coderising/ood/ocp/Formatter.java @@ -0,0 +1,5 @@ +package com.coderising.ood.ocp; + +public interface Formatter { + String formate(String msg); +} diff --git a/students/727171008/src/com/coderising/ood/ocp/FormatterFactory.java b/students/727171008/src/com/coderising/ood/ocp/FormatterFactory.java new file mode 100644 index 0000000000..4d6cc9603e --- /dev/null +++ b/students/727171008/src/com/coderising/ood/ocp/FormatterFactory.java @@ -0,0 +1,14 @@ +package com.coderising.ood.ocp; + +public class FormatterFactory { + public Formatter createFormatter(int type) { + Formatter formatter = null; + if (type == 1) { + formatter = new RawFormatter(); + } + if (type == 2) { + formatter = new HtmlFormatter(); + } + return formatter; + } +} diff --git a/students/727171008/src/com/coderising/ood/ocp/HtmlFormatter.java b/students/727171008/src/com/coderising/ood/ocp/HtmlFormatter.java new file mode 100644 index 0000000000..6d3d76f58e --- /dev/null +++ b/students/727171008/src/com/coderising/ood/ocp/HtmlFormatter.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp; + +public class HtmlFormatter implements Formatter { + + @Override + public String formate(String msg) { + + return null; + } + +} diff --git a/students/727171008/src/com/coderising/ood/ocp/LogTestDrive.java b/students/727171008/src/com/coderising/ood/ocp/LogTestDrive.java new file mode 100644 index 0000000000..d96987e6d4 --- /dev/null +++ b/students/727171008/src/com/coderising/ood/ocp/LogTestDrive.java @@ -0,0 +1,20 @@ +package com.coderising.ood.ocp; + +public class LogTestDrive { + + public static void main(String[] args) { + FormatterFactory ff = new FormatterFactory(); + SenderFactory sf = new SenderFactory(); + + Formatter formatter = ff.createFormatter(1); + Sender sender = sf.createSender(1); + + Logger logger = new Logger(formatter, sender); + String msg = "此处应该从文本读取?或者html读取?"; + logger.log(msg); + + System.out.println("end"); + + } + +} diff --git a/students/727171008/src/com/coderising/ood/ocp/Logger.java b/students/727171008/src/com/coderising/ood/ocp/Logger.java new file mode 100644 index 0000000000..a02cf8658c --- /dev/null +++ b/students/727171008/src/com/coderising/ood/ocp/Logger.java @@ -0,0 +1,15 @@ +package com.coderising.ood.ocp; + +public class Logger { + private Formatter formatter; + private Sender sender; + + public Logger(Formatter formatter, Sender sender) { + this.formatter = formatter; + this.sender = sender; + } + + public void log(String msg) { + sender.send(formatter.formate(msg)); + } +} diff --git a/students/727171008/src/com/coderising/ood/ocp/MailSenderImp.java b/students/727171008/src/com/coderising/ood/ocp/MailSenderImp.java new file mode 100644 index 0000000000..ab79fe070b --- /dev/null +++ b/students/727171008/src/com/coderising/ood/ocp/MailSenderImp.java @@ -0,0 +1,12 @@ +package com.coderising.ood.ocp; + +public class MailSenderImp implements Sender { + + @Override + public String send(String msg) { + + return "Raw data "; + + } + +} diff --git a/students/727171008/src/com/coderising/ood/ocp/PrintSenderImp.java b/students/727171008/src/com/coderising/ood/ocp/PrintSenderImp.java new file mode 100644 index 0000000000..22a4c8db2b --- /dev/null +++ b/students/727171008/src/com/coderising/ood/ocp/PrintSenderImp.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp; + +public class PrintSenderImp implements Sender { + + @Override + public String send(String msg) { + + return "print "; + } + +} diff --git a/students/727171008/src/com/coderising/ood/ocp/RawFormatter.java b/students/727171008/src/com/coderising/ood/ocp/RawFormatter.java new file mode 100644 index 0000000000..762917e981 --- /dev/null +++ b/students/727171008/src/com/coderising/ood/ocp/RawFormatter.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class RawFormatter implements Formatter { + + @Override + public String formate(String msg) { + return null; + } + +} diff --git a/students/727171008/src/com/coderising/ood/ocp/SMSSenderImp.java b/students/727171008/src/com/coderising/ood/ocp/SMSSenderImp.java new file mode 100644 index 0000000000..6aaa16f23e --- /dev/null +++ b/students/727171008/src/com/coderising/ood/ocp/SMSSenderImp.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp; + +public class SMSSenderImp implements Sender { + + @Override + public String send(String msg) { + + return "SMS data "; + } + +} diff --git a/students/727171008/src/com/coderising/ood/ocp/Sender.java b/students/727171008/src/com/coderising/ood/ocp/Sender.java new file mode 100644 index 0000000000..4c54985454 --- /dev/null +++ b/students/727171008/src/com/coderising/ood/ocp/Sender.java @@ -0,0 +1,5 @@ +package com.coderising.ood.ocp; + +public interface Sender { + String send(String msg); +} diff --git a/students/727171008/src/com/coderising/ood/ocp/SenderFactory.java b/students/727171008/src/com/coderising/ood/ocp/SenderFactory.java new file mode 100644 index 0000000000..96663989cf --- /dev/null +++ b/students/727171008/src/com/coderising/ood/ocp/SenderFactory.java @@ -0,0 +1,17 @@ +package com.coderising.ood.ocp; + +public class SenderFactory { + public Sender createSender(int type) { + Sender sender = null; + if(type == 1) { + sender = new MailSenderImp(); + } + if (type == 2) { + sender = new SMSSenderImp(); + } + if (type == 3) { + sender = new PrintSenderImp(); + } + return sender; + } +} diff --git a/students/727171008/src/com/coderising/ood/srp/Configuration.java b/students/727171008/src/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..5a52efee25 --- /dev/null +++ b/students/727171008/src/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,26 @@ +package com.coderising.ood.srp; + +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static { + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/727171008/src/com/coderising/ood/srp/ConfigurationKeys.java b/students/727171008/src/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..945db9004a --- /dev/null +++ b/students/727171008/src/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp.good1; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/727171008/src/com/coderising/ood/srp/Mail.java b/students/727171008/src/com/coderising/ood/srp/Mail.java new file mode 100644 index 0000000000..8ecea4a35e --- /dev/null +++ b/students/727171008/src/com/coderising/ood/srp/Mail.java @@ -0,0 +1,34 @@ +package com.coderising.ood.srp; + +import java.util.List; + +public class Mail { + private User user; + + public Mail(User user) { + this.user = user; + } + + public String getAddress() { + return user.getEMailAddress(); + } + + public String getSubjcet() { + return "您关注的商品降价了!"; + } + + public String getBody() { + return "尊敬的用户: " + user.getName() + ", 您关注的商品: " + this.buildProductDescList(); + } + + private String buildProductDescList() { + List products = user.getSubscribedProducts(); + + return null; + } + + public String getSubject() { + + return null; + } +} diff --git a/students/727171008/src/com/coderising/ood/srp/MailSender.java b/students/727171008/src/com/coderising/ood/srp/MailSender.java new file mode 100644 index 0000000000..48c29ac877 --- /dev/null +++ b/students/727171008/src/com/coderising/ood/srp/MailSender.java @@ -0,0 +1,35 @@ +package com.coderising.ood.srp; + +public class MailSender { + + private String fromAddress; + private String smtpHost; + private String altSmtpHost; + + public MailSender(Configuration config) { + this.fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + this.smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + this.altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + } + + public void sendMail(Mail mail) { + try { + sendEmail(mail, this.smtpHost); + } catch (Exception e) { + try { + sendEmail(mail, this.altSmtpHost); + } catch (Exception ex) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + ex.getMessage()); + } + + } + } + + private void sendEmail(Mail mail, String smtpHost) { + + String toAddress = mail.getAddress(); + String subject = mail.getSubject(); + String msg = mail.getBody(); + // 发送邮件 + } +} diff --git a/students/727171008/src/com/coderising/ood/srp/Product.java b/students/727171008/src/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..d04cdb97f4 --- /dev/null +++ b/students/727171008/src/com/coderising/ood/srp/Product.java @@ -0,0 +1,10 @@ +package com.coderising.ood.srp; + +public class Product { + private String id; + private String desc; + + public String getDesc() { + return desc; + } +} diff --git a/students/727171008/src/com/coderising/ood/srp/ProductService.java b/students/727171008/src/com/coderising/ood/srp/ProductService.java new file mode 100644 index 0000000000..5eea405243 --- /dev/null +++ b/students/727171008/src/com/coderising/ood/srp/ProductService.java @@ -0,0 +1,16 @@ +package com.coderising.ood.srp; + +import java.io.File; + +public class ProductService { + public Product getPromotionProduct() { + File f = new File("F:\\coding2017\\com\\codering\\ood\\src\\product_promotion.txt"); + Product product = readFile(f); + return product; + } + + private Product readFile(File file) { + + return null; + } +} diff --git a/students/727171008/src/com/coderising/ood/srp/PromotionJob.java b/students/727171008/src/com/coderising/ood/srp/PromotionJob.java new file mode 100644 index 0000000000..616335aa05 --- /dev/null +++ b/students/727171008/src/com/coderising/ood/srp/PromotionJob.java @@ -0,0 +1,24 @@ +package com.coderising.ood.srp; + +import java.util.List; + +public class PromotionJob { + + private ProductService productService = null; // 获取production service + private UserService userService = null;// 获取UserService + + public void run() { + + Configuration cfg = new Configuration(); + + Product p = productService.getPromotionProduct(); + + List users = userService.getUsers(p); //一次只读取了一件商品 + + MailSender mailSender = new MailSender(cfg); + + for (User user : users) { + mailSender.sendMail(new Mail(user)); + } + } +} diff --git a/students/727171008/src/com/coderising/ood/srp/User.java b/students/727171008/src/com/coderising/ood/srp/User.java new file mode 100644 index 0000000000..a79bc5c97a --- /dev/null +++ b/students/727171008/src/com/coderising/ood/srp/User.java @@ -0,0 +1,26 @@ +package com.coderising.ood.srp; + +import java.util.List; + +public class User { + + private String name; + private String emailAddress; + + private List subscribedProducts; + + public String getName() { + + return name; + } + + public String getEMailAddress() { + + return emailAddress; + } + + public List getSubscribedProducts() { + + return this.subscribedProducts; + } +} diff --git a/students/727171008/src/com/coderising/ood/srp/UserService.java b/students/727171008/src/com/coderising/ood/srp/UserService.java new file mode 100644 index 0000000000..9bc682a229 --- /dev/null +++ b/students/727171008/src/com/coderising/ood/srp/UserService.java @@ -0,0 +1,11 @@ +package com.coderising.ood.srp; + +import java.util.List; + +public class UserService { + + public List getUsers(Product product) { + // 调用DAO相关的类从数据库中读取订阅产品的用户列表 + return null; + } +} diff --git a/students/727171008/src/com/coderising/ood/srp/product_promotion.txt b/students/727171008/src/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/727171008/src/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/729693763/1.ood/ood-assignment/pom.xml b/students/729693763/1.ood/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/729693763/1.ood/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtil.java b/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtil.java new file mode 100644 index 0000000000..a02504fd05 --- /dev/null +++ b/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/FileUtil.java @@ -0,0 +1,64 @@ + +package com.coderising.ood.srp; +/** + * @author 作者 Denny + * @date 创建时间:Jun 25, 2017 10:27:58 AM + * @version 1.0 + * @parameter + * @since + * @return */ + +import java.util.List; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedList; + +public class FileUtil { + + /** + * 根据文件路径获取文件,如果文件不存在,抛出异常 + * @param fileName + * @return + * @throws FileNotFoundException + */ + public static File readFile(String fileName) throws FileNotFoundException{ + File file = new File(fileName); + if(!file.exists()){ + throw new FileNotFoundException(); + } + return file; + } + + public static List parseToString(File file, String regex) { + List list = new ArrayList(); + BufferedReader bf= null; + try { + if(file != null && file.exists( )){ + bf = new BufferedReader(new FileReader(file)); + String temp = null; + while ((temp = bf.readLine()) != null) { + String[] strs = temp.split(regex); + list.add(strs); + } + } + } catch (Exception e) { + // TODO: handle exception + e.printStackTrace(); + }finally { + if(bf != null){ + try { + bf.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + return list; + } + +} diff --git a/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..3c367759c4 --- /dev/null +++ b/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,48 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + + /** + * 邮件单元是需要管理邮件的,包括发送到哪,端口主机等等 + */ + private static String fromAddress = ""; + private static String smtpHost = ""; + private static String altSmtpHost = ""; + + + private static Configuration config = new Configuration(); + + public static void ConfigureEmail() { + altSmtpHost = (String) config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + fromAddress = (String) config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + smtpHost = (String) config.getProperty(ConfigurationKeys.SMTP_SERVER); + + } + + + public static void sendEmail(String toAddress,String subject,String message) { + ConfigureEmail(); + //假装发了一封邮件 + try{ + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + } catch (Exception e) { + try { + System.out.println("备用SMTP服务器: "); + MailUtil.sendEmail(toAddress, subject, message); + + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + + + } + + +} diff --git a/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..902b6ff341 --- /dev/null +++ b/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,108 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +public class PromotionMail { + + protected String subject = null; + protected String message = null; + + private static List products = new ArrayList(); + + private static String filePath = "/Users/vi/Desktop/ood/ood-assignment/bin/src/main/java/com/coderising/ood/srp/product_promotion.txt"; + + private static ServerDAO server = new ServerDAO(); + + public static void main(String[] args) throws Exception { + + File f = new File(filePath); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f); + for (String[] data : products) { + List> list = pe.loadMailingList(data[0]); + if (list != null && list.size() > 0) { + pe.sendEMails(list, data[1]); + } + } + + + + } + + /** + * 构造器,初始化应该加载商品的详细信息。 + * @param file + * @throws IOException + */ + public PromotionMail(File file) throws IOException { + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + } + +// /** +// * 促销邮件; +// * @param file +// * @param mailDebug +// * @throws Exception +// */ +// public PromotionMail(File file, boolean mailDebug) throws Exception { +// +// setLoadQuery(); +// +// sendEMails(mailDebug, loadMailingList()); +// } +// + + protected void setMessage(String name, String productDesc) throws IOException { + this.subject = "您关注的产品降价了"; + this.message = "尊敬的 " + name + ", 您关注的产品 " + productDesc + " 降价了,欢迎购买!"; + } + + protected void readFile(File file) throws IOException // @02C + { + List list = FileUtil.parseToString(file, " "); + if(list != null && !list.isEmpty()){ + products = list; + for (String[] data: products) { + System.out.println("产品ID = " + data[0] + "\n"); + System.out.println("产品描述 = " + data[1] + "\n"); + } + } + } + + + + protected List loadMailingList(String productID) throws Exception { + return server.getList(productID); + } + + + protected void sendEMails(List> mailingList,String productDesc) throws IOException + { + System.out.println("开始发送邮件"); + + if (mailingList != null) { + Iterator> iter = mailingList.iterator(); + while (iter.hasNext()) { + Map map = iter.next(); + String toAddress = (String) map.get("EMAIL"); + String name = (String) map.get("NAME"); + setMessage(name, productDesc); + if (toAddress != null && toAddress.length() > 0) + MailUtil.sendEmail(toAddress, subject, message); + } + } else { + System.out.println("没有邮件发送"); + } + } +} diff --git a/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/ServerDAO.java b/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/ServerDAO.java new file mode 100644 index 0000000000..30a4c5bdde --- /dev/null +++ b/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/ServerDAO.java @@ -0,0 +1,31 @@ + +package com.coderising.ood.srp; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * @author 作者 Denny + * @date 创建时间:Jun 25, 2017 2:20:04 PM + * @version 1.0 + * @parameter + * @since + * @return */ +public class ServerDAO { + public List> getList(String productID) { + // TODO Auto-generated method stub + List> list = new ArrayList>(); + String sql = "Select name from subscriptions " + "where product_id= '" + productID + "' " + + "and send_mail=1 "; + + System.out.println("loadQuery set"); + try { + list = DBUtil.query(sql); + } catch (Exception e) { + e.printStackTrace(); + } + + return list; + } +} diff --git a/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/729693763/1.ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/Circle.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/Circle.java new file mode 100644 index 0000000000..af7b07c91b --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/Circle.java @@ -0,0 +1,20 @@ +package bridge; + +public class Circle implements Shape { + + private int x; + private int y; + private int r; + + public Circle(int x, int y, int r) { + this.x = x; + this.y = y; + this.r = r; + } + + @Override + public void draw(GraphicLibrary gl) { + gl.drawCircle(x, y, r); + } + +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/GraphicLibrary.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/GraphicLibrary.java new file mode 100644 index 0000000000..73088a9324 --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/GraphicLibrary.java @@ -0,0 +1,9 @@ +package bridge; + +public interface GraphicLibrary { + + void drawRectangle(int x1, int y1, int x2, int y2); + + void drawCircle(int x, int y, int r); + +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/GraphicLibrary1.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/GraphicLibrary1.java new file mode 100644 index 0000000000..a53f877500 --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/GraphicLibrary1.java @@ -0,0 +1,26 @@ +package bridge; + +public class GraphicLibrary1 implements GraphicLibrary { + + @Override + public void drawRectangle(int x1, int y1, int x2, int y2) { + draw_a_line(x1, y1, x1, y2); + draw_a_line(x1, y2, x2, y2); + draw_a_line(x2, y2, x2, y1); + draw_a_line(x2, y1, x1, y1); + } + + @Override + public void drawCircle(int x, int y, int r) { + draw_a_circle(x, y, r); + } + + private void draw_a_line(int x1, int y1, int x2, int y2) { + + } + + private void draw_a_circle(int x, int y, int r) { + + } + +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/GraphicLibrary2.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/GraphicLibrary2.java new file mode 100644 index 0000000000..6ad1bdc5dd --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/GraphicLibrary2.java @@ -0,0 +1,21 @@ +package bridge; + +public class GraphicLibrary2 implements GraphicLibrary { + + @Override + public void drawRectangle(int x1, int y1, int x2, int y2) { + drawLine(x1, x2, y1, y2); + drawLine(x1, x2, y2, y2); + drawLine(x2, x2, y2, y1); + drawLine(x2, x1, y1, y1); + } + + @Override + public void drawCircle(int x,int y, int r) { + + } + + private void drawLine(int x1, int x2, int y1, int y2) { + } + +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/Rectangle.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/Rectangle.java new file mode 100644 index 0000000000..471c2b94ec --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/Rectangle.java @@ -0,0 +1,21 @@ +package bridge; + +public class Rectangle implements Shape { + + private int x1; + private int y1; + private int x2; + private int y2; + + public Rectangle(int x1, int y1, int x2, int y2) { + this.x1 = x1; + this.y1 = y1; + this.x2 = x2; + this.y2 = y2; + } + + @Override + public void draw(GraphicLibrary gl) { + gl.drawRectangle(x1, y1, x2, y2); + } +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/Shape.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/Shape.java new file mode 100644 index 0000000000..1b6e584cd4 --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/bridge/Shape.java @@ -0,0 +1,7 @@ +package bridge; + +public interface Shape { + + void draw(GraphicLibrary gl); + +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/command/Command.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/command/Command.java new file mode 100644 index 0000000000..dd04cf6efe --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/command/Command.java @@ -0,0 +1,11 @@ +package command; + +/** + * Created by Lu on 2017/08/13. + * @author Lu Mingming + */ +public interface Command { + + void execute(); + +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/command/CommandTest.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/command/CommandTest.java new file mode 100644 index 0000000000..28f5319e3b --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/command/CommandTest.java @@ -0,0 +1,22 @@ +package command; + +/** + * Created by Lu on 2017/08/13. + * @author Lu Mingming + */ +public class CommandTest { + + public static void main(String[] args) { + Cook cook = new Cook(); + Waiter waiter = new Waiter(); + + Command command1 = new OrderSteakCommand(cook); + Command command2 = new OrderPorkCommand(cook); + + waiter.addOrder(command1); + waiter.addOrder(command2); + + waiter.sendOrders(); + } + +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/command/Cook.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/command/Cook.java new file mode 100644 index 0000000000..bf6b47b77b --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/command/Cook.java @@ -0,0 +1,17 @@ +package command; + +/** + * Created by Lu on 2017/08/13. + * @author Lu Mingming + */ +public class Cook { + + public void cookSteak() { + System.out.println("Steak is ok"); + } + + public void cookPork() { + System.out.println("Pork is ok"); + } + +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/command/OrderPorkCommand.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/command/OrderPorkCommand.java new file mode 100644 index 0000000000..771588e093 --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/command/OrderPorkCommand.java @@ -0,0 +1,19 @@ +package command; + +/** + * Created by Lu on 2017/08/13. + * @author Lu Mingming + */ +public class OrderPorkCommand implements Command { + + private Cook cook; + + public OrderPorkCommand(Cook cook) { + this.cook = cook; + } + + @Override + public void execute() { + cook.cookPork(); + } +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/command/OrderSteakCommand.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/command/OrderSteakCommand.java new file mode 100644 index 0000000000..99c399d284 --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/command/OrderSteakCommand.java @@ -0,0 +1,19 @@ +package command; + +/** + * Created by Lu on 2017/08/13. + * @author Lu Mingming + */ +public class OrderSteakCommand implements Command { + + private Cook cook; + + public OrderSteakCommand(Cook cook) { + this.cook = cook; + } + + @Override + public void execute() { + cook.cookSteak(); + } +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/command/Waiter.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/command/Waiter.java new file mode 100644 index 0000000000..96cf2bcd38 --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/command/Waiter.java @@ -0,0 +1,24 @@ +package command; + +import java.util.LinkedList; +import java.util.Queue; + +/** + * Created by Lu on 2017/08/13. + * @author Lu Mingming + */ +public class Waiter { + + Queue commands = new LinkedList<>(); + + public void addOrder(Command command) { + commands.add(command); + } + + public void sendOrders() { + while (!commands.isEmpty()) { + commands.poll().execute(); + } + } + +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Line.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Line.java new file mode 100644 index 0000000000..d15975aaad --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Line.java @@ -0,0 +1,9 @@ +package composite; + +public class Line implements Shape { + + @Override + public void draw() { + } + +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Picture.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Picture.java new file mode 100644 index 0000000000..80bfa14450 --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Picture.java @@ -0,0 +1,17 @@ +package composite; + +import java.util.ArrayList; +import java.util.List; + +public class Picture implements Shape { + private final List shapes = new ArrayList<>(); + + @Override + public void draw() { + shapes.forEach(shape -> draw()); + } + + public void add(Shape shape) { + shapes.add(shape); + } +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Rectangle.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Rectangle.java new file mode 100644 index 0000000000..4902fbcd99 --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Rectangle.java @@ -0,0 +1,11 @@ +package composite; + +public class Rectangle implements Shape { + + @Override + public void draw() { + // TODO Auto-generated method stub + + } + +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Shape.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Shape.java new file mode 100644 index 0000000000..8864087e5f --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Shape.java @@ -0,0 +1,5 @@ +package composite; + +public interface Shape { + public void draw(); +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Square.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Square.java new file mode 100644 index 0000000000..9aff729f35 --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Square.java @@ -0,0 +1,10 @@ +package composite; + +public class Square implements Shape { + + @Override + public void draw() { + // TODO Auto-generated method stub + } + +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Text.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Text.java new file mode 100644 index 0000000000..15305bb9e6 --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/composite/Text.java @@ -0,0 +1,10 @@ +package composite; + +public class Text implements Shape { + + @Override + public void draw() { + // TODO Auto-generated method stub + } + +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/Email.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/Email.java new file mode 100644 index 0000000000..c36050aa31 --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/Email.java @@ -0,0 +1,8 @@ +package decorator; + +public interface Email { + + String getContent(); + +} + diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/EmailDecorator.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/EmailDecorator.java new file mode 100644 index 0000000000..0cadd60575 --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/EmailDecorator.java @@ -0,0 +1,4 @@ +package decorator; + +public abstract class EmailDecorator implements Email { +} \ No newline at end of file diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/EmailImpl.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/EmailImpl.java new file mode 100644 index 0000000000..7044dc9c47 --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/EmailImpl.java @@ -0,0 +1,14 @@ +package decorator; + +public class EmailImpl implements Email { + + private String content; + + public EmailImpl(String content) { + this.content = content; + } + + public String getContent() { + return content; + } +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/ExternalEmail.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/ExternalEmail.java new file mode 100644 index 0000000000..1dc01a34bf --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/ExternalEmail.java @@ -0,0 +1,14 @@ +package decorator; + +public class ExternalEmail extends EmailDecorator { + + private Email email; + + public ExternalEmail(Email email) { + this.email = email; + } + + public String getContent() { + return email.getContent() + "\n\n本邮件仅为个人观点,并不代表公司立场"; + } +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/InternalEmail.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/InternalEmail.java new file mode 100644 index 0000000000..885a7573db --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/decorator/InternalEmail.java @@ -0,0 +1,11 @@ +package decorator; + +public class InternalEmail extends EmailDecorator { + + private Email email; + + public String getContent() { + return email.getContent(); + } + +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/interpreter/EmailLogger.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/interpreter/EmailLogger.java new file mode 100644 index 0000000000..7646017b72 --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/interpreter/EmailLogger.java @@ -0,0 +1,24 @@ +package interpreter; + +/** + * Created by Lu on 2017/08/13. + * @author Lu Mingming + */ +public class EmailLogger extends Logger { + + public EmailLogger(int mode) { + this.mode = mode; + } + + @Override + public void message(String msg, int mode) { + msg = "EmailLogger#" + msg; + if (mode == this.mode) { + System.out.println(msg); + return; + } + if (nextLogger != null) { + nextLogger.message(msg, mode); + } + } +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/interpreter/FileLogger.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/interpreter/FileLogger.java new file mode 100644 index 0000000000..7e6e09cc2d --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/interpreter/FileLogger.java @@ -0,0 +1,24 @@ +package interpreter; + +/** + * Created by Lu on 2017/08/13. + * @author Lu Mingming + */ +public class FileLogger extends Logger { + + public FileLogger(int mode) { + this.mode = mode; + } + + @Override + public void message(String msg, int mode) { + msg = "FileLogger#" + msg; + if (mode == this.mode) { + System.out.println(msg); + return; + } + if (nextLogger != null) { + nextLogger.message(msg, mode); + } + } +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/interpreter/Logger.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/interpreter/Logger.java new file mode 100644 index 0000000000..347a5e6c5d --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/interpreter/Logger.java @@ -0,0 +1,22 @@ +package interpreter; + +/** + * Created by Lu on 2017/08/13. + * @author Lu Mingming + */ +public abstract class Logger { + + public static final int DEBUG = 1; + public static final int NOTICE = 2; + public static final int ERR = 3; + + protected int mode; + protected Logger nextLogger; + + public abstract void message(String msg, int mode); + + public Logger setNext(Logger logger) { + nextLogger = logger; + return this; + } +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/interpreter/LoggerTest.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/interpreter/LoggerTest.java new file mode 100644 index 0000000000..fd2aa0a1f4 --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/interpreter/LoggerTest.java @@ -0,0 +1,19 @@ +package interpreter; + +/** + * Created by Lu on 2017/08/13. + * @author Lu Mingming + */ +public class LoggerTest { + + public static void main(String[] args) { + Logger logger = new StdoutLogger(Logger.DEBUG).setNext( + new EmailLogger(Logger.NOTICE).setNext( + new FileLogger(Logger.ERR))); + + logger.message("进入计算函数", Logger.DEBUG); + logger.message("第一步已经完成", Logger.NOTICE); + logger.message("一个致命的错误发成了", Logger.ERR); + } + +} diff --git a/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/interpreter/StdoutLogger.java b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/interpreter/StdoutLogger.java new file mode 100644 index 0000000000..99661de1e4 --- /dev/null +++ b/students/729770920/ood/ood-assignment/src/main/java/com/coderising/dp/interpreter/StdoutLogger.java @@ -0,0 +1,26 @@ +package interpreter; + +/** + * Created by Lu on 2017/08/13. + * @author Lu Mingming + */ +public class StdoutLogger extends Logger { + + public StdoutLogger(int mode) { + this.mode = mode; + } + + @Override + public void message(String msg, int mode) { + msg = "StdoutLogger#" + msg; + if (mode == this.mode) { + System.out.println(msg); + return; + } + if (nextLogger != null) { + nextLogger.message(msg, mode); + } + } + + +} diff --git a/students/734473301/coding2017jyz/product_promotion.txt b/students/734473301/coding2017jyz/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/734473301/coding2017jyz/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/734473301/coding2017jyz/readme.txt b/students/734473301/coding2017jyz/readme.txt new file mode 100644 index 0000000000..746bb1fdc8 --- /dev/null +++ b/students/734473301/coding2017jyz/readme.txt @@ -0,0 +1,4 @@ +因为内容不多,也就没有分包,全部放在了一起。 + +发送邮件的实现方法,最后是放在了host上,可以直接new一个host发送, +这个方法应该实现在哪个类,这个还需结合实际考虑。 \ No newline at end of file diff --git a/students/734473301/coding2017jyz/src/homework/jyz/coding2017/Configuration.java b/students/734473301/coding2017jyz/src/homework/jyz/coding2017/Configuration.java new file mode 100644 index 0000000000..01dbf8d408 --- /dev/null +++ b/students/734473301/coding2017jyz/src/homework/jyz/coding2017/Configuration.java @@ -0,0 +1,32 @@ +package homework.jyz.coding2017; +import java.util.HashMap; +import java.util.Map; + +/** + * 主机配置类 + */ +public class Configuration { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + + private Map configurations = new HashMap<>(); + + public Configuration() { + configurations.put(SMTP_SERVER, "smtp.163.com"); + configurations.put(ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(EMAIL_ADMIN, "admin@company.com"); + } + + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/734473301/coding2017jyz/src/homework/jyz/coding2017/Email.java b/students/734473301/coding2017jyz/src/homework/jyz/coding2017/Email.java new file mode 100644 index 0000000000..8e33d1e4d0 --- /dev/null +++ b/students/734473301/coding2017jyz/src/homework/jyz/coding2017/Email.java @@ -0,0 +1,54 @@ +package homework.jyz.coding2017; + +/** + * 邮件实体信息 + * Created by jyz on 2017/6/13. + */ +public class Email { + private String fromAddress; + private String toAddress; + private String subject; + private String message; + + public Email() { + } + + public Email(String fromAddress, String toAddress, String subject, String message) { + this.fromAddress = fromAddress; + this.toAddress = toAddress; + this.subject = subject; + this.message = message; + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/students/734473301/coding2017jyz/src/homework/jyz/coding2017/EmailHost.java b/students/734473301/coding2017jyz/src/homework/jyz/coding2017/EmailHost.java new file mode 100644 index 0000000000..dd12981982 --- /dev/null +++ b/students/734473301/coding2017jyz/src/homework/jyz/coding2017/EmailHost.java @@ -0,0 +1,58 @@ +package homework.jyz.coding2017; + +/** + * 邮件服务器主机类 + * Created by jyz on 2017/6/13. + */ +public class EmailHost { + private Configuration config; + private String host; + private String altHost; + private String hostAdmin; + + + /** + * 构建主机 + * @param config 主机配置 + */ + public EmailHost(Configuration config) { + this.config = config; + host = this.config.getProperty(Configuration.SMTP_SERVER); + altHost = this.config.getProperty(Configuration.ALT_SMTP_SERVER); + hostAdmin = this.config.getProperty(Configuration.EMAIL_ADMIN); + } + + public boolean send(Email email){ + + if(email != null){ + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(email.getFromAddress()).append("\n"); + buffer.append("To:").append(email.getToAddress()).append("\n"); + buffer.append("Subject:").append(email.getSubject()).append("\n"); + buffer.append("Content:").append(email.getMessage()).append("\n"); + if(send(host,buffer.toString())){ + return true; + } + System.out.println("启用备用主机发送.."); + if(send(altHost,buffer.toString())){ + return true; + } + System.out.println("发送失败"); + return false; + } + System.out.println("邮件为空,发送失败"); + return false; + } + + public boolean send(String host,String message){ + try { + System.out.println("使用主机"+host+"发送邮件"); + System.out.println(message); + return true; + } catch (Exception e) { + System.out.println("使用主机"+host+"发送邮件失败"); + e.printStackTrace(); + return false; + } + } +} diff --git a/students/734473301/coding2017jyz/src/homework/jyz/coding2017/MailConfig.java b/students/734473301/coding2017jyz/src/homework/jyz/coding2017/MailConfig.java new file mode 100644 index 0000000000..2d3a56aac6 --- /dev/null +++ b/students/734473301/coding2017jyz/src/homework/jyz/coding2017/MailConfig.java @@ -0,0 +1,68 @@ +package homework.jyz.coding2017; + + + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * 配置邮件信息类 + * Created by jyz on 2017/6/13. + */ +public class MailConfig { + private MailDao dao; + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + private String productID = ""; + private String productDesc = ""; + + public MailConfig(MailDao dao) { + this.dao = dao; + } + + public List getEmails() { + List mails = dao.getMails(productID); + List list = new ArrayList<>(); + for (HashMap map : mails) { + Email email = new Email(); + setMessage(map, email); + list.add(email); + } + return list; + } + + private void setMessage(HashMap userInfo, Email email) { + String name = (String) userInfo.get(NAME_KEY); + email.setSubject("您关注的产品降价了"); + String message = "尊敬的 " + name + ", 您关注的产品 " + productDesc + " 降价了,欢迎购买!"; + email.setMessage(message); + } + + + public void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + productID = data[0]; + productDesc = data[1]; + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + if(br != null){ + br.close(); + } + } + } +} diff --git a/students/734473301/coding2017jyz/src/homework/jyz/coding2017/MailDao.java b/students/734473301/coding2017jyz/src/homework/jyz/coding2017/MailDao.java new file mode 100644 index 0000000000..def5400761 --- /dev/null +++ b/students/734473301/coding2017jyz/src/homework/jyz/coding2017/MailDao.java @@ -0,0 +1,34 @@ +package homework.jyz.coding2017; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * 邮件Dao + * Created by jyz on 2017/6/13. + */ +public class MailDao { + + public List getMails(String productID){ + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + System.out.println("loadQuery set"); + return query(sendMailQuery); + } + + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/734473301/coding2017jyz/src/homework/jyz/coding2017/MailSend.java b/students/734473301/coding2017jyz/src/homework/jyz/coding2017/MailSend.java new file mode 100644 index 0000000000..d9658cb22f --- /dev/null +++ b/students/734473301/coding2017jyz/src/homework/jyz/coding2017/MailSend.java @@ -0,0 +1,41 @@ +package homework.jyz.coding2017; + +import java.util.List; + +/** + * 发送邮件的工作类 + * Created by jyz on 2017/6/13. + */ +public class MailSend { + + private EmailHost host; + + public MailSend(EmailHost host){ + this.host = host; + } + + public MailSend() { + } + + /** + * 默认主机发送 + * @param emails + */ + public void send(List emails){ + emails.forEach(email -> host.send(email)); + } + public void send(Email email){ + host.send(email); + } + /** + * 指定主机发送 + * @param host + * @param emails + */ + public void send(EmailHost host,List emails){ + for (Email email : emails) { + host.send(email); + } + } + +} diff --git a/students/734473301/coding2017jyz/src/homework/jyz/coding2017/WorkStart.java b/students/734473301/coding2017jyz/src/homework/jyz/coding2017/WorkStart.java new file mode 100644 index 0000000000..9759223a94 --- /dev/null +++ b/students/734473301/coding2017jyz/src/homework/jyz/coding2017/WorkStart.java @@ -0,0 +1,26 @@ +package homework.jyz.coding2017; + +import java.io.File; +import java.io.IOException; + +/** + * 主程序类 + * Created by jyz on 2017/6/13. + */ +public class WorkStart { + public static void main(String args[]) throws IOException { + // 发送邮件程序入口 + Configuration confg = new Configuration();// 加载配置 + MailSend ms = new MailSend(new EmailHost(confg));// 创建邮件工作类 + MailConfig mc = new MailConfig(new MailDao());// 组织待发送邮件 + mc.readFile(new File("product_promotion.txt"));// 获取产品信息 + ms.send(mc.getEmails());// 批量发送 + + Email email = new Email("from@qq.com","to@qq.com","coding2017","hello,world!"); + ms.send(email); // 单个发送 + + } + + + +} diff --git a/students/734473301/myjunit/calculator/Calculator.java b/students/734473301/myjunit/calculator/Calculator.java new file mode 100644 index 0000000000..e9835f3872 --- /dev/null +++ b/students/734473301/myjunit/calculator/Calculator.java @@ -0,0 +1,22 @@ +package com.jyz.myjunit.calculator; + +public class Calculator { + + private int result = 0; + public void add(int x){ + result += x; + } + public void subtract(int x){ + result -=x; + } + + public int getResult(){ + return this.result; + } + public static void main(String[] args){ + Calculator calculator = new Calculator(); + calculator.add(10); + calculator.subtract(5); + System.out.println(calculator.getResult()); + } +} diff --git a/students/734473301/myjunit/calculator/CalculatorTest.java b/students/734473301/myjunit/calculator/CalculatorTest.java new file mode 100644 index 0000000000..256a867371 --- /dev/null +++ b/students/734473301/myjunit/calculator/CalculatorTest.java @@ -0,0 +1,41 @@ +package com.jyz.myjunit.calculator; + + +import com.jyz.myjunit.junit.TestCase; +import com.jyz.myjunit.junit.TestResult; +import com.jyz.myjunit.junit.TestSuite; + +public class CalculatorTest extends TestCase { + public CalculatorTest(String name) { + super(name); + + } + Calculator calculator =null; + + public void setUp(){ + calculator = new Calculator(); + } + public void tearDown(){ + calculator = null; + } + + public void testAdd(){ + + calculator.add(10); + assertEquals(1,calculator.getResult()); + } + public void testSubtract(){ + calculator.add(10); + calculator.subtract(5); + //throw new RuntimeException("this is a test"); + assertEquals(5,calculator.getResult()); + } + + public static void main(String[] args) throws ClassNotFoundException { + + TestSuite ts = new TestSuite(Class.forName("com.jyz.myjunit.calculator.CalculatorTest")); + TestResult result = new TestResult(); + ts.run(result); + System.out.println(result); + } +} diff --git a/students/734473301/myjunit/junit/Assert.java b/students/734473301/myjunit/junit/Assert.java new file mode 100644 index 0000000000..5d2c11214f --- /dev/null +++ b/students/734473301/myjunit/junit/Assert.java @@ -0,0 +1,243 @@ +package com.jyz.myjunit.junit; + +/** + * A set of assert methods. + */ + +public class Assert { + /** + * Protect constructor since it is a static only class + */ + protected Assert() { + } + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError with the given message. + * @deprecated use assertTrue + */ + /*static public void assert(String message, boolean condition) { + if (!condition) + fail(message); + }*/ + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError. + * @deprecated use assertTrue + * + */ + /*static public void assert(boolean condition) { + assert(null, condition); + } +*/ + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError with the given message. + */ + static public void assertTrue(String message, boolean condition) { + if (!condition) + fail(message); + } + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError. + */ + static public void assertTrue(boolean condition) { + assertTrue(null, condition); + } + /** + * Fails a test with the given message. + */ + static public void fail(String message) { + throw new AssertionFailedError(message); + } + /** + * Fails a test with no message. + */ + static public void fail() { + fail(null); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(String message, Object expected, Object actual) { + if (expected == null && actual == null) + return; + if (expected != null && expected.equals(actual)) + return; + failNotEquals(message, expected, actual); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(Object expected, Object actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, double expected, double actual, double delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Double.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Double(expected), new Double(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) // Because comparison with NaN always returns false + failNotEquals(message, new Double(expected), new Double(actual)); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(double expected, double actual, double delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, float expected, float actual, float delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Float.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Float(expected), new Float(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) + failNotEquals(message, new Float(expected), new Float(actual)); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(float expected, float actual, float delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(String message, long expected, long actual) { + assertEquals(message, new Long(expected), new Long(actual)); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(long expected, long actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(String message, boolean expected, boolean actual) { + assertEquals(message, new Boolean(expected), new Boolean(actual)); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(boolean expected, boolean actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(String message, byte expected, byte actual) { + assertEquals(message, new Byte(expected), new Byte(actual)); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(byte expected, byte actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(String message, char expected, char actual) { + assertEquals(message, new Character(expected), new Character(actual)); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(char expected, char actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(String message, short expected, short actual) { + assertEquals(message, new Short(expected), new Short(actual)); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(short expected, short actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(String message, int expected, int actual) { + assertEquals(message, new Integer(expected), new Integer(actual)); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(int expected, int actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(Object object) { + assertNotNull(null, object); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(String message, Object object) { + assertTrue(message, object != null); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(Object object) { + assertNull(null, object); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(String message, Object object) { + assertTrue(message, object == null); + } + /** + * Asserts that two objects refer to the same object. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertSame(String message, Object expected, Object actual) { + if (expected == actual) + return; + failNotSame(message, expected, actual); + } + /** + * Asserts that two objects refer to the same object. If they are not + * the same an AssertionFailedError is thrown. + */ + static public void assertSame(Object expected, Object actual) { + assertSame(null, expected, actual); + } + + static private void failNotEquals(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected:<"+expected+"> but was:<"+actual+">"); + } + + static private void failNotSame(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected same"); + } +} \ No newline at end of file diff --git a/students/734473301/myjunit/junit/AssertionFailedError.java b/students/734473301/myjunit/junit/AssertionFailedError.java new file mode 100644 index 0000000000..7dd67f0beb --- /dev/null +++ b/students/734473301/myjunit/junit/AssertionFailedError.java @@ -0,0 +1,13 @@ +package com.jyz.myjunit.junit; + +/** + * Thrown when an assertion failed. + */ +public class AssertionFailedError extends Error { + + public AssertionFailedError () { + } + public AssertionFailedError (String message) { + super (message); + } +} \ No newline at end of file diff --git a/students/734473301/myjunit/junit/Test.java b/students/734473301/myjunit/junit/Test.java new file mode 100644 index 0000000000..ecf2f9ef7c --- /dev/null +++ b/students/734473301/myjunit/junit/Test.java @@ -0,0 +1,9 @@ +package com.jyz.myjunit.junit; + +/** + * Created by jyz on 2017/9/16. + */ +public interface Test { + void run(TestResult tr); + int countTestCases(); +} diff --git a/students/734473301/myjunit/junit/TestCase.java b/students/734473301/myjunit/junit/TestCase.java new file mode 100644 index 0000000000..9071ad9813 --- /dev/null +++ b/students/734473301/myjunit/junit/TestCase.java @@ -0,0 +1,75 @@ +package com.jyz.myjunit.junit; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +/** + * Created by jyz on 2017/9/16. + */ +public abstract class TestCase extends Assert implements Test { + private String name;// 该用例的方法名字 + + public TestCase(String name) { + this.name = name; + } + + @Override + public String toString() { + return "TestCase{" + + "methond ='" + name + '\'' + + '}'; + } + + public void doRun() throws Throwable{ + setUp(); + try{ + runTest(); + } + finally{ + tearDown(); + } + } + + @Override + public int countTestCases(){ + return 1; + } + + protected void setUp() { + + } + + protected void tearDown() { + + } + + @Override + public void run(TestResult tr) { + tr.run(this); + } + + protected void runTest() throws Throwable{ + Method runMethod= null; + try { + runMethod= getClass().getMethod(name, null); + } catch (NoSuchMethodException e) { + fail("Method \""+name+"\" not found"); + } + if (!Modifier.isPublic(runMethod.getModifiers())) { + fail("Method \""+name+"\" should be public"); + } + + try { + runMethod.invoke(this); + } + catch (InvocationTargetException e) { + e.fillInStackTrace(); + throw e.getTargetException(); + } + catch (IllegalAccessException e) { + e.fillInStackTrace(); + throw e; + } + } +} diff --git a/students/734473301/myjunit/junit/TestFailure.java b/students/734473301/myjunit/junit/TestFailure.java new file mode 100644 index 0000000000..f6da0b3086 --- /dev/null +++ b/students/734473301/myjunit/junit/TestFailure.java @@ -0,0 +1,30 @@ +package com.jyz.myjunit.junit; + +/** + * Created by jyz on 2017/9/16. + */ +public class TestFailure { + protected Test failedTest; + protected Throwable throwException; + + public TestFailure(Test failedTest, Throwable throwException) { + this.failedTest = failedTest; + this.throwException = throwException; + } + + public Test getFailedTest() { + return failedTest; + } + + public Throwable getThrowException() { + return throwException; + } + + @Override + public String toString() { + return "TestFailure{" + + "failedTest=" + failedTest + + ", throwException=" + throwException + + '}'; + } +} diff --git a/students/734473301/myjunit/junit/TestResult.java b/students/734473301/myjunit/junit/TestResult.java new file mode 100644 index 0000000000..02d72ec0ea --- /dev/null +++ b/students/734473301/myjunit/junit/TestResult.java @@ -0,0 +1,104 @@ +package com.jyz.myjunit.junit; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + + +/** + * 用来保存测试结果 + */ +public class TestResult { + protected List failures; + protected List errors; + + protected int testCount; + private boolean stop; + + public TestResult() { + failures= new ArrayList<>(); + errors= new ArrayList<>(); + + testCount= 0; + stop= false; + } + + public void addError(Test test, Throwable t) { + errors.add(new TestFailure(test, t)); + } + + public void addFailure(Test test, AssertionFailedError t) { + failures.add(new TestFailure(test, t)); + } + + public void startTest(Test test) { + int count= test.countTestCases(); + testCount+= count; + } + public void endTest(Test test) { + } + + /** + * Runs a TestCase. + */ + protected void run(final TestCase test) { + startTest(test); + try { + test.doRun(); + } + catch (AssertionFailedError e) { + addFailure(test, e); + } + catch (Throwable e) { + addError(test, e); + } + + endTest(test); + } + /** + * Gets the number of run tests. + */ + public int runCount() { + return testCount; + } + + + public boolean shouldStop() { + return stop; + } + + public void stop() { + stop= true; + } + + public int errorCount() { + return errors.size(); + } + + public Iterator errors() { + return errors.iterator(); + } + + public int failureCount() { + return failures.size(); + } + + public Iterator failures() { + return failures.iterator(); + } + /** + * Returns whether the entire test was successful or not. + */ + public boolean wasSuccessful() { + return this.failureCount() == 0 && this.errorCount() == 0; + } + + @Override + public String toString() { + return "TestResult{" + + "\n failures=" + failures + + ",\n errors=" + errors + + ",\n testCount=" + testCount + + ",\n success ="+wasSuccessful()+"\n}"; + } +} \ No newline at end of file diff --git a/students/734473301/myjunit/junit/TestSuite.java b/students/734473301/myjunit/junit/TestSuite.java new file mode 100644 index 0000000000..12e995b64f --- /dev/null +++ b/students/734473301/myjunit/junit/TestSuite.java @@ -0,0 +1,98 @@ +package com.jyz.myjunit.junit; + + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + + +/** + * 测试套件 + * 测试套件通过反射获取一个 测试用例类 的所有test开头的方法;每个方法对应一个实例 + * 遍历这些实例 + * Created by jyz on 2017/9/16. + */ +public class TestSuite extends Assert implements Test{ + private List tests= new ArrayList<>(10); + private String name; + + + /** + * 反射获取该类所有测试方法 + * @param theClass + */ + public TestSuite(final Class theClass) { + this.name= theClass.getName(); + Constructor constructor = null; + try { + constructor= theClass.getConstructor(String.class); + Method[] methods= theClass.getDeclaredMethods(); + for (Method method : methods) { + if(isPublicTestMethod(method)){ + System.out.println("添加测试方法:"+method.getName()); + addTest((Test) constructor.newInstance(method.getName())); + } + } + } catch (Exception e) { + addTest(warning("在获取测试方法时出现异常!")); + e.printStackTrace(); + } + if (tests.size() == 0){ + addTest(warning("没有发现可以使用的测试用例!")); + } + + } + + + private boolean isPublicTestMethod(Method m) { + return isTestMethod(m) && Modifier.isPublic(m.getModifiers()); + } + private boolean isTestMethod(Method m) { + String name= m.getName(); + Class[] parameters= m.getParameterTypes(); + Class returnType= m.getReturnType(); + return parameters.length == 0 && name.startsWith("test") && returnType.equals(Void.TYPE); + } + + public void addTest(Test test) { + tests.add(test); + } + + private Test warning(final String message) { + return new TestCase("warning") { + @Override + public void doRun() { + fail(message); + } + }; + } + + @Override + public void run(TestResult result) { + + for (Iterator e = tests(); e.hasNext(); ) { + if (result.shouldStop() ){ + break; + } + Test test= (Test)e.next(); + test.run(result); + // result.run(test); + } + + } + + public int countTestCases() { + int count= 0; + for (Iterator e= tests(); e.hasNext(); ) { + Test test= e.next(); + count= count + test.countTestCases(); + } + return count; + } + public Iterator tests() { + return tests.iterator(); + } +} diff --git a/students/734473301/payroll/PayrollService.java b/students/734473301/payroll/PayrollService.java new file mode 100644 index 0000000000..c333a1b40d --- /dev/null +++ b/students/734473301/payroll/PayrollService.java @@ -0,0 +1,68 @@ +package com.jyz.payroll; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import com.jyz.payroll.affiliation.NonAffiliation; +import com.jyz.payroll.classification.CommissionedClassification; +import com.jyz.payroll.classification.HourlyClassification; +import com.jyz.payroll.classification.SalariedClassification; +import com.jyz.payroll.domain.Employee; +import com.jyz.payroll.domain.HoldMethod; +import com.jyz.payroll.domain.Paycheck; +import com.jyz.payroll.domain.TimeCard; +import com.jyz.payroll.schedule.BiweeklySchedule; +import com.jyz.payroll.schedule.MonthlySchedule; +import com.jyz.payroll.schedule.WeeklySchedule; + +public class PayrollService { + private List allEmployees = new ArrayList<>(); + + public List getAllEmployees(){ + return allEmployees; + } + public void savePaycheck(Paycheck pc){ + System.out.println("保存此次支付记录:"+pc); + } + + public Employee addHourlyEmployee(String name, String address, double hourlyRate){ + + Employee e = new Employee(name, address); + HourlyClassification hourlyClassification = new HourlyClassification(hourlyRate); + + hourlyClassification.addTimeCard(new TimeCard(new Date(),8)); + + e.setClassification(hourlyClassification); + e.setSchedule(new WeeklySchedule()); + e.setPaymentMethod(new HoldMethod()); + e.setAffiliation(new NonAffiliation()); + allEmployees.add(e); + //保存员工到数据库.. 略 + return e; + } + + public Employee addSalariedEmployee(String name, String address, double salary){ + Employee e = new Employee(name, address); + e.setClassification(new SalariedClassification(salary)); + e.setSchedule(new MonthlySchedule()); + e.setPaymentMethod(new HoldMethod()); + e.setAffiliation(new NonAffiliation()); + //保存员工到数据库.. 略 + allEmployees.add(e); + return e; + } + + public Employee addCommissionedEmployee(String name, String address, double salary, double saleRate){ + Employee e = new Employee(name, address); + e.setClassification(new CommissionedClassification(salary, saleRate)); + e.setSchedule(new BiweeklySchedule()); + e.setPaymentMethod(new HoldMethod()); + e.setAffiliation(new NonAffiliation()); + //保存员工到数据库.. 略 + allEmployees.add(e); + return e; + } + + +} diff --git a/students/734473301/payroll/affiliation/NonAffiliation.java b/students/734473301/payroll/affiliation/NonAffiliation.java new file mode 100644 index 0000000000..1b42201113 --- /dev/null +++ b/students/734473301/payroll/affiliation/NonAffiliation.java @@ -0,0 +1,10 @@ +package com.jyz.payroll.affiliation; + +import com.jyz.payroll.domain.Affiliation; +import com.jyz.payroll.domain.Paycheck; + +public class NonAffiliation implements Affiliation{ + public double calculateDeductions(Paycheck pc){ + return 9.0; + } +} diff --git a/students/734473301/payroll/affiliation/UnionAffiliation.java b/students/734473301/payroll/affiliation/UnionAffiliation.java new file mode 100644 index 0000000000..5ab02ac21e --- /dev/null +++ b/students/734473301/payroll/affiliation/UnionAffiliation.java @@ -0,0 +1,14 @@ +package com.jyz.payroll.affiliation; + +import com.jyz.payroll.domain.Affiliation; +import com.jyz.payroll.domain.Paycheck; + +public class UnionAffiliation implements Affiliation { + + @Override + public double calculateDeductions(Paycheck pc) { + + return 0; + } + +} diff --git a/students/734473301/payroll/classification/CommissionedClassification.java b/students/734473301/payroll/classification/CommissionedClassification.java new file mode 100644 index 0000000000..7db6f16a4b --- /dev/null +++ b/students/734473301/payroll/classification/CommissionedClassification.java @@ -0,0 +1,39 @@ +package com.jyz.payroll.classification; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import com.jyz.payroll.domain.Paycheck; +import com.jyz.payroll.domain.PaymentClassification; +import com.jyz.payroll.domain.SalesReceipt; +import com.jyz.payroll.util.DateUtil; + +/** + * 销售人员计算薪水 + */ +public class CommissionedClassification implements PaymentClassification { + double salary; + double rate; + public CommissionedClassification(double salary , double rate){ + this.salary = salary; + this.rate = rate; + receipts = new HashMap<>(); + SalesReceipt sr = new SalesReceipt(new Date(),50000); + receipts.put(new Date(),sr); + } + Map receipts; + + @Override + public double calculatePay(Paycheck pc) { + double commission = 0.0; + for(SalesReceipt sr : receipts.values()){ + if(DateUtil.between(sr.getSaleDate(), pc.getPayPeriodStartDate(), + pc.getPayPeriodEndDate())){ + commission += sr.getAmount() * rate; + } + } + return salary + commission; + } + +} diff --git a/students/734473301/payroll/classification/HourlyClassification.java b/students/734473301/payroll/classification/HourlyClassification.java new file mode 100644 index 0000000000..ee563836c9 --- /dev/null +++ b/students/734473301/payroll/classification/HourlyClassification.java @@ -0,0 +1,48 @@ +package com.jyz.payroll.classification; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import com.jyz.payroll.domain.Paycheck; +import com.jyz.payroll.domain.PaymentClassification; +import com.jyz.payroll.domain.TimeCard; +import com.jyz.payroll.util.DateUtil; +/** + * 小时工的薪水计算 + */ + +public class HourlyClassification implements PaymentClassification { + private double rate; + private Map timeCards = new HashMap<>(); + + public HourlyClassification(double hourlyRate) { + this.rate = hourlyRate; + } + public void addTimeCard(TimeCard tc){ + timeCards.put(tc.getDate(), tc); + } + + @Override + public double calculatePay(Paycheck pc) { + double totalPay = 0; + for(TimeCard tc : timeCards.values()){ + if(DateUtil.between(tc.getDate(), pc.getPayPeriodStartDate(), + pc.getPayPeriodEndDate())){ + totalPay += calculatePayForTimeCard(tc); + } + } + return totalPay; + + } + private double calculatePayForTimeCard(TimeCard tc) { + int hours = tc.getHours(); + + if(hours > 8){ + return 8*rate + (hours-8) * rate * 1.5; + } else{ + return 8*rate; + } + } +} + diff --git a/students/734473301/payroll/classification/SalariedClassification.java b/students/734473301/payroll/classification/SalariedClassification.java new file mode 100644 index 0000000000..48db5e6b22 --- /dev/null +++ b/students/734473301/payroll/classification/SalariedClassification.java @@ -0,0 +1,19 @@ +package com.jyz.payroll.classification; + +import com.jyz.payroll.domain.Paycheck; +import com.jyz.payroll.domain.PaymentClassification; + +/** + * 月薪族 + */ +public class SalariedClassification implements PaymentClassification { + private double salary; + public SalariedClassification(double salary){ + this.salary = salary; + } + @Override + public double calculatePay(Paycheck pc) { + return salary; + } + +} diff --git a/students/734473301/payroll/domain/Affiliation.java b/students/734473301/payroll/domain/Affiliation.java new file mode 100644 index 0000000000..a1ea246762 --- /dev/null +++ b/students/734473301/payroll/domain/Affiliation.java @@ -0,0 +1,10 @@ +package com.jyz.payroll.domain; + +public interface Affiliation { + /** + * 计算扣除 + * @param pc + * @return + */ + double calculateDeductions(Paycheck pc); +} diff --git a/students/734473301/payroll/domain/Employee.java b/students/734473301/payroll/domain/Employee.java new file mode 100644 index 0000000000..7bbadd103d --- /dev/null +++ b/students/734473301/payroll/domain/Employee.java @@ -0,0 +1,58 @@ +package com.jyz.payroll.domain; + +import java.util.Date; +// 雇员类 +public class Employee { + private String id; + private String name; + private String address; + private Affiliation affiliation; + + + private PaymentClassification classification; // 计算薪水 + private PaymentSchedule schedule; // 支付周期 + + private PaymentMethod paymentMethod; // 该雇员的支付 方式 + // 支票邮寄到他们指定的邮政地址,也可以保存在财务那里随时支取,或者要求直接存入他们指定的银行账户 + + public Employee(String name, String address){ + this.name = name; + this.address = address; + } + public boolean isPayDay(Date d) { + return this.schedule.isPayDate(d); + } + + public Date getPayPeriodStartDate(Date d) { + return this.schedule.getPayPeriodStartDate(d); + } + + // 重复发薪校验 + public void payDay(Paycheck pc){ + double grossPay = classification.calculatePay(pc); + double deductions = affiliation.calculateDeductions(pc); + double netPay = grossPay - deductions; + pc.setGrossPay(grossPay); + pc.setDeductions(deductions); + pc.setNetPay(netPay); + System.out.println("员工:"+name); + paymentMethod.pay(pc); + } + + + + public void setClassification(PaymentClassification classification) { + this.classification = classification; + } + public void setSchedule(PaymentSchedule schedule) { + this.schedule = schedule; + } + public void setPaymentMethod(PaymentMethod paymentMethod) { + this.paymentMethod = paymentMethod; + } + + public void setAffiliation(Affiliation affiliation) { + this.affiliation = affiliation; + } +} + diff --git a/students/734473301/payroll/domain/HoldMethod.java b/students/734473301/payroll/domain/HoldMethod.java new file mode 100644 index 0000000000..9ca345cce2 --- /dev/null +++ b/students/734473301/payroll/domain/HoldMethod.java @@ -0,0 +1,11 @@ +package com.jyz.payroll.domain; + +public class HoldMethod implements PaymentMethod { + + @Override + public void pay(Paycheck pc) { + + System.out.println("支付记录:"+pc); + } + +} diff --git a/students/734473301/payroll/domain/Paycheck.java b/students/734473301/payroll/domain/Paycheck.java new file mode 100644 index 0000000000..61ab731817 --- /dev/null +++ b/students/734473301/payroll/domain/Paycheck.java @@ -0,0 +1,48 @@ +package com.jyz.payroll.domain; + +import java.util.Date; +import java.util.Map; + +public class Paycheck { + private Date payPeriodStart;// 上一次支付时间 + private Date payPeriodEnd;// 这一次支付时间 + private double grossPay; //总共薪水 + private double netPay; //实际支付 + private double deductions; //应该扣除的钱 + private Map itsFields; + + public Paycheck(Date payPeriodStart, Date payPeriodEnd){ + this.payPeriodStart = payPeriodStart; + this.payPeriodEnd = payPeriodEnd; + } + + public void setGrossPay(double grossPay) { + this.grossPay = grossPay; + + } + + public void setDeductions(double deductions) { + this.deductions = deductions; + } + public void setNetPay(double netPay){ + this.netPay = netPay; + } + + public Date getPayPeriodEndDate() { + + return this.payPeriodEnd; + } + public Date getPayPeriodStartDate() { + + return this.payPeriodStart; + } + + @Override + public String toString() { + return "{" + + "总薪水= " + grossPay + + ", 实际支付= " + netPay + + ", 扣除部分= " + deductions + + '}'; + } +} diff --git a/students/734473301/payroll/domain/PaydayTransaction.java b/students/734473301/payroll/domain/PaydayTransaction.java new file mode 100644 index 0000000000..0e574ebab9 --- /dev/null +++ b/students/734473301/payroll/domain/PaydayTransaction.java @@ -0,0 +1,44 @@ +package com.jyz.payroll.domain; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +import com.jyz.payroll.PayrollService; + + +public class PaydayTransaction { + private Date date; + private PayrollService payrollService; + + public void execute(){ + List employees = payrollService.getAllEmployees(); + for(Employee e : employees){ + if(e.isPayDay(date)){ + Paycheck pc = new Paycheck(e.getPayPeriodStartDate(date),date); + e.payDay(pc); + payrollService.savePaycheck(pc); + System.out.println(""); + } + } + } + + + public static void main(String args[]) throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH"); + PayrollService ps = new PayrollService(); + PaydayTransaction pt = new PaydayTransaction(); + pt.date = sdf.parse("2017-09-21 05"); + pt.payrollService = ps; + // 小时工 + ps.addHourlyEmployee("小时工","上海",200); + //销售人员 + ps.addCommissionedEmployee("销售","广州",500,0.2); + ps.addSalariedEmployee("月薪族","北京",10000); + pt.execute(); + + + } +} + diff --git a/students/734473301/payroll/domain/PaymentClassification.java b/students/734473301/payroll/domain/PaymentClassification.java new file mode 100644 index 0000000000..97ec105da9 --- /dev/null +++ b/students/734473301/payroll/domain/PaymentClassification.java @@ -0,0 +1,10 @@ +package com.jyz.payroll.domain; + +public interface PaymentClassification { + /** + * 计算薪水 + * @param pc + * @return + */ + double calculatePay(Paycheck pc); +} diff --git a/students/734473301/payroll/domain/PaymentMethod.java b/students/734473301/payroll/domain/PaymentMethod.java new file mode 100644 index 0000000000..97b932a8c9 --- /dev/null +++ b/students/734473301/payroll/domain/PaymentMethod.java @@ -0,0 +1,9 @@ +package com.jyz.payroll.domain; + +public interface PaymentMethod { + /** + * 支付方式 + * @param pc + */ + void pay(Paycheck pc); +} diff --git a/students/734473301/payroll/domain/PaymentSchedule.java b/students/734473301/payroll/domain/PaymentSchedule.java new file mode 100644 index 0000000000..85c561b7c5 --- /dev/null +++ b/students/734473301/payroll/domain/PaymentSchedule.java @@ -0,0 +1,19 @@ +package com.jyz.payroll.domain; + +import java.util.Date; + +public interface PaymentSchedule { + /** + * 今天是不是发薪水的日子 + * @param date + * @return + */ + boolean isPayDate(Date date); + + /** + * 上一次发薪水的日子 + * @param payPeriodEndDate + * @return + */ + Date getPayPeriodStartDate(Date payPeriodEndDate); +} diff --git a/students/734473301/payroll/domain/SalesReceipt.java b/students/734473301/payroll/domain/SalesReceipt.java new file mode 100644 index 0000000000..7d72733879 --- /dev/null +++ b/students/734473301/payroll/domain/SalesReceipt.java @@ -0,0 +1,23 @@ +package com.jyz.payroll.domain; + +import java.util.Date; + +/** + * 销售凭条 + */ +public class SalesReceipt { + private Date saleDate; + private double amount; + + public SalesReceipt(Date saleDate, double amount) { + this.saleDate = saleDate; + this.amount = amount; + } + + public Date getSaleDate() { + return saleDate; + } + public double getAmount() { + return amount; + } +} diff --git a/students/734473301/payroll/domain/TimeCard.java b/students/734473301/payroll/domain/TimeCard.java new file mode 100644 index 0000000000..1cf5d56173 --- /dev/null +++ b/students/734473301/payroll/domain/TimeCard.java @@ -0,0 +1,23 @@ +package com.jyz.payroll.domain; + +import java.util.Date; + +/** + * 时间卡,小时工用 + */ +public class TimeCard { + private Date date; + private int hours; + + public TimeCard(Date date, int hours) { + this.date = date; + this.hours = hours; + } + + public Date getDate() { + return date; + } + public int getHours() { + return hours; + } +} diff --git a/students/734473301/payroll/schedule/BiweeklySchedule.java b/students/734473301/payroll/schedule/BiweeklySchedule.java new file mode 100644 index 0000000000..32db8ba2ea --- /dev/null +++ b/students/734473301/payroll/schedule/BiweeklySchedule.java @@ -0,0 +1,42 @@ +package com.jyz.payroll.schedule; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import com.jyz.payroll.domain.PaymentSchedule; +import com.jyz.payroll.util.DateUtil; + +/** + * 双周支付一次薪水 + */ +public class BiweeklySchedule implements PaymentSchedule { + Date firstPayableFriday = DateUtil.parseDate("2017-09-07"); + + @Override + public boolean isPayDate(Date date) { + + long interval = DateUtil.getDaysBetween(firstPayableFriday, date); + System.out.println("距离上次支付多少天:" + interval); + return interval % 14 == 0; + } + + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.add(payPeriodEndDate, -13); + + } + + public static void main(String [] args) throws Exception{ + BiweeklySchedule schedule = new BiweeklySchedule(); + + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); + Date d = sdf.parse("2017-06-30"); + + System.out.println(schedule.isPayDate(d)); + + System.out.println(DateUtil.isFriday(d)); + + System.out.println(schedule.getPayPeriodStartDate(d)); + } + +} diff --git a/students/734473301/payroll/schedule/MonthlySchedule.java b/students/734473301/payroll/schedule/MonthlySchedule.java new file mode 100644 index 0000000000..1839cd7518 --- /dev/null +++ b/students/734473301/payroll/schedule/MonthlySchedule.java @@ -0,0 +1,25 @@ +package com.jyz.payroll.schedule; + +import java.util.Date; + +import com.jyz.payroll.domain.PaymentSchedule; +import com.jyz.payroll.util.DateUtil; + +/** + * 月薪族支付 + */ +public class MonthlySchedule implements PaymentSchedule { + + @Override + public boolean isPayDate(Date date) { + //return DateUtil.isLastDayOfMonth(date); + System.out.println("月薪族测试,总是每月的最后一天"); + return true; + } + + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.getFirstDay(payPeriodEndDate); + } + +} diff --git a/students/734473301/payroll/schedule/WeeklySchedule.java b/students/734473301/payroll/schedule/WeeklySchedule.java new file mode 100644 index 0000000000..33264f81dc --- /dev/null +++ b/students/734473301/payroll/schedule/WeeklySchedule.java @@ -0,0 +1,22 @@ +package com.jyz.payroll.schedule; + +import java.util.Date; + +import com.jyz.payroll.domain.PaymentSchedule; +import com.jyz.payroll.util.DateUtil; + +/** + * 每周五支付 + */ +public class WeeklySchedule implements PaymentSchedule { + + @Override + public boolean isPayDate(Date date) { + return DateUtil.isFriday(date); + } + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.add(payPeriodEndDate, -6); + } + +} diff --git a/students/734473301/payroll/util/DateUtil.java b/students/734473301/payroll/util/DateUtil.java new file mode 100644 index 0000000000..8ac5925122 --- /dev/null +++ b/students/734473301/payroll/util/DateUtil.java @@ -0,0 +1,58 @@ +package com.jyz.payroll.util; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +public class DateUtil { + public static long getDaysBetween(Date d1, Date d2){ + + return (d2.getTime() - d1.getTime())/(24*60*60*1000); + } + + public static Date parseDate(String txtDate){ + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); + try { + return sdf.parse(txtDate); + } catch (ParseException e) { + e.printStackTrace(); + return null; + } + } + public static boolean isFriday(Date d){ + Calendar calendar = Calendar.getInstance(); + calendar.setTime(d); + System.out.println("今天周几:"+calendar.get(Calendar.DAY_OF_WEEK)); + return calendar.get(Calendar.DAY_OF_WEEK) == 5; + } + + public static Date add(Date d, int days){ + Calendar calendar = Calendar.getInstance(); + calendar.setTime(d); + calendar.add(Calendar.DATE, days); + return calendar.getTime(); + } + + public static boolean isLastDayOfMonth(Date d){ + Calendar calendar=Calendar.getInstance(); + calendar.setTime(d); + return calendar.get(Calendar.DATE)==calendar.getActualMaximum(Calendar.DAY_OF_MONTH); + } + public static Date getFirstDay(Date d){ + Calendar calendar=Calendar.getInstance(); + calendar.setTime(d); + int day = calendar.get(Calendar.DATE); + calendar.add(Calendar.DATE, -(day-1)); + return calendar.getTime(); + } + public static void main(String [] args) throws Exception{ + System.out.println(DateUtil.isLastDayOfMonth(DateUtil.parseDate("2017-6-29"))); + + System.out.println(DateUtil.getFirstDay(DateUtil.parseDate("2017-6-30"))); + } + + public static boolean between(Date d, Date date1, Date date2){ + return d.after(date1) && d.before(date2); + } +} diff --git a/students/740707954/pom.xml b/students/740707954/pom.xml new file mode 100644 index 0000000000..577a0f582d --- /dev/null +++ b/students/740707954/pom.xml @@ -0,0 +1,25 @@ + + 4.0.0 + + 740707954 + 740707954 + 1.0-SNAPSHOT + jar + + 740707954 + http://maven.apache.org + + + UTF-8 + + + + + junit + junit + 4.10 + test + + + diff --git a/students/740707954/readMe b/students/740707954/readMe deleted file mode 100644 index a930ed0c81..0000000000 --- a/students/740707954/readMe +++ /dev/null @@ -1 +0,0 @@ -TEST1 \ No newline at end of file diff --git a/students/740707954/src/main/java/dp/ChainOfResponsibility/EmailLogger.java b/students/740707954/src/main/java/dp/ChainOfResponsibility/EmailLogger.java new file mode 100644 index 0000000000..b6b5568063 --- /dev/null +++ b/students/740707954/src/main/java/dp/ChainOfResponsibility/EmailLogger.java @@ -0,0 +1,43 @@ +package dp.ChainOfResponsibility; + +/** + * Created by lx on 2017/8/12. + */ +public class EmailLogger implements Logger { + + private Logger nextLogger; + private int level; + + public EmailLogger(int level) { + this.level = level; + } + + /** + * 设置下一处理 + * @param logger + * @return + */ + @Override + public Logger setNext(Logger logger) { + nextLogger = logger; + return this; + } + + /** + * 输出日志信息 + * @param content + * @param level + */ + @Override + public void message(String content, int level) { + System.out.println("EmailLogger 处理...."); + + if (this.level >= level) { + System.out.println(content); + } + + if (null != nextLogger) { + nextLogger.message(content, level); + } + } +} diff --git a/students/740707954/src/main/java/dp/ChainOfResponsibility/FileLogger.java b/students/740707954/src/main/java/dp/ChainOfResponsibility/FileLogger.java new file mode 100644 index 0000000000..1ea9963cc0 --- /dev/null +++ b/students/740707954/src/main/java/dp/ChainOfResponsibility/FileLogger.java @@ -0,0 +1,42 @@ +package dp.ChainOfResponsibility; + +/** + * Created by lx on 2017/8/12. + */ +public class FileLogger implements Logger { + private Logger nextLogger; + private int level; + + public FileLogger(int level) { + this.level = level; + } + + /** + * 设置下一处理 + * @param logger + * @return + */ + @Override + public Logger setNext(Logger logger) { + nextLogger = logger; + return this; + } + + /** + * 输出日志信息 + * @param content + * @param level + */ + @Override + public void message(String content, int level) { + System.out.println("FileLogger 处理...."); + + if (this.level >= level) { + System.out.println(content); + } + + if (null != nextLogger) { + nextLogger.message(content, level); + } + } +} diff --git a/students/740707954/src/main/java/dp/ChainOfResponsibility/Logger.java b/students/740707954/src/main/java/dp/ChainOfResponsibility/Logger.java new file mode 100644 index 0000000000..23a3d39b31 --- /dev/null +++ b/students/740707954/src/main/java/dp/ChainOfResponsibility/Logger.java @@ -0,0 +1,15 @@ +package dp.ChainOfResponsibility; + +/** + * Created by lx on 2017/8/12. + */ +public interface Logger { + + public static final int DEBUG = 3; + public static final int NOTICE = 2; + public static final int ERR = 1; + + Logger setNext(Logger logger); + + void message(String content, int level); +} diff --git a/students/740707954/src/main/java/dp/ChainOfResponsibility/StdoutLogger.java b/students/740707954/src/main/java/dp/ChainOfResponsibility/StdoutLogger.java new file mode 100644 index 0000000000..b6c28e9d42 --- /dev/null +++ b/students/740707954/src/main/java/dp/ChainOfResponsibility/StdoutLogger.java @@ -0,0 +1,42 @@ +package dp.ChainOfResponsibility; + +/** + * Created by lx on 2017/8/12. + */ +public class StdoutLogger implements Logger { + private Logger nextLogger; + private int level; + + public StdoutLogger(int level) { + this.level = level; + } + + /** + * 设置下一处理 + * @param logger + * @return + */ + @Override + public Logger setNext(Logger logger) { + nextLogger = logger; + return this; + } + + /** + * 输出日志信息 + * @param content + * @param level + */ + @Override + public void message(String content, int level) { + System.out.println("StdoutLogger 处理...."); + + if (this.level >= level) { + System.out.println(content); + } + + if (null != nextLogger) { + nextLogger.message(content, level); + } + } +} diff --git a/students/740707954/src/main/java/dp/bridge/v1/Circle.java b/students/740707954/src/main/java/dp/bridge/v1/Circle.java new file mode 100644 index 0000000000..5102a18211 --- /dev/null +++ b/students/740707954/src/main/java/dp/bridge/v1/Circle.java @@ -0,0 +1,17 @@ +package dp.bridge.v1; + +/** + * Created by lx on 2017/7/29. + */ +public class Circle extends Shape { + public Circle(Drawing drawing) { + setDrawing(drawing); + } + + @Override + public void shape() { + getDrawing().drawCircle(); + } + + +} diff --git a/students/740707954/src/main/java/dp/bridge/v1/Drawing.java b/students/740707954/src/main/java/dp/bridge/v1/Drawing.java new file mode 100644 index 0000000000..5011838201 --- /dev/null +++ b/students/740707954/src/main/java/dp/bridge/v1/Drawing.java @@ -0,0 +1,10 @@ +package dp.bridge.v1; + +/** + * Created by lx on 2017/7/29. + */ +public interface Drawing { + void drawLine(); + + void drawCircle(); +} diff --git a/students/740707954/src/main/java/dp/bridge/v1/DrawingGL1.java b/students/740707954/src/main/java/dp/bridge/v1/DrawingGL1.java new file mode 100644 index 0000000000..5915eb884c --- /dev/null +++ b/students/740707954/src/main/java/dp/bridge/v1/DrawingGL1.java @@ -0,0 +1,17 @@ +package dp.bridge.v1; + +/** + * 图形库1 + * Created by lx on 2017/7/29. + */ +public class DrawingGL1 implements Drawing{ + @Override + public void drawLine() { + System.out.println("图形库1画线"); + } + + @Override + public void drawCircle() { + System.out.println("图形库1画圆"); + } +} diff --git a/students/740707954/src/main/java/dp/bridge/v1/DrawingGL2.java b/students/740707954/src/main/java/dp/bridge/v1/DrawingGL2.java new file mode 100644 index 0000000000..e2c215a233 --- /dev/null +++ b/students/740707954/src/main/java/dp/bridge/v1/DrawingGL2.java @@ -0,0 +1,17 @@ +package dp.bridge.v1; + +/** + * 图形库2 + * Created by lx on 2017/7/29. + */ +public class DrawingGL2 implements Drawing { + @Override + public void drawLine() { + System.out.println("图形库2画线"); + } + + @Override + public void drawCircle() { + System.out.println("图形库2画圆"); + } +} diff --git a/students/740707954/src/main/java/dp/bridge/v1/Retangle.java b/students/740707954/src/main/java/dp/bridge/v1/Retangle.java new file mode 100644 index 0000000000..1f4c907686 --- /dev/null +++ b/students/740707954/src/main/java/dp/bridge/v1/Retangle.java @@ -0,0 +1,16 @@ +package dp.bridge.v1; + +/** + * Created by lx on 2017/7/29. + */ +public class Retangle extends Shape { + public Retangle(Drawing drawing) { + setDrawing(drawing); + } + + @Override + public void shape() { + getDrawing().drawLine(); + } + +} diff --git a/students/740707954/src/main/java/dp/bridge/v1/Shape.java b/students/740707954/src/main/java/dp/bridge/v1/Shape.java new file mode 100644 index 0000000000..890474ce06 --- /dev/null +++ b/students/740707954/src/main/java/dp/bridge/v1/Shape.java @@ -0,0 +1,18 @@ +package dp.bridge.v1; + +/** + * Created by lx on 2017/7/29. + */ +public abstract class Shape { + private Drawing drawing; + + abstract void shape(); + + public void setDrawing(Drawing drawing) { + this.drawing = drawing; + } + + public Drawing getDrawing() { + return drawing; + } +} diff --git a/students/740707954/src/main/java/dp/bridge/v2/Cicle.java b/students/740707954/src/main/java/dp/bridge/v2/Cicle.java new file mode 100644 index 0000000000..e738ed46d6 --- /dev/null +++ b/students/740707954/src/main/java/dp/bridge/v2/Cicle.java @@ -0,0 +1,26 @@ +package dp.bridge.v2; + +/** + * Created by Administrator on 2017/8/10 0010. + */ +public class Cicle implements Shape { + + private Drawing drawing; + private int x1, x2, r; + + public Cicle(int x1, int x2, int r) { + this.x1 = x1; + this.x2 = x2; + this.r = r; + } + + @Override + public void setDrawing(Drawing d) { + this.drawing = d; + } + + @Override + public void draw() { + drawing.drawCircle(); + } +} diff --git a/students/740707954/src/main/java/dp/bridge/v2/Drawing.java b/students/740707954/src/main/java/dp/bridge/v2/Drawing.java new file mode 100644 index 0000000000..89d1074b14 --- /dev/null +++ b/students/740707954/src/main/java/dp/bridge/v2/Drawing.java @@ -0,0 +1,10 @@ +package dp.bridge.v2; + +/** + * Created by lx on 2017/7/29. + */ +public interface Drawing { + void drawLine(); + + void drawCircle(); +} diff --git a/students/740707954/src/main/java/dp/bridge/v2/DrawingGL1.java b/students/740707954/src/main/java/dp/bridge/v2/DrawingGL1.java new file mode 100644 index 0000000000..a4d3c0bf8b --- /dev/null +++ b/students/740707954/src/main/java/dp/bridge/v2/DrawingGL1.java @@ -0,0 +1,17 @@ +package dp.bridge.v2; + +/** + * 图形库1 + * Created by lx on 2017/7/29. + */ +public class DrawingGL1 implements Drawing { + @Override + public void drawLine() { + System.out.println("图形库1画线"); + } + + @Override + public void drawCircle() { + System.out.println("图形库1画圆"); + } +} diff --git a/students/740707954/src/main/java/dp/bridge/v2/DrawingGL2.java b/students/740707954/src/main/java/dp/bridge/v2/DrawingGL2.java new file mode 100644 index 0000000000..368fe60bef --- /dev/null +++ b/students/740707954/src/main/java/dp/bridge/v2/DrawingGL2.java @@ -0,0 +1,17 @@ +package dp.bridge.v2; + +/** + * 图形库2 + * Created by lx on 2017/7/29. + */ +public class DrawingGL2 implements Drawing { + @Override + public void drawLine() { + System.out.println("图形库2画线"); + } + + @Override + public void drawCircle() { + System.out.println("图形库2画圆"); + } +} diff --git a/students/740707954/src/main/java/dp/bridge/v2/Rectangle.java b/students/740707954/src/main/java/dp/bridge/v2/Rectangle.java new file mode 100644 index 0000000000..32ce8f6f05 --- /dev/null +++ b/students/740707954/src/main/java/dp/bridge/v2/Rectangle.java @@ -0,0 +1,27 @@ +package dp.bridge.v2; + +/** + * Created by Administrator on 2017/8/10 0010. + */ +public class Rectangle implements Shape { + + private Drawing drawing; + private int x1, y1, x2, y2; + + public Rectangle(int x1, int y1, int x2, int y2) { + this.x1 = x1; + this.x2 = x2; + this.y1 = y1; + this.y2 = y2; + } + + @Override + public void setDrawing(Drawing d) { + this.drawing = d; + } + + @Override + public void draw() { + drawing.drawLine(); + } +} diff --git a/students/740707954/src/main/java/dp/bridge/v2/Shape.java b/students/740707954/src/main/java/dp/bridge/v2/Shape.java new file mode 100644 index 0000000000..8dd46ef2d7 --- /dev/null +++ b/students/740707954/src/main/java/dp/bridge/v2/Shape.java @@ -0,0 +1,10 @@ +package dp.bridge.v2; + +/** + * Created by Administrator on 2017/8/10 0010. + */ +public interface Shape { + void setDrawing(Drawing d); + + void draw(); +} diff --git a/students/740707954/src/main/java/dp/builder/Attribute.java b/students/740707954/src/main/java/dp/builder/Attribute.java new file mode 100644 index 0000000000..a44481c71a --- /dev/null +++ b/students/740707954/src/main/java/dp/builder/Attribute.java @@ -0,0 +1,25 @@ +package dp.builder; + +/** + * Created by lx on 2017/7/22. + */ +public class Attribute { + private String name; + private String value; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/students/740707954/src/main/java/dp/builder/TagBuilder.java b/students/740707954/src/main/java/dp/builder/TagBuilder.java new file mode 100644 index 0000000000..74615b5797 --- /dev/null +++ b/students/740707954/src/main/java/dp/builder/TagBuilder.java @@ -0,0 +1,68 @@ +package dp.builder; + +import java.util.List; + +/** + * 标签构造 + * Created by lx on 2017/7/22. + */ +public class TagBuilder { + private TagNode root;// 根节点 + private TagNode currentNode;// 当前节点 + private TagNode prevNode;// 上一节点 + + public TagBuilder(String order) { + root = new TagNode(order); + currentNode = root; + } + + /** + * 添加子标签 + * @param nodeName 节点名称 + * @return TagBuilder + */ + public TagBuilder addChild(String nodeName) { + TagNode node = new TagNode(nodeName); + List children = currentNode.getChildren(); + children.add(node); + prevNode = currentNode; + currentNode = node; + return this; + } + + /** + * 添加当前标签属性 + * @param key + * @param value + * @return TagBuilder + */ + public TagBuilder setAttribute(String key, String value) { + currentNode.setAttribute(key, value); + return this; + } + + /** + * 添加兄弟标签 + * @param nodeName 节点名称 + * @return TagBuilder + */ + public TagBuilder addSibling(String nodeName) { + TagNode node = new TagNode(nodeName); + prevNode.getChildren().add(node); + currentNode = node; + return this; + } + + /** + * 设置文本值 + * @param value + * @return 节点名称 + */ + public TagBuilder setText(String value) { + return null; + } + + public String toXML() { + return root.toXML(); + } +} diff --git a/students/740707954/src/main/java/dp/builder/TagNode.java b/students/740707954/src/main/java/dp/builder/TagNode.java new file mode 100644 index 0000000000..bf8caeed0f --- /dev/null +++ b/students/740707954/src/main/java/dp/builder/TagNode.java @@ -0,0 +1,130 @@ +package dp.builder; + +import java.util.ArrayList; +import java.util.List; + +/** + * 标签 + * Created by lx on 2017/7/22. + */ +public class TagNode { + private String tagName; + private String tagValue; + private List children = new ArrayList<>(); + private List attributes = new ArrayList<>(); + + public TagNode(String tagName) { + this.tagName = tagName; + } + + /** + * 添加子标签 + * @param node + */ + public void add(TagNode node) { + children.add(node); + } + + /** + * 设置属性 + * @param key + * @param value + */ + public void setAttribute(String key, String value) { + Attribute attr = new Attribute(); + attr.setName(key); + attr.setValue(value); + attributes.add(attr); + } + + /** + * 查找当前标签属性 + * @param name + * @return + */ + private Attribute findAttribute(String name) { + for (Attribute attr : attributes) { + if (attr.getName().equals(name)) { + return attr; + } + } + return null; + } + + /** + * 转成xml字符串 + * @return + */ + public String toXML() { + return toXML(this); + } + + /** + * 将标签转成xml + * @param node + * @return + */ + private String toXML(TagNode node) { + StringBuilder buffer = new StringBuilder(); + buffer.append("<").append(node.tagName); + if (node.attributes.size() > 0) { + for (Attribute attr : node.attributes) { + buffer.append(" ").append(toXML(attr)); + } + } + + if (node.children.size() == 0) { + buffer.append("/>"); + return buffer.toString(); + } + + buffer.append(">"); + for (TagNode childrenNode : node.children) { + buffer.append(toXML(childrenNode)); + } + + buffer.append(""); + return buffer.toString(); + } + + /** + * 将属性转成xml + * @param attr + * @return + */ + private String toXML(Attribute attr) { + return attr.getName() + "=\"" + attr.getValue() + "\""; + } + + public String getTagName() { + return tagName; + } + + public void setTagName(String tagName) { + this.tagName = tagName; + } + + public String getTagValue() { + return tagValue; + } + + public void setTagValue(String tagValue) { + this.tagValue = tagValue; + } + + public List getChildren() { + return children; + } + + public void setChildren(List children) { + this.children = children; + } + + public List getAttributes() { + return attributes; + } + + public void setAttributes(List attributes) { + this.attributes = attributes; + } +} diff --git a/students/740707954/src/main/java/dp/command/Command.java b/students/740707954/src/main/java/dp/command/Command.java new file mode 100644 index 0000000000..70a987aa3d --- /dev/null +++ b/students/740707954/src/main/java/dp/command/Command.java @@ -0,0 +1,8 @@ +package dp.command; + +/** + * Created by lx on 2017/8/12. + */ +public interface Command { + void excute(); +} diff --git a/students/740707954/src/main/java/dp/command/Cook.java b/students/740707954/src/main/java/dp/command/Cook.java new file mode 100644 index 0000000000..7125986f8c --- /dev/null +++ b/students/740707954/src/main/java/dp/command/Cook.java @@ -0,0 +1,22 @@ +package dp.command; + +/** + * 厨师 + * Created by lx on 2017/8/12. + */ +public class Cook { + + /** + * 做牛排 + */ + void cookSteak() { + System.out.println("Steak is ok"); + } + + /** + * 做猪排 + */ + void cookPork() { + System.out.println("Pork is ok"); + } +} diff --git a/students/740707954/src/main/java/dp/command/OrderPorkCommand.java b/students/740707954/src/main/java/dp/command/OrderPorkCommand.java new file mode 100644 index 0000000000..8f7f3713e7 --- /dev/null +++ b/students/740707954/src/main/java/dp/command/OrderPorkCommand.java @@ -0,0 +1,18 @@ +package dp.command; + +/** + * Created by lx on 2017/8/12. + */ +public class OrderPorkCommand implements Command { + + private Cook cook; + + public OrderPorkCommand(Cook cook) { + this.cook = cook; + } + + @Override + public void excute() { + cook.cookPork(); + } +} diff --git a/students/740707954/src/main/java/dp/command/OrderSteakCommand.java b/students/740707954/src/main/java/dp/command/OrderSteakCommand.java new file mode 100644 index 0000000000..9481545b24 --- /dev/null +++ b/students/740707954/src/main/java/dp/command/OrderSteakCommand.java @@ -0,0 +1,18 @@ +package dp.command; + +/** + * Created by lx on 2017/8/12. + */ +public class OrderSteakCommand implements Command { + + private Cook cook; + + public OrderSteakCommand(Cook cook) { + this.cook = cook; + } + + @Override + public void excute() { + cook.cookSteak(); + } +} diff --git a/students/740707954/src/main/java/dp/command/Waiter.java b/students/740707954/src/main/java/dp/command/Waiter.java new file mode 100644 index 0000000000..66690c157f --- /dev/null +++ b/students/740707954/src/main/java/dp/command/Waiter.java @@ -0,0 +1,28 @@ +package dp.command; + +import java.util.ArrayList; +import java.util.List; + +/** + * 店小二 + * Created by lx on 2017/8/12. + */ +public class Waiter { + + private List commands = new ArrayList<>(); + + /** + * 发菜单 + */ + public void sendOrders() { + commands.forEach((Command c) -> c.excute()); + } + + /** + * 添加订单 + * @param command1 + */ + public void addOrder(Command command1) { + commands.add(command1); + } +} diff --git a/students/740707954/src/main/java/dp/composite/Line.java b/students/740707954/src/main/java/dp/composite/Line.java new file mode 100644 index 0000000000..bc3e9a6c0c --- /dev/null +++ b/students/740707954/src/main/java/dp/composite/Line.java @@ -0,0 +1,12 @@ +package dp.composite; + +/** + * 线 + * Created by lx on 2017/7/29. + */ +public class Line implements Shape { + @Override + public void draw() { + System.out.println("画线"); + } +} diff --git a/students/740707954/src/main/java/dp/composite/Picture.java b/students/740707954/src/main/java/dp/composite/Picture.java new file mode 100644 index 0000000000..4809e7bf6b --- /dev/null +++ b/students/740707954/src/main/java/dp/composite/Picture.java @@ -0,0 +1,42 @@ +package dp.composite; + +import java.util.ArrayList; +import java.util.List; + +/** + * 图片 + * Created by lx on 2017/7/29. + */ +public class Picture implements Shape{ + + private List shapes = new ArrayList<>(); + + @Override + public void draw() { + shapes.forEach((shape) -> shape.draw()); + } + + /** + * 添加图形 + * @param shape + */ + public void addShape(Shape shape) { + shapes.add(shape); + } + + /** + * 获取图形 + * @param i + */ + public void getShape(int i) { + shapes.get(i); + } + + /** + * 删除图形 + * @param i + */ + public void deleteShape(int i) { + shapes.remove(i); + } +} diff --git a/students/740707954/src/main/java/dp/composite/Rectangle.java b/students/740707954/src/main/java/dp/composite/Rectangle.java new file mode 100644 index 0000000000..a2b83477c4 --- /dev/null +++ b/students/740707954/src/main/java/dp/composite/Rectangle.java @@ -0,0 +1,12 @@ +package dp.composite; + +/** + * 矩形 + * Created by lx on 2017/7/29. + */ +public class Rectangle implements Shape{ + @Override + public void draw() { + System.out.println("画矩形"); + } +} diff --git a/students/740707954/src/main/java/dp/composite/Shape.java b/students/740707954/src/main/java/dp/composite/Shape.java new file mode 100644 index 0000000000..c7821b1a95 --- /dev/null +++ b/students/740707954/src/main/java/dp/composite/Shape.java @@ -0,0 +1,8 @@ +package dp.composite; + +/** + * Created by lx on 2017/7/29. + */ +public interface Shape { + void draw(); +} diff --git a/students/740707954/src/main/java/dp/composite/Square.java b/students/740707954/src/main/java/dp/composite/Square.java new file mode 100644 index 0000000000..3fd2236441 --- /dev/null +++ b/students/740707954/src/main/java/dp/composite/Square.java @@ -0,0 +1,12 @@ +package dp.composite; + +/** + * 正方形 + * Created by lx on 2017/7/29. + */ +public class Square implements Shape{ + @Override + public void draw() { + System.out.println("画正方形"); + } +} diff --git a/students/740707954/src/main/java/dp/composite/Text.java b/students/740707954/src/main/java/dp/composite/Text.java new file mode 100644 index 0000000000..2a07f699fd --- /dev/null +++ b/students/740707954/src/main/java/dp/composite/Text.java @@ -0,0 +1,12 @@ +package dp.composite; + +/** + * 文本 + * Created by lx on 2017/7/29. + */ +public class Text implements Shape{ + @Override + public void draw() { + System.out.println("画文本"); + } +} diff --git a/students/740707954/src/main/java/dp/decorator/Email.java b/students/740707954/src/main/java/dp/decorator/Email.java new file mode 100644 index 0000000000..520475c0a3 --- /dev/null +++ b/students/740707954/src/main/java/dp/decorator/Email.java @@ -0,0 +1,8 @@ +package dp.decorator; + +/** + * Created by lx on 2017/7/29. + */ +public interface Email { + String getContent(); +} diff --git a/students/740707954/src/main/java/dp/decorator/EmailImpl.java b/students/740707954/src/main/java/dp/decorator/EmailImpl.java new file mode 100644 index 0000000000..58ef0b4d82 --- /dev/null +++ b/students/740707954/src/main/java/dp/decorator/EmailImpl.java @@ -0,0 +1,17 @@ +package dp.decorator; + +/** + * Created by lx on 2017/7/29. + */ +public class EmailImpl implements Email { + private String content; + + public EmailImpl(String content) { + this.content = content; + } + + @Override + public String getContent() { + return content; + } +} diff --git a/students/740707954/src/main/java/dp/decorator/EncryptionEmailImpl.java b/students/740707954/src/main/java/dp/decorator/EncryptionEmailImpl.java new file mode 100644 index 0000000000..f3adfce50a --- /dev/null +++ b/students/740707954/src/main/java/dp/decorator/EncryptionEmailImpl.java @@ -0,0 +1,22 @@ +package dp.decorator; + +/** + * 加密邮件 + * Created by lx on 2017/7/29. + */ +public class EncryptionEmailImpl extends FilterEmail{ + + public EncryptionEmailImpl(Email email) { + super(email); + } + + @Override + public String getContent() { + return encryptionEmail(super.getContent()); + } + + public String encryptionEmail(String content) { + System.out.println("加密邮件。。"); + return "加密:" + content; + } +} diff --git a/students/740707954/src/main/java/dp/decorator/FilterEmail.java b/students/740707954/src/main/java/dp/decorator/FilterEmail.java new file mode 100644 index 0000000000..c063b0c3da --- /dev/null +++ b/students/740707954/src/main/java/dp/decorator/FilterEmail.java @@ -0,0 +1,18 @@ +package dp.decorator; + +/** + * Created by lx on 2017/7/29. + */ +public class FilterEmail implements Email { + + private Email email; + + public FilterEmail(Email email) { + this.email = email; + } + + @Override + public String getContent() { + return email.getContent(); + } +} diff --git a/students/740707954/src/main/java/dp/decorator/OutsideEmailImpl.java b/students/740707954/src/main/java/dp/decorator/OutsideEmailImpl.java new file mode 100644 index 0000000000..07f53202af --- /dev/null +++ b/students/740707954/src/main/java/dp/decorator/OutsideEmailImpl.java @@ -0,0 +1,22 @@ +package dp.decorator; + +/** + * 外部邮件 + * Created by lx on 2017/7/29. + */ +public class OutsideEmailImpl extends FilterEmail { + + public OutsideEmailImpl(Email email) { + super(email); + } + + @Override + public String getContent() { + return super.getContent() + addSuffix(); + } + + public String addSuffix() { + return "本邮件仅为个人观点,并不代表公司立场"; + } + +} diff --git "a/students/740707954/src/main/java/dp/\350\256\276\350\256\241\346\250\241\345\274\217\344\275\234\344\270\232" "b/students/740707954/src/main/java/dp/\350\256\276\350\256\241\346\250\241\345\274\217\344\275\234\344\270\232" new file mode 100644 index 0000000000..e69de29bb2 diff --git a/students/740707954/src/main/java/ood/srp1/ConfigurationKeys.java b/students/740707954/src/main/java/ood/srp1/ConfigurationKeys.java new file mode 100644 index 0000000000..65f5e77dc4 --- /dev/null +++ b/students/740707954/src/main/java/ood/srp1/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package ood.srp1; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/740707954/src/main/java/ood/srp1/MailSender.java b/students/740707954/src/main/java/ood/srp1/MailSender.java new file mode 100644 index 0000000000..410c9ab27f --- /dev/null +++ b/students/740707954/src/main/java/ood/srp1/MailSender.java @@ -0,0 +1,73 @@ +package ood.srp1; + +import ood.srp1.entity.Email; +import ood.srp1.entity.Product; +import ood.srp1.server.MainSmtpFactory; +import ood.srp1.server.SmtpServer; +import ood.srp1.server.TempSmtpFactory; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +/** + * 邮件发送器 + * Created by lx on 2017/6/17. + */ +public class MailSender { + + protected SmtpServer mainServer = new MainSmtpFactory().createSmtp(); + protected SmtpServer tempServer = new TempSmtpFactory().createSmtp(); + public static final String NAME_KEY = "NAME"; + + /** + * 批量发送邮件 + * @param p 产品信息 + * @param sendUserList 用户信息 + * @param d + * @throws java.io.IOException + */ + public void batchSendEMail(Product p, List sendUserList, boolean d) throws IOException { + System.out.println("--------开始发送邮件-------"); + if (null == sendUserList || sendUserList.size() == 0) { + System.out.println("没有邮件发送"); + return; + } + + for (Map userInfo : sendUserList) { + Email email = new Email(); + String toAddr = userInfo.get("EMAIL").toString(); + email.setToAddress(toAddr); + email.setFromAddress(mainServer.address); + email.setSubject("您关注的产品降价了"); + email.setMessage("尊敬的 " + userInfo.get(NAME_KEY).toString() + ", 您关注的产品 " + p.getProductDesc() + " 降价了,欢迎购买!"); + try { + sendEmail(email, d); + } catch (Exception e) { + try { + email.setFromAddress(tempServer.address); + sendEmail(email, d); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + } + + /** + * 发送邮件 + * @param n + * @param debug + */ + public static void sendEmail(Email n, boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(n.getFromAddress()).append("\n"); + buffer.append("To:").append(n.getToAddress()).append("\n"); + buffer.append("Subject:").append(n.getSubject()).append("\n"); + buffer.append("Content:").append(n.getMessage()).append("\n"); + System.out.println(buffer.toString()); + + } +} diff --git a/students/740707954/src/main/java/ood/srp1/PromotionMail.java b/students/740707954/src/main/java/ood/srp1/PromotionMail.java new file mode 100644 index 0000000000..865ae00896 --- /dev/null +++ b/students/740707954/src/main/java/ood/srp1/PromotionMail.java @@ -0,0 +1,32 @@ +package ood.srp1; + +import ood.srp1.entity.Product; +import ood.srp1.server.UserServer; +import ood.srp1.server.ProductServer; + +import java.util.List; +import java.util.Map; + +/** + * promotion 提升 + */ +public class PromotionMail { + // 用户信息 + private static UserServer ms = new UserServer(); + // 邮件发送器 + private static MailSender mSend = new MailSender(); + + public static void main(String[] args) throws Exception { + // 获取产品信息 + List pList = ProductServer.getUserProduct(); + + for (Product p : pList) { + System.out.println("产品ID: " + p.getProductId() + "\n" + "产品描述:" + p.getProductDesc()); + // 获取接收产品用户列表 + List sendUserList = ms.querySendUser(p.getProductId()); + // 发送邮件 + mSend.batchSendEMail(p, sendUserList, false); + } + + } +} diff --git a/students/740707954/src/main/java/ood/srp1/conf/Configuration.java b/students/740707954/src/main/java/ood/srp1/conf/Configuration.java new file mode 100644 index 0000000000..d1fa32b6bf --- /dev/null +++ b/students/740707954/src/main/java/ood/srp1/conf/Configuration.java @@ -0,0 +1,27 @@ +package ood.srp1.conf; + +import ood.srp1.ConfigurationKeys; + +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public static String getProperty(String key) { + return configurations.get(key); + } + +} diff --git a/students/740707954/src/main/java/ood/srp1/entity/Email.java b/students/740707954/src/main/java/ood/srp1/entity/Email.java new file mode 100644 index 0000000000..57103bb760 --- /dev/null +++ b/students/740707954/src/main/java/ood/srp1/entity/Email.java @@ -0,0 +1,57 @@ +package ood.srp1.entity; + +/** + * 邮件 + * Created by Administrator on 2017/6/15 0015. + */ +public class Email { + private String subject; + private String message; + private String toAddress; + private String fromAddress; + private String smtpHost; + + public Email() { + + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getSmtpHost() { + return smtpHost; + } + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } +} diff --git a/students/740707954/src/main/java/ood/srp1/entity/Product.java b/students/740707954/src/main/java/ood/srp1/entity/Product.java new file mode 100644 index 0000000000..0eed36cb74 --- /dev/null +++ b/students/740707954/src/main/java/ood/srp1/entity/Product.java @@ -0,0 +1,35 @@ +package ood.srp1.entity; + +/** + * 产品信息 + * Created by Administrator on 2017/6/15 0015. + */ +public class Product { + private String productId = null; + private String productDesc = null; + + public Product() { + + } + + public Product(String productId, String productDesc) { + this.productId = productId; + this.productDesc = productDesc; + } + + public void setProductId(String productId) { + this.productId = productId; + } + + public String getProductId() { + return productId; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git a/students/740707954/src/main/java/ood/srp1/product_promotion.txt b/students/740707954/src/main/java/ood/srp1/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/740707954/src/main/java/ood/srp1/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/740707954/src/main/java/ood/srp1/server/MainSmtpFactory.java b/students/740707954/src/main/java/ood/srp1/server/MainSmtpFactory.java new file mode 100644 index 0000000000..644ef5988e --- /dev/null +++ b/students/740707954/src/main/java/ood/srp1/server/MainSmtpFactory.java @@ -0,0 +1,11 @@ +package ood.srp1.server; + +/** + * Created by lx on 2017/6/17. + */ +public class MainSmtpFactory implements SmtpFactory { + @Override + public SmtpServer createSmtp() { + return new MainSmtpServer(); + } +} diff --git a/students/740707954/src/main/java/ood/srp1/server/MainSmtpServer.java b/students/740707954/src/main/java/ood/srp1/server/MainSmtpServer.java new file mode 100644 index 0000000000..127d0fbef9 --- /dev/null +++ b/students/740707954/src/main/java/ood/srp1/server/MainSmtpServer.java @@ -0,0 +1,30 @@ +package ood.srp1.server; + +import ood.srp1.ConfigurationKeys; +import ood.srp1.conf.Configuration; + +/** + * 主要服务器 + * Created by Administrator on 2017/6/15 0015. + */ +public class MainSmtpServer extends SmtpServer { + + public MainSmtpServer() { + address = Configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN); + host = Configuration.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + /** + * 设置服务器地址 + */ + public void setServerAddr() { + address = Configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + /** + * 设置服务器host + */ + public void setServerHost() { + host = Configuration.getProperty(ConfigurationKeys.SMTP_SERVER); + } +} diff --git a/students/740707954/src/main/java/ood/srp1/server/ProductServer.java b/students/740707954/src/main/java/ood/srp1/server/ProductServer.java new file mode 100644 index 0000000000..94dbea20e4 --- /dev/null +++ b/students/740707954/src/main/java/ood/srp1/server/ProductServer.java @@ -0,0 +1,55 @@ +package ood.srp1.server; + +import ood.srp1.entity.Product; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + *产品服务 + * Created by lx on 2017/6/17. + */ +public class ProductServer { + private static List pList = new ArrayList<>(); + static { + try { + initSpecialProductList(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * 生成优惠产品信息 + * @return + * @throws java.io.IOException + */ + private static void initSpecialProductList() throws IOException { + String filePath = System.getProperty("user.dir") + "/src/main/java/ood/srp1/product_promotion.txt"; + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(filePath)); + String pInfo; + while ((pInfo = br.readLine()) != null) { + String[] data = pInfo.split(" "); + pList.add(new Product(data[0], data[1])); + } + } catch (IOException e) { + throw new IOException( "读取文件内容失败 " + e.getMessage()); + } finally { + if (br != null) { + br.close(); + } + } + } + + /** + * 获取用户的产品 + * @return + */ + public static List getUserProduct() { + return pList; + } +} diff --git a/students/740707954/src/main/java/ood/srp1/server/SmtpFactory.java b/students/740707954/src/main/java/ood/srp1/server/SmtpFactory.java new file mode 100644 index 0000000000..07606ca9c2 --- /dev/null +++ b/students/740707954/src/main/java/ood/srp1/server/SmtpFactory.java @@ -0,0 +1,8 @@ +package ood.srp1.server; + +/** + * Created by lx on 2017/6/17. + */ +public interface SmtpFactory { + public SmtpServer createSmtp(); +} \ No newline at end of file diff --git a/students/740707954/src/main/java/ood/srp1/server/SmtpServer.java b/students/740707954/src/main/java/ood/srp1/server/SmtpServer.java new file mode 100644 index 0000000000..7bc254ede3 --- /dev/null +++ b/students/740707954/src/main/java/ood/srp1/server/SmtpServer.java @@ -0,0 +1,19 @@ +package ood.srp1.server; + +/** + * Created by Administrator on 2017/6/15 0015. + */ +public abstract class SmtpServer { + public String address = ""; + public String host = ""; + + /** + * 设置服务器地址 + */ + abstract void setServerAddr(); + + /** + * 设置服务器host + */ + abstract void setServerHost(); +} diff --git a/students/740707954/src/main/java/ood/srp1/server/TempSmtpFactory.java b/students/740707954/src/main/java/ood/srp1/server/TempSmtpFactory.java new file mode 100644 index 0000000000..1360c42c84 --- /dev/null +++ b/students/740707954/src/main/java/ood/srp1/server/TempSmtpFactory.java @@ -0,0 +1,11 @@ +package ood.srp1.server; + +/** + * Created by lx on 2017/6/17. + */ +public class TempSmtpFactory implements SmtpFactory { + @Override + public SmtpServer createSmtp() { + return new TempSmtpServer(); + } +} diff --git a/students/740707954/src/main/java/ood/srp1/server/TempSmtpServer.java b/students/740707954/src/main/java/ood/srp1/server/TempSmtpServer.java new file mode 100644 index 0000000000..9c2ffebac1 --- /dev/null +++ b/students/740707954/src/main/java/ood/srp1/server/TempSmtpServer.java @@ -0,0 +1,29 @@ +package ood.srp1.server; + +import ood.srp1.ConfigurationKeys; +import ood.srp1.conf.Configuration; + +/** + * 备用服务器 + * Created by Administrator on 2017/6/15 0015. + */ +public class TempSmtpServer extends SmtpServer { + + public TempSmtpServer() { + address = Configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN); + host = Configuration.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + } + /** + * 设置服务器地址 + */ + public void setServerAddr() { + address = Configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + /** + * 设置服务器host + */ + public void setServerHost() { + host = Configuration.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + } +} diff --git a/students/740707954/src/main/java/ood/srp1/server/UserServer.java b/students/740707954/src/main/java/ood/srp1/server/UserServer.java new file mode 100644 index 0000000000..952aca1d60 --- /dev/null +++ b/students/740707954/src/main/java/ood/srp1/server/UserServer.java @@ -0,0 +1,19 @@ +package ood.srp1.server; + +import ood.srp1.util.DBUtil; +import java.util.List; +import java.util.Map; + +/** + * Created by lx on 2017/6/17. + */ +public class UserServer { + + /** + * 查询发送人 + * @return + */ + public List querySendUser(String productId){ + return DBUtil.query("Select name from subscriptions where product_id= '" + productId + "' and send_mail=1 "); + } +} diff --git a/students/740707954/src/main/java/ood/srp1/util/DBUtil.java b/students/740707954/src/main/java/ood/srp1/util/DBUtil.java new file mode 100644 index 0000000000..715051d3c0 --- /dev/null +++ b/students/740707954/src/main/java/ood/srp1/util/DBUtil.java @@ -0,0 +1,25 @@ +package ood.srp1.util; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/740707954/src/main/java/payroll/Employee.java b/students/740707954/src/main/java/payroll/Employee.java new file mode 100644 index 0000000000..65ac530d81 --- /dev/null +++ b/students/740707954/src/main/java/payroll/Employee.java @@ -0,0 +1,72 @@ +package payroll; + +import payroll.affiliation.Affiliation; +import payroll.classify.PaymentClassification; +import payroll.method.PaymentMethod; +import payroll.schedule.PaymentSchedule; + +import java.util.Date; + +/** + * 员工 + * Created by lx on 2017/7/8. + */ +public class Employee { + private String id; + private String name; + private String address; + private Affiliation affiliation; + + private PaymentClassification classification; + private PaymentSchedule schedule; + private PaymentMethod paymentMethod; + + public Employee(String name, String address) { + this.name = name; + this.address = address; + } + + /** + * 计算员工薪水 + * @param pc + */ + public void calculatePay(PayCheck pc) { + double grossPay = classification.calculdatePay(pc); + double deductions = affiliation.calculateDeductions(pc); + double netPay = grossPay - deductions; + pc.setGrossPay(grossPay); + pc.setDeductions(deductions); + pc.setNetPay(netPay); + paymentMethod.pay(pc); + } + + /** + * 是否为支付日 + * @param d + * @return + */ + public boolean isPayDay(Date d) { + return schedule.isPayDate(d); + } + + /** + * 获取支付的起始时间 + * @param d + * @return + */ + public Date getPayPeriodStartDate(Date d) { + return schedule.getPayPeriodStartDate(d); + } + + public void setClassifcation(PaymentClassification classifcation) { + this.classification = classifcation; + } + + public void setSchedule(PaymentSchedule schedule) { + this.schedule = schedule; + } + + public void setPaymentMethod(PaymentMethod paymentMethod) { + this.paymentMethod = paymentMethod; + } +} diff --git a/students/740707954/src/main/java/payroll/PayCheck.java b/students/740707954/src/main/java/payroll/PayCheck.java new file mode 100644 index 0000000000..b469890593 --- /dev/null +++ b/students/740707954/src/main/java/payroll/PayCheck.java @@ -0,0 +1,40 @@ +package payroll; + +import java.util.Date; + +/** + * 可以检查是否重复执行 + * Created by lx on 2017/7/8. + */ +public class PayCheck { + private Date payPeriodStart; + private Date payPeriodEnd; + private double grossPay;// 应付 + private double netPay;// 实付 + private double deductions;// 扣除 + + public PayCheck(Date payPeriodStart, Date payPeriodEnd) { + this.payPeriodStart = payPeriodStart; + this.payPeriodEnd = payPeriodEnd; + } + + public Date getPayPeriodEnd() { + return payPeriodEnd; + } + + public Date getPayPeriodStart() { + return payPeriodStart; + } + + public void setGrossPay(double grossPay) { + this.grossPay = grossPay; + } + + public void setNetPay(double netPay) { + this.netPay = netPay; + } + + public void setDeductions(double deductions) { + this.deductions = deductions; + } +} diff --git a/students/740707954/src/main/java/payroll/PaySystem.java b/students/740707954/src/main/java/payroll/PaySystem.java new file mode 100644 index 0000000000..ac81d79d22 --- /dev/null +++ b/students/740707954/src/main/java/payroll/PaySystem.java @@ -0,0 +1,30 @@ +package payroll; + +import payroll.service.IPayrollService; +import payroll.service.PayrollServiceImpl; +import java.util.Date; +import java.util.List; + +/** + * 薪水支付系统 + * Created by lx on 2017/7/8. + */ +public class PaySystem { + private static IPayrollService payrollService; + + static { + payrollService = new PayrollServiceImpl(); + } + + public static void main(String[] args) { + Date date = new Date(); + List employees = payrollService.getAllEmployees(); + for (Employee e : employees) { + if (e.isPayDay(date)) { + PayCheck pc = new PayCheck(e.getPayPeriodStartDate(date), date); + e.calculatePay(pc); + payrollService.savePaycheck(pc); + } + } + } +} diff --git a/students/740707954/src/main/java/payroll/TimeCard.java b/students/740707954/src/main/java/payroll/TimeCard.java new file mode 100644 index 0000000000..db41ff2da3 --- /dev/null +++ b/students/740707954/src/main/java/payroll/TimeCard.java @@ -0,0 +1,19 @@ +package payroll; + +import java.util.Date; + +/** + * Created by lx on 2017/7/8. + */ +public class TimeCard { + private Date date; + private int hours; + + public Date getDate(){ + return date; + } + + public int getHours() { + return hours; + } +} diff --git a/students/740707954/src/main/java/payroll/affiliation/Affiliation.java b/students/740707954/src/main/java/payroll/affiliation/Affiliation.java new file mode 100644 index 0000000000..15b2a4b41b --- /dev/null +++ b/students/740707954/src/main/java/payroll/affiliation/Affiliation.java @@ -0,0 +1,17 @@ +package payroll.affiliation; + +import payroll.PayCheck; + +/** + * Affiliation 会员 + * Created by lx on 2017/7/8. + */ +public interface Affiliation { + + /** + * 计算服务费 + * @param pc + * @return + */ + double calculateDeductions(PayCheck pc); +} diff --git a/students/740707954/src/main/java/payroll/affiliation/NonAffiliation.java b/students/740707954/src/main/java/payroll/affiliation/NonAffiliation.java new file mode 100644 index 0000000000..0bd2232001 --- /dev/null +++ b/students/740707954/src/main/java/payroll/affiliation/NonAffiliation.java @@ -0,0 +1,14 @@ +package payroll.affiliation; + +import payroll.PayCheck; + +/** + * 非会员 + * Created by lx on 2017/7/8. + */ +public class NonAffiliation implements Affiliation { + @Override + public double calculateDeductions(PayCheck pc) { + return 0; + } +} diff --git a/students/740707954/src/main/java/payroll/affiliation/ServiceCharge.java b/students/740707954/src/main/java/payroll/affiliation/ServiceCharge.java new file mode 100644 index 0000000000..7d89f17e27 --- /dev/null +++ b/students/740707954/src/main/java/payroll/affiliation/ServiceCharge.java @@ -0,0 +1,28 @@ +package payroll.affiliation; + +import java.util.Date; + +/** + * 服务费用 + * Created by lx on 2017/7/8. + */ +public class ServiceCharge { + private Date date; + private double amount; + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public double getAmount() { + return amount; + } + + public void setAmount(double amount) { + this.amount = amount; + } +} diff --git a/students/740707954/src/main/java/payroll/affiliation/UnionAffiliation.java b/students/740707954/src/main/java/payroll/affiliation/UnionAffiliation.java new file mode 100644 index 0000000000..44f482dda8 --- /dev/null +++ b/students/740707954/src/main/java/payroll/affiliation/UnionAffiliation.java @@ -0,0 +1,40 @@ +package payroll.affiliation; + +import payroll.PayCheck; +import payroll.util.DateUtil; +import java.util.Date; +import java.util.Map; + +/** + * 会员 + * Created by lx on 2017/7/8. + */ +public class UnionAffiliation implements Affiliation { + private int memeberId = 0; + private double weekDue = 0; + private Map charege; + + /** + * 计算服务费用 + * @param pc + * @return + */ + @Override + public double calculateDeductions(PayCheck pc) { + int fridays = DateUtil.getFridaysBetween(pc.getPayPeriodStart(), pc.getPayPeriodEnd()); + double totalDue = fridays * weekDue; + double totalCharge = 0.0d; + for (Map.Entry entry : charege.entrySet()) { + ServiceCharge sc = entry.getValue(); + totalCharge += sc.getAmount(); +// calculateCharge(sc); + } + return totalCharge + totalDue; + } + +// private double calculateCharge(ServiceCharge sc) { +// return sc.getAmount(); +// } + + +} diff --git a/students/740707954/src/main/java/payroll/classify/CommissionClassification.java b/students/740707954/src/main/java/payroll/classify/CommissionClassification.java new file mode 100644 index 0000000000..6fa1705c03 --- /dev/null +++ b/students/740707954/src/main/java/payroll/classify/CommissionClassification.java @@ -0,0 +1,36 @@ +package payroll.classify; + +import payroll.PayCheck; +import payroll.util.DateUtil; + +import java.util.Date; +import java.util.Map; + +/** + * 佣金雇员 + * Created by lx on 2017/7/8. + */ +public class CommissionClassification implements PaymentClassification { + private Map salesReceipt;// 销售凭条 + private double salary;//薪水 + private double rate;//单价 + + /** + * 计算薪水 + * @param pc + * @return + */ + @Override + public double calculdatePay(PayCheck pc) { + //1 统计销售凭条在pc.getStartDate 和 pc.getEndDate之间 + //2 加上基本工资,计算薪水 + double commission = 0.0d; + for (Map.Entry entry : salesReceipt.entrySet()) { + SalesReceipt receipt = entry.getValue(); + if (DateUtil.between(receipt.getDate(), pc.getPayPeriodStart(), pc.getPayPeriodEnd())) { + commission = receipt.getAmount() * rate; + } + } + return commission + salary; + } +} diff --git a/students/740707954/src/main/java/payroll/classify/HourlyClassification.java b/students/740707954/src/main/java/payroll/classify/HourlyClassification.java new file mode 100644 index 0000000000..30e4f5c59f --- /dev/null +++ b/students/740707954/src/main/java/payroll/classify/HourlyClassification.java @@ -0,0 +1,50 @@ +package payroll.classify; + +import payroll.PayCheck; +import payroll.util.DateUtil; + +import java.util.Date; +import java.util.Map; + +/** + * 小时工 + * Created by lx on 2017/7/8. + */ +public class HourlyClassification implements PaymentClassification { + private Map timeCards; + private double rate;// 价格 + + /** + * 统计时间卡在pc.getStartDate 和 pc.getEndDate之间 + * 并计算薪水 + * + * @param pc + * @return + */ + @Override + public double calculdatePay(PayCheck pc) { + double totalPay = 0.0d; + for (Map.Entry entry : timeCards.entrySet()) { + TimeCard tc = entry.getValue(); + if (DateUtil.between(tc.getDate(), pc.getPayPeriodStart(), pc.getPayPeriodEnd())) { + totalPay += calculatePayForTimeCard(tc); + } + } + return totalPay; + } + + /** + * 计算每个时间卡的薪水 + * + * @param tc + * @return + */ + public double calculatePayForTimeCard(TimeCard tc) { + int hours = tc.getHours(); + if (tc.getHours() > 8) { + return 8 * rate + (hours - 8) * 1.5 * rate; + } else { + return 8 * rate; + } + } +} diff --git a/students/740707954/src/main/java/payroll/classify/PaymentClassification.java b/students/740707954/src/main/java/payroll/classify/PaymentClassification.java new file mode 100644 index 0000000000..6cb2dafeee --- /dev/null +++ b/students/740707954/src/main/java/payroll/classify/PaymentClassification.java @@ -0,0 +1,11 @@ +package payroll.classify; + +import payroll.PayCheck; + +/** + * 分类 + * Created by lx on 2017/7/8. + */ +public interface PaymentClassification { + public double calculdatePay(PayCheck pc); +} diff --git a/students/740707954/src/main/java/payroll/classify/SalariedClassification.java b/students/740707954/src/main/java/payroll/classify/SalariedClassification.java new file mode 100644 index 0000000000..863d42e381 --- /dev/null +++ b/students/740707954/src/main/java/payroll/classify/SalariedClassification.java @@ -0,0 +1,21 @@ +package payroll.classify; + +import payroll.PayCheck; + +/** + * 月薪雇员 + * Created by lx on 2017/7/8. + */ +public class SalariedClassification implements PaymentClassification { + private double salary; + + /** + * 计算支付 + * @param pc + * @return + */ + @Override + public double calculdatePay(PayCheck pc) { + return salary; + } +} diff --git a/students/740707954/src/main/java/payroll/classify/SalesReceipt.java b/students/740707954/src/main/java/payroll/classify/SalesReceipt.java new file mode 100644 index 0000000000..2eae0fe092 --- /dev/null +++ b/students/740707954/src/main/java/payroll/classify/SalesReceipt.java @@ -0,0 +1,28 @@ +package payroll.classify; + +import java.util.Date; + +/** + * 销售凭条 + * Created by lx on 2017/7/8. + */ +public class SalesReceipt { + private Date date; + private double amount; + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public double getAmount() { + return amount; + } + + public void setAmount(double amount) { + this.amount = amount; + } +} diff --git a/students/740707954/src/main/java/payroll/classify/TimeCard.java b/students/740707954/src/main/java/payroll/classify/TimeCard.java new file mode 100644 index 0000000000..86b760083f --- /dev/null +++ b/students/740707954/src/main/java/payroll/classify/TimeCard.java @@ -0,0 +1,28 @@ +package payroll.classify; + +import java.util.Date; + +/** + * 时间卡 + * Created by lx on 2017/7/8. + */ +public class TimeCard { + private int hours;// 上班时间 + private Date date;// 那天上班 + + public int getHours() { + return hours; + } + + public void setHours(int hours) { + this.hours = hours; + } + + public void setDate(Date date) { + this.date = date; + } + + public Date getDate() { + return date; + } +} diff --git a/students/740707954/src/main/java/payroll/method/BankMethod.java b/students/740707954/src/main/java/payroll/method/BankMethod.java new file mode 100644 index 0000000000..4009040157 --- /dev/null +++ b/students/740707954/src/main/java/payroll/method/BankMethod.java @@ -0,0 +1,14 @@ +package payroll.method; + +import payroll.PayCheck; + +/** + * 银行卡支付 + * Created by lx on 2017/7/8. + */ +public class BankMethod implements PaymentMethod { + @Override + public void pay(PayCheck pc) { + + } +} diff --git a/students/740707954/src/main/java/payroll/method/HoldMethod.java b/students/740707954/src/main/java/payroll/method/HoldMethod.java new file mode 100644 index 0000000000..2261593191 --- /dev/null +++ b/students/740707954/src/main/java/payroll/method/HoldMethod.java @@ -0,0 +1,14 @@ +package payroll.method; + +import payroll.PayCheck; + +/** + * 从财务那里支付 + * Created by lx on 2017/7/8. + */ +public class HoldMethod implements PaymentMethod { + @Override + public void pay(PayCheck pc) { + + } +} diff --git a/students/740707954/src/main/java/payroll/method/MailMethod.java b/students/740707954/src/main/java/payroll/method/MailMethod.java new file mode 100644 index 0000000000..41ae0ff02e --- /dev/null +++ b/students/740707954/src/main/java/payroll/method/MailMethod.java @@ -0,0 +1,14 @@ +package payroll.method; + +import payroll.PayCheck; + +/** + * 邮递支付 + * Created by lx on 2017/7/8. + */ +public class MailMethod implements PaymentMethod{ + @Override + public void pay(PayCheck pc) { + + } +} diff --git a/students/740707954/src/main/java/payroll/method/PaymentMethod.java b/students/740707954/src/main/java/payroll/method/PaymentMethod.java new file mode 100644 index 0000000000..23ca7f954a --- /dev/null +++ b/students/740707954/src/main/java/payroll/method/PaymentMethod.java @@ -0,0 +1,11 @@ +package payroll.method; + +import payroll.PayCheck; + +/** + * 支付方式 + * Created by lx on 2017/7/8. + */ +public interface PaymentMethod { + public void pay(PayCheck pc); +} diff --git a/students/740707954/src/main/java/payroll/schedule/BiWeeklySchedule.java b/students/740707954/src/main/java/payroll/schedule/BiWeeklySchedule.java new file mode 100644 index 0000000000..6bb0dd22f6 --- /dev/null +++ b/students/740707954/src/main/java/payroll/schedule/BiWeeklySchedule.java @@ -0,0 +1,35 @@ +package payroll.schedule; + +import payroll.util.DateUtil; + +import java.util.Date; + +/** + * 每隔一周支付 + * Created by lx on 2017/7/8. + */ +public class BiWeeklySchedule implements PaymentSchedule { + Date firstPayFriday = DateUtil.parse("2017-07-07"); + + /** + * 是否为支付日 + * @param date + * @return + */ + @Override + public boolean isPayDate(Date date) { +// return DateUtil.add(date, -13) == firstPayFriday; + int interval = DateUtil.getDaysBetween(firstPayFriday, date); + return interval % 14 == 0; + } + + /** + * 获取支付薪水日期的起始时间 + * @param payPeriodEndDate + * @return + */ + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.add(payPeriodEndDate, -13); + } +} diff --git a/students/740707954/src/main/java/payroll/schedule/MonthSchedule.java b/students/740707954/src/main/java/payroll/schedule/MonthSchedule.java new file mode 100644 index 0000000000..b229cb7e2f --- /dev/null +++ b/students/740707954/src/main/java/payroll/schedule/MonthSchedule.java @@ -0,0 +1,31 @@ +package payroll.schedule; + +import payroll.util.DateUtil; + +import java.util.Date; + +/** + * 每月月底支付 + * Created by lx on 2017/7/8. + */ +public class MonthSchedule implements PaymentSchedule { + /** + * 是否为支付日 + * @param date + * @return + */ + @Override + public boolean isPayDate(Date date) { + return DateUtil.isLastDayOfMonth(date); + } + + /** + * 获取支付薪水日期的起始时间 + * @param payPeriodEndDate + * @return + */ + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.getFirstDayOfMonth(payPeriodEndDate); + } +} diff --git a/students/740707954/src/main/java/payroll/schedule/PaymentSchedule.java b/students/740707954/src/main/java/payroll/schedule/PaymentSchedule.java new file mode 100644 index 0000000000..f7445d2d3d --- /dev/null +++ b/students/740707954/src/main/java/payroll/schedule/PaymentSchedule.java @@ -0,0 +1,11 @@ +package payroll.schedule; + +import java.util.Date; + +/** + * Created by lx on 2017/7/8. + */ +public interface PaymentSchedule { + public boolean isPayDate(Date date); + public Date getPayPeriodStartDate(Date payPeriodEndDate); +} diff --git a/students/740707954/src/main/java/payroll/schedule/WeeklySchedule.java b/students/740707954/src/main/java/payroll/schedule/WeeklySchedule.java new file mode 100644 index 0000000000..8bf4fed61a --- /dev/null +++ b/students/740707954/src/main/java/payroll/schedule/WeeklySchedule.java @@ -0,0 +1,32 @@ +package payroll.schedule; + +import payroll.util.DateUtil; + +import java.util.Date; + +/** + * 每周五支付 + * Created by lx on 2017/7/8. + */ +public class WeeklySchedule implements PaymentSchedule{ + + /** + * 是否为支付日 + * @param date + * @return + */ + @Override + public boolean isPayDate(Date date) { + return DateUtil.isFriday(date); + } + + /** + * 获取支付薪水日期的起始时间 + * @param payPeriodEndDate + * @return + */ + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.add(payPeriodEndDate, -6); + } +} diff --git a/students/740707954/src/main/java/payroll/service/IPayrollService.java b/students/740707954/src/main/java/payroll/service/IPayrollService.java new file mode 100644 index 0000000000..ea0bf8f78f --- /dev/null +++ b/students/740707954/src/main/java/payroll/service/IPayrollService.java @@ -0,0 +1,14 @@ +package payroll.service; + +import payroll.Employee; +import payroll.PayCheck; +import java.util.List; + +/** + * Created by lx on 2017/7/8. + */ +public interface IPayrollService { + List getAllEmployees(); + + boolean savePaycheck(PayCheck pc); +} diff --git a/students/740707954/src/main/java/payroll/service/PayrollServiceImpl.java b/students/740707954/src/main/java/payroll/service/PayrollServiceImpl.java new file mode 100644 index 0000000000..1df829008d --- /dev/null +++ b/students/740707954/src/main/java/payroll/service/PayrollServiceImpl.java @@ -0,0 +1,31 @@ +package payroll.service; + +import payroll.Employee; +import payroll.PayCheck; +import java.util.List; + +/** + * Created by lx on 2017/7/8. + */ +public class PayrollServiceImpl implements IPayrollService { + + /** + * 获取所有员工信息 + * @return + */ + @Override + public List getAllEmployees() { + return null; + } + + /** + * 保存paycheck + * @param pc + * @return + */ + @Override + public boolean savePaycheck(PayCheck pc) { + System.out.println("保存。。。。。"); + return true; + } +} diff --git a/students/740707954/src/main/java/payroll/util/DateUtil.java b/students/740707954/src/main/java/payroll/util/DateUtil.java new file mode 100644 index 0000000000..f3e7f02d6c --- /dev/null +++ b/students/740707954/src/main/java/payroll/util/DateUtil.java @@ -0,0 +1,80 @@ +package payroll.util; + +import java.util.Date; + +/** + * 日期工具类 + * Created by lx on 2017/7/8. + */ +public class DateUtil { + /** + * 是否为周五 + * @param date + * @return + */ + public static boolean isFriday(Date date) { + return false; + } + + /** + * 返回对指定日期+i的日期 + * @param payPeriodEndDate + * @param i + * @return + */ + public static Date add(Date payPeriodEndDate, int i) { + return null; + } + + /** + * 是否为本月的最后一天 + * @param date + * @return + */ + public static boolean isLastDayOfMonth(Date date) { + return false; + } + + /** + * 获取本月的第一天 + * @param payPeriodEndDate + * @return + */ + public static Date getFirstDayOfMonth(Date payPeriodEndDate) { + return null; + } + + /** + * 将字符串转换为日期 + * @param s + * @return + */ + public static Date parse(String s) { + return null; + } + + /** + * 计算两个日期之间相差的天数 + * @param firstPayFriday + * @param date + * @return + */ + public static int getDaysBetween(Date firstPayFriday, Date date) { + return 0; + } + + public static boolean between(Date date, Date payPeriodStart, Date payPeriodEnd) { + + return false; + } + + /** + * 获取两个时间段中有几个周五 + * @param payPeriodStart + * @param payPeriodEnd + * @return + */ + public static int getFridaysBetween(Date payPeriodStart, Date payPeriodEnd) { + return 0; + } +} diff --git "a/students/740707954/src/main/java/payroll/\351\234\200\346\261\202" "b/students/740707954/src/main/java/payroll/\351\234\200\346\261\202" new file mode 100644 index 0000000000..1e2abc7bc0 --- /dev/null +++ "b/students/740707954/src/main/java/payroll/\351\234\200\346\261\202" @@ -0,0 +1,16 @@ +该系统由一个公司数据库以及和雇员相关的数据(例如工作时间卡)组成,系统需要准时地按照规则给员工支付薪水, +同时,必须从薪水中扣除各种扣款有些雇员是钟点工, 会按照他们雇员记录中每小时的报酬字段的值对他们进行支付, +他们每天提交工作时间卡,其中记录了日期以及工作小时数,如果每天工作超过8小时,按1.5倍进行支付。 +每周五对他们进行支付。有些雇员完全以月薪进行支付,每个月的最后一个工作日对他们进行支付, +在他们的雇员记录中有个月薪字段 同时,对于一些带薪的雇员,会根据他们的销售情况,支付给他们一定数量的佣金, +他们会提交销售凭条,其中记录了销售的日期和数量。在他们的雇员记录中有一个酬金报酬字段。 +每隔一周的周五对他们进行支付。雇员可以选择支付方式,可以把支票邮寄到他们指定的邮政地址, +也可以保存在财务那里随时支取,或者要求直接存入他们指定的银行账户 一些雇员会加入协会,在他们的雇员记录中有一个每周应付款项字段, +这些应付款需要从他们的薪水中扣除。协会有时会针对单个会员征收服务费用。 +协会每周会提交这些服务费用,服务费用从相应雇员的薪水总额中扣除。薪水支付程序每个工作日运行一次, 并在当天对相应的雇员进行支付, +系统会被告知雇员的支付日期,这样它会计算从雇员上次支付日期到规定的支付日期间应付的数额。 + + +雇员类型:小时工、领月薪的、带薪的 +支付方式:打到银行卡、邮递、保存在财务那里 +支付时间:每周五、每隔一周、每个月 diff --git a/students/740707954/src/test/java/BridgeTest.java b/students/740707954/src/test/java/BridgeTest.java new file mode 100644 index 0000000000..90fd115a40 --- /dev/null +++ b/students/740707954/src/test/java/BridgeTest.java @@ -0,0 +1,28 @@ +import dp.bridge.v2.*; +import org.junit.Test; + +/** + * Created by lx on 2017/7/29. + */ +public class BridgeTest { + + @Test + public void testBridge() { + Shape r = new Rectangle(1, 2, 3, 4); + Shape c = new Cicle(1, 2, 3); + Drawing d1 = new DrawingGL1(); + Drawing d2 = new DrawingGL2(); + + r.setDrawing(d1); + r.draw(); + + c.setDrawing(d1); + c.draw(); + + r.setDrawing(d2); + r.draw(); + + c.setDrawing(d2); + c.draw(); + } +} diff --git a/students/740707954/src/test/java/ChainTest.java b/students/740707954/src/test/java/ChainTest.java new file mode 100644 index 0000000000..a9c676bd90 --- /dev/null +++ b/students/740707954/src/test/java/ChainTest.java @@ -0,0 +1,31 @@ +import dp.ChainOfResponsibility.EmailLogger; +import dp.ChainOfResponsibility.FileLogger; +import dp.ChainOfResponsibility.Logger; +import dp.ChainOfResponsibility.StdoutLogger; +import org.junit.Test; + +/** + * 责任链测试 + * Created by lx on 2017/8/12. + */ +public class ChainTest { + private static Logger l = new StdoutLogger(Logger.DEBUG).setNext(new EmailLogger(Logger.NOTICE).setNext(new FileLogger(Logger.ERR))); + + @Test + public void testDebug() { + // StdoutLooger处理 + l.message("进入计算函数", Logger.DEBUG); + } + + @Test + public void testNotic() { + // StdoutLogger和EmailLogger处理 + l.message("第一步已经完成", Logger.NOTICE); + } + + @Test + public void testErr() { + // 三个都处理 + l.message("一个致命的错误发生了", Logger.ERR); + } +} diff --git a/students/740707954/src/test/java/CommandTest.java b/students/740707954/src/test/java/CommandTest.java new file mode 100644 index 0000000000..9184b55bc9 --- /dev/null +++ b/students/740707954/src/test/java/CommandTest.java @@ -0,0 +1,24 @@ +import dp.command.*; +import org.junit.Test; + +/** + * Created by lx on 2017/8/12. + */ +public class CommandTest { + + @Test + public void testCommand() { + // 创建厨师 + Cook cook = new Cook(); + + // 创建店小二 + Waiter waiter = new Waiter(); + + Command command1 = new OrderSteakCommand(cook); + Command command2 = new OrderPorkCommand(cook); + + waiter.addOrder(command1); + waiter.addOrder(command2); + waiter.sendOrders(); + } +} diff --git a/students/740707954/src/test/java/CompositeTest.java b/students/740707954/src/test/java/CompositeTest.java new file mode 100644 index 0000000000..141326e1dd --- /dev/null +++ b/students/740707954/src/test/java/CompositeTest.java @@ -0,0 +1,23 @@ +import dp.composite.*; +import org.junit.Test; + +/** + * Created by lx on 2017/7/29. + */ +public class CompositeTest { + + @Test + public void testComp() { + Picture picture1 = new Picture(); + Picture picture = new Picture(); + picture1.addShape(new Text()); + picture1.addShape(new Line()); + picture1.addShape(new Square()); + picture.addShape(picture1); + picture.addShape(new Line()); + picture.addShape(new Rectangle()); + + picture.draw(); + + } +} diff --git a/students/740707954/src/test/java/EmailTest.java b/students/740707954/src/test/java/EmailTest.java new file mode 100644 index 0000000000..624f11dffc --- /dev/null +++ b/students/740707954/src/test/java/EmailTest.java @@ -0,0 +1,17 @@ +import dp.decorator.Email; +import dp.decorator.EmailImpl; +import dp.decorator.EncryptionEmailImpl; +import dp.decorator.OutsideEmailImpl; +import org.junit.Test; + +/** + * Created by lx on 2017/7/29. + */ +public class EmailTest { + @Test + public void testEmail() { + Email e = new OutsideEmailImpl(new EncryptionEmailImpl(new EmailImpl("内容\n"))); + System.out.println(e.getContent()); + } + +} diff --git a/students/740707954/src/test/java/TagBuilderTest.java b/students/740707954/src/test/java/TagBuilderTest.java new file mode 100644 index 0000000000..1cc5388f49 --- /dev/null +++ b/students/740707954/src/test/java/TagBuilderTest.java @@ -0,0 +1,40 @@ +import dp.builder.TagBuilder; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.*; +/** + * Created by lx on 2017/7/23. + */ +public class TagBuilderTest { + + @Before + public void setUp() throws Exception{ + System.out.println("up"); + } + + @After + public void tearDown() { + System.out.println("down"); + } + + @Test + public void testToXML() { + TagBuilder builder = new TagBuilder("order"); + + String xml = builder.addChild("line-items") + .addChild("line-item").setAttribute("pid", "P3677").setAttribute("qty", "3") + .addSibling("line-item").setAttribute("pid", "P9877").setAttribute("qty", "10") + .toXML(); + + String expected = "" + + "" + + "" + + "" + + "" + + ""; + + System.out.println(xml); + assertEquals(expected, xml); + } +} diff --git a/students/740707954/src/test/java/test b/students/740707954/src/test/java/test new file mode 100644 index 0000000000..30d74d2584 --- /dev/null +++ b/students/740707954/src/test/java/test @@ -0,0 +1 @@ +test \ No newline at end of file diff --git a/students/75939388/.gitignore b/students/75939388/.gitignore new file mode 100644 index 0000000000..d3a81f6bdb --- /dev/null +++ b/students/75939388/.gitignore @@ -0,0 +1,10 @@ +target/ +.idea/ +ood/target/ +datastrure/target/ + +*.class +*.jar +*.war +*.zip +*.iml diff --git a/students/75939388/datastrure/pom.xml b/students/75939388/datastrure/pom.xml new file mode 100644 index 0000000000..b17b9fe45f --- /dev/null +++ b/students/75939388/datastrure/pom.xml @@ -0,0 +1,15 @@ + + + + season2 + learning2017 + 2.0-SEASON2 + + 4.0.0 + + datastrure + + + \ No newline at end of file diff --git a/students/75939388/datastrure/src/main/java/tree/BinaryTreeNode.java b/students/75939388/datastrure/src/main/java/tree/BinaryTreeNode.java new file mode 100644 index 0000000000..f0802fdceb --- /dev/null +++ b/students/75939388/datastrure/src/main/java/tree/BinaryTreeNode.java @@ -0,0 +1,10 @@ +package tree; + +/** + * Created by Tee on 2017/6/15. + */ +public class BinaryTreeNode { + /** + * 二叉树 + */ +} diff --git a/students/75939388/datastrure/src/test/java/tree/BinaryTreeNodeTest.java b/students/75939388/datastrure/src/test/java/tree/BinaryTreeNodeTest.java new file mode 100644 index 0000000000..90705ddca2 --- /dev/null +++ b/students/75939388/datastrure/src/test/java/tree/BinaryTreeNodeTest.java @@ -0,0 +1,22 @@ +package tree; + +import org.junit.Before; +import org.junit.Test; + +/** + * Created by Tee on 2017/6/15. + */ +public class BinaryTreeNodeTest { + + BinaryTreeNode tree; + + @Before + public void init(){ + tree = new BinaryTreeNode(); + } + + @Test + public void test1(){ + + } +} diff --git a/students/75939388/ood/pom.xml b/students/75939388/ood/pom.xml new file mode 100644 index 0000000000..e6a1b1de5a --- /dev/null +++ b/students/75939388/ood/pom.xml @@ -0,0 +1,15 @@ + + + + season2 + learning2017 + 2.0-SEASON2 + + 4.0.0 + + ood + + + \ No newline at end of file diff --git a/students/75939388/ood/src/main/java/srp/original/PromotionMail.java b/students/75939388/ood/src/main/java/srp/original/PromotionMail.java new file mode 100644 index 0000000000..8deec60166 --- /dev/null +++ b/students/75939388/ood/src/main/java/srp/original/PromotionMail.java @@ -0,0 +1,202 @@ +package srp.original; + +import srp.refactor.configuration.Configuration; +import srp.refactor.configuration.ConfigurationKeys; +import srp.refactor.util.DBUtil; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery = null; + + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected String productID = null; + protected String productDesc = null; + + private static Configuration config; + + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + + + config = new Configuration(); + + setSMTPHost(); + setAltSMTPHost(); + + + setFromAddress(); + + + setLoadQuery(); + + sendEMails(mailDebug, loadMailingList()); + + + } + + + + + protected void setProductID(String productID) + { + this.productID = productID; + + } + + protected String getproductID() + { + return productID; + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected void setSMTPHost() + { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() + { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + protected void setFromAddress() + { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setMessage(HashMap userInfo) throws IOException + { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + + + + } + + + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + private void setProductDesc(String desc) { + this.productDesc = desc; + } + + + protected void configureEMail(HashMap userInfo) throws IOException + { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try + { + if (toAddress.length() > 0){} +// MailContentUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } + catch (Exception e) + { + + try { +// MailContentUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } + + else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/75939388/ood/src/main/java/srp/refactor/PromotionMailClient.java b/students/75939388/ood/src/main/java/srp/refactor/PromotionMailClient.java new file mode 100644 index 0000000000..6335f4f86e --- /dev/null +++ b/students/75939388/ood/src/main/java/srp/refactor/PromotionMailClient.java @@ -0,0 +1,72 @@ +package srp.refactor; + +import srp.refactor.configuration.Configuration; +import srp.refactor.configuration.ConfigurationKeys; +import srp.refactor.domain.Product; +import srp.refactor.domain.User; +import srp.refactor.mail.MailClient; +import srp.refactor.services.ProductService; +import srp.refactor.services.UserService; + +import java.util.List; + +/** + * 在原有的MailClient邮件功能的基础上修改而来的促销邮件发送端 + * + * 根据SRP原则,这个邮件客户端只有两个职责: + * 解析传进来的List,然后批量保存至超类的待发送邮件列表中 + * 全部解析完成(数据量较大时需要设置阈值)后 + * 由用户发起发送请求 + * + * Created by Tee on 2017/6/15. + */ +public class PromotionMailClient extends MailClient { + + private static Configuration config = new Configuration(); + + private UserService userService = new UserService(); + private ProductService productService = new ProductService(); + + private void init(){ + super.initMailSettings( + config.getProperty(ConfigurationKeys.SMTP_SERVER), + config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER), + config.getProperty(ConfigurationKeys.EMAIL_ADMIN) + ); + } + + public PromotionMailClient(){ + init(); + } + + @Override + public void createMail(String toAddress, String subject, String message){ + this.toAddress = toAddress; + this.subject = subject; + this.message = message; + super.addToMailList(); + } + + /** + * 批量编写邮件 + * @param promotionProducts 促销中的所有产品 + * @throws Exception 查询sql时报的异常,这里选择不处理 + */ + public void batchWrite(List promotionProducts) throws Exception{ + if(promotionProducts.isEmpty()){ + throw new RuntimeException("没有商品待促销不能为空"); + } + for(Product product : promotionProducts){ + String querySql = productService.getLoadQuerySql(product.getProductId()); + List userList = userService.getUserList(querySql); + for(User user : userList){ + String add = user.getEmail(); + String subj = "您关注的" + product.getProductDesc() + "已降价"; + String msg = "尊敬的 "+ user.getName() +", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!"; + + createMail(add, subj, msg); + } + } + } + +} \ No newline at end of file diff --git a/students/75939388/ood/src/main/java/srp/refactor/configuration/Configuration.java b/students/75939388/ood/src/main/java/srp/refactor/configuration/Configuration.java new file mode 100644 index 0000000000..b3b24944d2 --- /dev/null +++ b/students/75939388/ood/src/main/java/srp/refactor/configuration/Configuration.java @@ -0,0 +1,23 @@ +package srp.refactor.configuration; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/75939388/ood/src/main/java/srp/refactor/configuration/ConfigurationKeys.java b/students/75939388/ood/src/main/java/srp/refactor/configuration/ConfigurationKeys.java new file mode 100644 index 0000000000..9b1cfe8dcc --- /dev/null +++ b/students/75939388/ood/src/main/java/srp/refactor/configuration/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package srp.refactor.configuration; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/75939388/ood/src/main/java/srp/refactor/domain/Product.java b/students/75939388/ood/src/main/java/srp/refactor/domain/Product.java new file mode 100644 index 0000000000..955ab28490 --- /dev/null +++ b/students/75939388/ood/src/main/java/srp/refactor/domain/Product.java @@ -0,0 +1,30 @@ +package srp.refactor.domain; + +/** + * Created by Tee on 2017/6/16. + */ +public class Product { + private String productId; + private String productDesc; + + public Product(String productId, String productDesc){ + this.productId = productId; + this.productDesc = productDesc; + } + + public String getProductId() { + return productId; + } + + public void setProductId(String productId) { + this.productId = productId; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git a/students/75939388/ood/src/main/java/srp/refactor/domain/User.java b/students/75939388/ood/src/main/java/srp/refactor/domain/User.java new file mode 100644 index 0000000000..4167396f89 --- /dev/null +++ b/students/75939388/ood/src/main/java/srp/refactor/domain/User.java @@ -0,0 +1,30 @@ +package srp.refactor.domain; + +/** + * Created by Tee on 2017/6/16. + */ +public class User { + private String name; + private String email; + + public User(String name, String email){ + this.name = name; + this.email = email; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/students/75939388/ood/src/main/java/srp/refactor/mail/MailClient.java b/students/75939388/ood/src/main/java/srp/refactor/mail/MailClient.java new file mode 100644 index 0000000000..3ca783fe0d --- /dev/null +++ b/students/75939388/ood/src/main/java/srp/refactor/mail/MailClient.java @@ -0,0 +1,95 @@ +package srp.refactor.mail; + +import org.apache.commons.lang3.StringUtils; +import srp.refactor.services.MailService; +import srp.refactor.util.Constants; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * 具有初始化设置、可以批量发送邮件的邮件客户端 + * + * Created by Tee on 2017/6/15. + */ +public abstract class MailClient { + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected List mailList; + + private MailService mailService = new MailService(); + /** + * 初始化邮件设置 + * + * @param smtpHost smtp主机 + * @param altSmtpHost 备用smtp主机 + * @param fromAddress 发件人地址 + */ + protected void initMailSettings(String smtpHost, String altSmtpHost, String fromAddress){ + this.smtpHost = smtpHost; + this.altSmtpHost = altSmtpHost; + this.fromAddress = fromAddress; + this.mailList = new ArrayList<>(); + } + + public abstract void createMail(String toAddress, String subject, String message); + + /** + * 撰写邮件 + */ + protected void addToMailList(){ + HashMap mailToSend = new HashMap<>(); + mailToSend.put(Constants.EmailInfo.TO_ADDRESS_KEY.getKey(), this.toAddress); + mailToSend.put(Constants.EmailInfo.SUBJECT_KEY.getKey(), this.subject); + mailToSend.put(Constants.EmailInfo.MESSAGE_KEY.getKey(), this.message); + this.mailList.add(mailToSend); + } + + private boolean isInit(){ + return StringUtils.isNotBlank(this.smtpHost) && + StringUtils.isNotBlank(this.altSmtpHost) && + StringUtils.isNotBlank(this.fromAddress); + } + + public String getSmtpHost() { + return smtpHost; + } + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + /** + * 调用邮件邮件服务器来收发邮件 + * @param debug + */ + public void batchSend(boolean debug){ + if(!isInit()){ + throw new RuntimeException("邮件客户端还未做配置"); + } + + mailService.batchSend(debug, this, this.mailList); + } +} diff --git a/students/75939388/ood/src/main/java/srp/refactor/services/MailService.java b/students/75939388/ood/src/main/java/srp/refactor/services/MailService.java new file mode 100644 index 0000000000..27bcb38389 --- /dev/null +++ b/students/75939388/ood/src/main/java/srp/refactor/services/MailService.java @@ -0,0 +1,66 @@ +package srp.refactor.services; + +import org.apache.commons.lang3.StringUtils; +import srp.refactor.mail.MailClient; +import srp.refactor.util.Constants; + +import java.util.HashMap; +import java.util.List; + +/** + * 邮件收发服务 + * + * Created by Tee on 2017/6/16. + */ +public class MailService { + + + /** + * 批量发送 + */ + public void batchSend(boolean debug, MailClient mailClient, List mailList){ + if(mailList.isEmpty()){ + System.out.println("没有邮件要发送"); + return; + } + int size = mailList.size(); + System.out.println("开始发送邮件, 总邮件数=" + size); + int i = 0; + for(HashMap mail : mailList){ + i++; + String toAddress = (String)mail.get(Constants.EmailInfo.TO_ADDRESS_KEY.getKey()); + if(StringUtils.isBlank(toAddress)){ + System.out.println("收件人地址为空,此邮件发送中止"); + continue; + } + + String subject = (String)mail.get(Constants.EmailInfo.SUBJECT_KEY.getKey()); + String message = (String)mail.get(Constants.EmailInfo.MESSAGE_KEY.getKey()); + + System.out.println("\n正在发送第[" + i + "]封邮件"); + System.out.println("=========================================================="); + try{ + sendEmail(toAddress, mailClient.getFromAddress(), subject, message, mailClient.getSmtpHost(), debug); + }catch(Exception e){ + sendEmail(toAddress, mailClient.getFromAddress(), subject, message, mailClient.getAltSmtpHost(), debug); + } + System.out.println("=========================================================="); + System.out.println("第[" + i + "]封邮件发送完成"); + } + } + + /** + * 发送邮件客户端的功能和责任,所以移入邮件客户端,但是只能被基础客户端调用 + * 子类只能通过batchSend来发送邮件 + */ + public void sendEmail(String toAddress, String fromAddress, String subject, + String message, String smtpHost, boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.print(buffer.toString()); + } +} diff --git a/students/75939388/ood/src/main/java/srp/refactor/services/ProductService.java b/students/75939388/ood/src/main/java/srp/refactor/services/ProductService.java new file mode 100644 index 0000000000..a1484520d1 --- /dev/null +++ b/students/75939388/ood/src/main/java/srp/refactor/services/ProductService.java @@ -0,0 +1,38 @@ +package srp.refactor.services; + +import org.apache.commons.lang3.StringUtils; +import srp.refactor.domain.Product; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by Tee on 2017/6/16. + */ +public class ProductService { + + public Product setPromotionInfo(String productId, String productDesc){ + return new Product(productId, productDesc); + } + + public String getLoadQuerySql(String productID){ + if(StringUtils.isBlank(productID)){ + throw new RuntimeException("没有获取到productID"); + } + + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + System.out.println("loadQuery set, productID -> " + productID); + return sendMailQuery; + } + + public List getPromotionInfoList(List data){ + List list = new ArrayList<>(); + for(int i = 0; i < data.size(); i += 2){ + list.add(setPromotionInfo(data.get(i), data.get(i + 1))); + } + return list; + } +} diff --git a/students/75939388/ood/src/main/java/srp/refactor/services/UserService.java b/students/75939388/ood/src/main/java/srp/refactor/services/UserService.java new file mode 100644 index 0000000000..403c9d8a95 --- /dev/null +++ b/students/75939388/ood/src/main/java/srp/refactor/services/UserService.java @@ -0,0 +1,31 @@ +package srp.refactor.services; + +import srp.refactor.domain.User; +import srp.refactor.util.DBUtil; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * Created by Tee on 2017/6/16. + */ +public class UserService { + + public User setUser(String userName, String email){ + return new User(userName, email); + } + + public List getUserList(String sql){ + List userMapList = DBUtil.query(sql); + List userList = new ArrayList<>(); + for(HashMap map : userMapList){ + userList.add(setUser( + (String)map.get("NAME"), + (String)map.get("EMAIL")) + ); + } + + return userList; + } +} diff --git a/students/75939388/ood/src/main/java/srp/refactor/util/Constants.java b/students/75939388/ood/src/main/java/srp/refactor/util/Constants.java new file mode 100644 index 0000000000..88633b1faf --- /dev/null +++ b/students/75939388/ood/src/main/java/srp/refactor/util/Constants.java @@ -0,0 +1,21 @@ +package srp.refactor.util; + +/** + * Created by Tee on 2017/6/16. + */ +public class Constants { + public enum EmailInfo{ + TO_ADDRESS_KEY("toAddress"), + SUBJECT_KEY("subject"), + MESSAGE_KEY("message"); + + private String key; + EmailInfo(String key){ + this.key = key; + } + + public String getKey(){ + return this.key; + } + } +} diff --git a/students/75939388/ood/src/main/java/srp/refactor/util/DBUtil.java b/students/75939388/ood/src/main/java/srp/refactor/util/DBUtil.java new file mode 100644 index 0000000000..00aa263606 --- /dev/null +++ b/students/75939388/ood/src/main/java/srp/refactor/util/DBUtil.java @@ -0,0 +1,25 @@ +package srp.refactor.util; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/75939388/ood/src/main/java/srp/refactor/util/FileUtil.java b/students/75939388/ood/src/main/java/srp/refactor/util/FileUtil.java new file mode 100644 index 0000000000..a1fbdca905 --- /dev/null +++ b/students/75939388/ood/src/main/java/srp/refactor/util/FileUtil.java @@ -0,0 +1,39 @@ +package srp.refactor.util; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Created by Tee on 2017/6/15. + */ +public class FileUtil { + + public static List readFile(File file)throws IOException { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String tmp = null; + List data = new ArrayList<>(); + while((tmp = br.readLine()) != null){ + String[] temp = tmp.split(" "); + data.add(temp[0]); + data.add(temp[1]); + } + + return data; + } catch (IOException e) { + throw new IOException(e); + } finally { + try{ + br.close(); + }catch(Exception e){ + e.printStackTrace(); + } + + } + } +} diff --git a/students/75939388/ood/src/main/resources/ood_demo_file/product_promotion.txt b/students/75939388/ood/src/main/resources/ood_demo_file/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/75939388/ood/src/main/resources/ood_demo_file/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/75939388/ood/src/test/java/srp/SrpTest.java b/students/75939388/ood/src/test/java/srp/SrpTest.java new file mode 100644 index 0000000000..c55f54b1d0 --- /dev/null +++ b/students/75939388/ood/src/test/java/srp/SrpTest.java @@ -0,0 +1,41 @@ +package srp; + +import org.junit.Before; +import org.junit.Test; +import srp.refactor.PromotionMailClient; +import srp.refactor.domain.Product; +import srp.refactor.services.ProductService; +import srp.refactor.util.FileUtil; + +import java.io.File; +import java.util.List; + +/** + * Created by Tee on 2017/6/15. + */ +public class SrpTest { + + PromotionMailClient promotionMail = null; + + private static int in = 0; + + @Before + public void init(){ + + } + + /** + * 重构后的代码尝试运行 + */ + @Test + public void runTrial() throws Exception{ + File file = new File("/Users/Tee/Code/learning2017/season2/coding2017/" + + "students/75939388/ood/src/main/resources/ood_demo_file/product_promotion.txt"); + List data = FileUtil.readFile(file); + + PromotionMailClient promotionMail = new PromotionMailClient(); + List promotionProducts = new ProductService().getPromotionInfoList(data); + promotionMail.batchWrite(promotionProducts); + promotionMail.batchSend(false); + } +} diff --git a/students/75939388/pom.xml b/students/75939388/pom.xml new file mode 100644 index 0000000000..e5dd20227d --- /dev/null +++ b/students/75939388/pom.xml @@ -0,0 +1,104 @@ + + + 4.0.0 + + learning2017 + season2 + 2.0-SEASON2 + + + + datastrure + + ood + + + https://github.com/macvis/coding2017 + + 2017编程能力提高,第二季。 + teacher:刘欣 + gitHub: https://github.com/onlyliuxin/coding2017.git + student: TerrenceWen + + + + + TerrenceWen + https://github.com/macvis/ + macvis@126.com + + + + + 1.8 + 1.8 + UTF-8 + UTF-8 + 1.8 + 1.8 + UTF-8 + + + + + + aliyun + aliyun + http://maven.aliyun.com/nexus/content/groups/public + + true + never + + + false + + + + + + + + junit + junit + 4.12 + + + + + dom4j + dom4j + 1.6.1 + + + + + jaxen + jaxen + 1.1.6 + + + + + commons-io + commons-io + 2.5 + + + org.apache.commons + commons-lang3 + 3.5 + + + commons-codec + commons-codec + 1.10 + + + org.apache.commons + commons-collections4 + 4.1 + + + \ No newline at end of file diff --git a/students/759412759/ood-assignment/pom.xml b/students/759412759/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/759412759/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/759412759/ood-assignment/src/main/java/com/coderising/ood/ocp/DateFormater.java b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/ocp/DateFormater.java new file mode 100644 index 0000000000..18b61a77b3 --- /dev/null +++ b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/ocp/DateFormater.java @@ -0,0 +1,14 @@ +package com.coderising.ood.ocp; + +/** + * 日期类型格式化模板 + * Created by Tudou on 2017/6/19. + */ +public class DateFormater extends Formater { + + @Override + public String formatMessage(String message) { + String txtDate = DateUtil.getCurrentDateAsString(); + return txtDate + " : " + message; + } +} diff --git a/students/759412759/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java new file mode 100644 index 0000000000..b6cf28c096 --- /dev/null +++ b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/ocp/DateUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return null; + } + +} diff --git a/students/759412759/ood-assignment/src/main/java/com/coderising/ood/ocp/Formater.java b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/ocp/Formater.java new file mode 100644 index 0000000000..7a94fea749 --- /dev/null +++ b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/ocp/Formater.java @@ -0,0 +1,12 @@ +package com.coderising.ood.ocp; + +/** + * 格式化打印参数基类 + * Created by Tudou on 2017/6/19. + */ +public class Formater { + + public String formatMessage(String message){ + return message; + } +} diff --git a/students/759412759/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java new file mode 100644 index 0000000000..a9f62d6a66 --- /dev/null +++ b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/ocp/Logger.java @@ -0,0 +1,20 @@ +package com.coderising.ood.ocp; + +public class Logger { + + private Printer printer; + private Formater formater; + + + public Logger(Printer printer, Formater formater) { + this.printer = printer; + this.formater = formater; + } + + + public void log(String msg) { + String logMsg = formater.formatMessage(msg); + printer.print(logMsg); + } +} + diff --git a/students/759412759/ood-assignment/src/main/java/com/coderising/ood/ocp/MailPrintUtil.java b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/ocp/MailPrintUtil.java new file mode 100644 index 0000000000..d522e5e7d2 --- /dev/null +++ b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/ocp/MailPrintUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + + +public class MailPrintUtil extends Printer { + + @Override + public void print(String msg) { + + } +} diff --git a/students/759412759/ood-assignment/src/main/java/com/coderising/ood/ocp/Printer.java b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/ocp/Printer.java new file mode 100644 index 0000000000..caa28fbf0c --- /dev/null +++ b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/ocp/Printer.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp; + +/** + * Created by Tudou on 2017/6/19. + */ +public class Printer { + + public void print(String msg){ + System.out.println(msg); + } +} diff --git a/students/759412759/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSPrintUtil.java b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSPrintUtil.java new file mode 100644 index 0000000000..204256f44b --- /dev/null +++ b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/ocp/SMSPrintUtil.java @@ -0,0 +1,9 @@ +package com.coderising.ood.ocp; + +public class SMSPrintUtil extends Printer { + + @Override + public void print(String msg) { + + } +} diff --git a/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..7616041c05 --- /dev/null +++ b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,24 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap(); + + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public static String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..0bef2d57c9 --- /dev/null +++ b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List> query(String sql){ + List> userList = new ArrayList>(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + return userList; + } + + +} diff --git a/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java new file mode 100644 index 0000000000..49f0db842d --- /dev/null +++ b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/Mail.java @@ -0,0 +1,81 @@ +package com.coderising.ood.srp; + + +public class Mail { + + private String smtpHost; + private String altSmtpHost; + private String fromAddress; + + private String toAddress; + private String subject; + private String message; + private boolean debug; + + + public Mail() { + + } + + public void init() { + smtpHost = Configuration.getProperty(ConfigurationKeys.SMTP_SERVER); + altSmtpHost = Configuration.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + fromAddress = Configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + public String getSmtpHost() { + return smtpHost; + } + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public boolean getDebug() { + return debug; + } + + public void setDebug(boolean debug) { + this.debug = debug; + } +} diff --git a/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..2820127c4b --- /dev/null +++ b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,22 @@ +package com.coderising.ood.srp; + + +public class MailUtil { + + public static boolean sendEmail(Mail mail) { + //假装发了一封邮件 + if(mail.getToAddress().length() < 0){ + return Boolean.FALSE; + } + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(mail.getFromAddress()).append("\n"); + buffer.append("To:").append(mail.getToAddress()).append("\n"); + buffer.append("Subject:").append(mail.getSmtpHost()).append("\n"); + buffer.append("Content:").append(mail.getMessage()).append("\n"); + buffer.append("smtpHost:").append(mail.getSmtpHost()).append("\n"); + buffer.append("isDebug:").append(mail.getDebug() ? "1" : "0").append("\n"); + System.out.println(buffer.toString()); + return Boolean.TRUE; + } + +} diff --git a/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..860f584faf --- /dev/null +++ b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,31 @@ +package com.coderising.ood.srp; + +/** + * Created by Tudou on 2017/6/16. + */ +public class Product { + + private String productID; + private String productDesc; + + + public Product() { + + } + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git a/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/ProductService.java b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/ProductService.java new file mode 100644 index 0000000000..18674e0101 --- /dev/null +++ b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/ProductService.java @@ -0,0 +1,32 @@ +package com.coderising.ood.srp; + +import java.io.*; + +/** + * Created by Tudou on 2017/6/16. + */ +public class ProductService { + + public static Product loadProductFromFile(String filePath) throws IOException { + Product product = new Product(); + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(new File(filePath))); + String temp = br.readLine(); + String[] data = temp.split(" "); + + product.setProductID(data[0]); + product.setProductDesc(data[1]); + + System.out.println("产品ID = " + product.getProductID() + "\n"); + System.out.println("产品描述 = " + product.getProductDesc() + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + return product; + } + +} diff --git a/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..015b68ff10 --- /dev/null +++ b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,63 @@ +package com.coderising.ood.srp; + +import java.io.*; +import java.util.*; + +public class PromotionMail { + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + UserService userService = new UserService(); + PromotionMail pe = new PromotionMail(); + + String path = "F:\\IDEA_PRO_01\\coderrising\\ood-assignment\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"; + Product product = ProductService.loadProductFromFile(path); + List> list = userService.loadMailingList(product.getProductID()); + + pe.sendEMails(list,product,Boolean.FALSE); + } + + private void sendEMails(List> mailingList, Product product, boolean debug) throws IOException { + System.out.println("开始发送邮件"); + if (mailingList != null) { + Iterator> iter = mailingList.iterator(); + while (iter.hasNext()) { + HashMap userInfo = iter.next(); + Mail mail = getMail(product, debug, userInfo); + try { + boolean flag = MailUtil.sendEmail(mail); + if (!flag) { + mail.setSmtpHost(mail.getAltSmtpHost()); + MailUtil.sendEmail(mail); + } + } catch (Exception e) { + try { + mail.setSmtpHost(mail.getAltSmtpHost()); + MailUtil.sendEmail(mail); + } catch (Exception e2) { + System.out.println("通过备用 SMTP 服务器发送邮件失败: " + e2.getMessage()); + } + } + } + } else { + System.out.println("没有邮件发送"); + } + } + + private Mail getMail(Product product, boolean debug, HashMap userInfo) { + Mail mail = new Mail(); + String subject = "您关注的产品降价了"; + String message = "尊敬的 " + userInfo.get(NAME_KEY) + ", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!"; + + mail.init(); + mail.setToAddress(userInfo.get(EMAIL_KEY)); + mail.setSubject(subject); + mail.setMessage(message); + mail.setDebug(debug); + return mail; + } +} diff --git a/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/UserService.java b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/UserService.java new file mode 100644 index 0000000000..80dc46eda8 --- /dev/null +++ b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/UserService.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +import java.util.HashMap; +import java.util.List; + +/** + * Created by Tudou on 2017/6/16. + */ +public class UserService { + + public List> loadMailingList(String productId) throws Exception { + String sql = "Select name from subscriptions " + + "where product_id= '" + productId + "' " + + "and send_mail=1 "; + return DBUtil.query(sql); + } + +} diff --git a/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..46c64c6e64 --- /dev/null +++ b/students/759412759/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1 @@ +P8756 iPhone8 \ No newline at end of file diff --git a/students/765324639/ood/ood-assignment/pom.xml b/students/765324639/ood/ood-assignment/pom.xml new file mode 100644 index 0000000000..cb72faa5f8 --- /dev/null +++ b/students/765324639/ood/ood-assignment/pom.xml @@ -0,0 +1,45 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..60c50b34f0 --- /dev/null +++ b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList<>(); + for (int i = 1; i <= 3; i++) { + UserInfo userInfo = new UserInfo(); + userInfo.setUsername("User" + i); + userInfo.setEmail("aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailInfo.java b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailInfo.java new file mode 100644 index 0000000000..dcb42dcc95 --- /dev/null +++ b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailInfo.java @@ -0,0 +1,40 @@ +package com.coderising.ood.srp; + +public class MailInfo { + private String fromAddress; + private String toAddress; + private String subject; + private String message; + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..614de5a438 --- /dev/null +++ b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,44 @@ +package com.coderising.ood.srp; + +import java.util.List; + +public class MailUtil { + + public static void sendEmail(List mailInfoList, boolean debug) { + if (mailInfoList == null && mailInfoList.size() == 0) { + System.out.println("无邮件发送"); + return; + } + System.out.println("开始发送邮件"); + for (MailInfo mailInfo : mailInfoList) { + sendEmail(mailInfo, debug); + } + } + + public static void sendEmail(MailInfo mailInfo, boolean debug) { + Configuration configuration = new Configuration(); + String smtpServer = configuration.getProperty(ConfigurationKeys.SMTP_SERVER); + String altSmtpServer = configuration.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + String emailAdmin = configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN); + try { + send(mailInfo.getToAddress(), emailAdmin, mailInfo.getSubject(), mailInfo.getMessage(), smtpServer, debug); + } catch (Exception e) { + try { + send(mailInfo.getToAddress(), emailAdmin, mailInfo.getSubject(), mailInfo.getMessage(), altSmtpServer, debug); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + public static void send(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + } +} diff --git a/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..8887870547 --- /dev/null +++ b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,30 @@ +package com.coderising.ood.srp; + +public class Product { + private String id; + private String desc; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + @Override + public String toString() { + return "Product{" + + "id='" + id + '\'' + + ", desc='" + desc + '\'' + + '}'; + } +} diff --git a/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ProductInfoReader.java b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ProductInfoReader.java new file mode 100644 index 0000000000..3e1660608d --- /dev/null +++ b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ProductInfoReader.java @@ -0,0 +1,36 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ProductInfoReader { + + protected static List readProductInfo() { + File file = new File("E:\\coding2017\\students\\765324639\\ood\\ood-assignment\\src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"); + List productList = new ArrayList<>(); + try (BufferedReader br = new BufferedReader(new FileReader(file));) { + String temp = null; + while ((temp = br.readLine()) != null) { + String[] data = temp.split(" "); + Product product = new Product(); + product.setId(data[0]); + product.setDesc(data[1]); + productList.add(product); + System.out.println("产品ID = " + data[0]); + System.out.println("产品描述 = " + data[1] + "\n"); + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return productList; + } +} diff --git a/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..b47f451636 --- /dev/null +++ b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,40 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +public class PromotionMail { + + public static void main(String[] args) throws Exception { + + List productList = ProductInfoReader.readProductInfo(); + + for (Product product : productList) { + List userInfoList = UserInfoReader.readUserInfo(product.getId()); + List mailInfoList = generateEmails(product, userInfoList); + boolean emailDebug = false; + MailUtil.sendEmail(mailInfoList, emailDebug); + } + + } + + public static List generateEmails(Product product, List userInfoList) { + List mailInfoList = new ArrayList<>(); + for (UserInfo userInfo : userInfoList) { + MailInfo mailInfo = new MailInfo(); + mailInfo.setToAddress(userInfo.getEmail()); + mailInfo.setSubject("您关注的产品降价了"); + mailInfo.setMessage("尊敬的 "+ userInfo.getUsername() +", 您关注的产品 " + product.getDesc() + " 降价了,欢迎购买!"); + mailInfoList.add(mailInfo); + } + return mailInfoList; + } +} diff --git a/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/UserInfo.java b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/UserInfo.java new file mode 100644 index 0000000000..c4f501a3ff --- /dev/null +++ b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/UserInfo.java @@ -0,0 +1,30 @@ +package com.coderising.ood.srp; + +public class UserInfo { + private String username; + private String email; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public String toString() { + return "UserInfo{" + + "username='" + username + '\'' + + ", email='" + email + '\'' + + '}'; + } +} diff --git a/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/UserInfoReader.java b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/UserInfoReader.java new file mode 100644 index 0000000000..edfe66d829 --- /dev/null +++ b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/UserInfoReader.java @@ -0,0 +1,14 @@ +package com.coderising.ood.srp; + +import java.util.List; + +public class UserInfoReader { + + public static List readUserInfo(String productID) { + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + System.out.println("loadQuery set"); + return DBUtil.query(sendMailQuery); + } +} diff --git a/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/765324639/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/769232552/season_two/pom.xml b/students/769232552/season_two/pom.xml new file mode 100644 index 0000000000..e71b8c044d --- /dev/null +++ b/students/769232552/season_two/pom.xml @@ -0,0 +1,31 @@ + + + 4.0.0 + + com + season_two + 1.0-SNAPSHOT + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + + \ No newline at end of file diff --git a/students/769232552/season_two/src/main/java/work01/srp/DBUtil.java b/students/769232552/season_two/src/main/java/work01/srp/DBUtil.java new file mode 100644 index 0000000000..89801f6621 --- /dev/null +++ b/students/769232552/season_two/src/main/java/work01/srp/DBUtil.java @@ -0,0 +1,25 @@ +package work01.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/769232552/season_two/src/main/java/work01/srp/Mail.java b/students/769232552/season_two/src/main/java/work01/srp/Mail.java new file mode 100644 index 0000000000..79ddb9c94a --- /dev/null +++ b/students/769232552/season_two/src/main/java/work01/srp/Mail.java @@ -0,0 +1,73 @@ +package work01.srp; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; + +public class Mail { + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + private Product product; + private String toAddress; + private String subject; + private String message; + private String sendMailQuery; + + + public Mail(Product product){ + this.product = product; + } + + public List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + public void generateMail(HashMap userInfo) throws IOException { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0){ + setMessage(userInfo); + setLoadQuery(); + setToAddress(toAddress); + } + } + + public String getMessage() { + return message; + } + + public void setMessage(HashMap userInfo) throws IOException { + String name = (String) userInfo.get(NAME_KEY); + this.message = "尊敬的 "+name+", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!" ; + this.subject = "您关注的产品降价了"; + } + + public String getSubject() { + return subject; + } + + public void setLoadQuery() { + this.sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + product.getProductID() +"' " + + "and send_mail=1 "; + } + + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getToAddress() { + return toAddress; + } + + public Product getProduct() { + return product; + } + + public void setProduct(Product product) { + this.product = product; + } +} diff --git a/students/769232552/season_two/src/main/java/work01/srp/MailBox.java b/students/769232552/season_two/src/main/java/work01/srp/MailBox.java new file mode 100644 index 0000000000..a7fccfaae9 --- /dev/null +++ b/students/769232552/season_two/src/main/java/work01/srp/MailBox.java @@ -0,0 +1,43 @@ +package work01.srp; + +public class MailBox { + + private String smtpHost = null; + private String altSmtpHost = null; + private String fromAddress = null; + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getSmtpHost() { + return smtpHost; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public String getFromAddress() { + return fromAddress; + } + + public void sendEmail(Mail mail, String smtpHost, boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(mail.getToAddress()).append("\n"); + buffer.append("Subject:").append(mail.getSubject()).append("\n"); + buffer.append("Content:").append(mail.getMessage()).append("\n"); + buffer.append("SMTPHost:").append(smtpHost).append("\n"); + System.out.println(buffer.toString()); + } +} diff --git a/students/769232552/season_two/src/main/java/work01/srp/MailBoxConfiguration.java b/students/769232552/season_two/src/main/java/work01/srp/MailBoxConfiguration.java new file mode 100644 index 0000000000..024119cd18 --- /dev/null +++ b/students/769232552/season_two/src/main/java/work01/srp/MailBoxConfiguration.java @@ -0,0 +1,62 @@ +package work01.srp; +import java.util.HashMap; +import java.util.Map; + +public class MailBoxConfiguration { + + static Map configurations = new HashMap(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + + } + + private MailBox mailBox; + + public MailBoxConfiguration(){} + + public void config(){ + setSMTPHost(); + setAltSMTPHost(); + setFromAddress(); + } + + public void setMailBox(MailBox mailBox) { + this.mailBox = mailBox; + } + + private void setSMTPHost() { + this.mailBox.setSmtpHost(getProperty(ConfigurationKeys.SMTP_SERVER)); + } + + + private void setAltSMTPHost() { + this.mailBox.setAltSmtpHost(getProperty(ConfigurationKeys.ALT_SMTP_SERVER)); + } + + + private void setFromAddress() { + this.mailBox.setFromAddress(getProperty(ConfigurationKeys.EMAIL_ADMIN)); + } + + + + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + private String getProperty(String key) { + + return configurations.get(key); + } + + public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + + } +} diff --git a/students/769232552/season_two/src/main/java/work01/srp/Product.java b/students/769232552/season_two/src/main/java/work01/srp/Product.java new file mode 100644 index 0000000000..2eff922d22 --- /dev/null +++ b/students/769232552/season_two/src/main/java/work01/srp/Product.java @@ -0,0 +1,28 @@ +package work01.srp; + + +public class Product { + + protected String productID = null; + + + protected String productDesc = null; + + + public void setProductID(String productID) { + this.productID = productID; + } + + public void setProductDesc(String desc) { + this.productDesc = desc; + } + + + public String getProductDesc() { + return productDesc; + } + + public String getProductID() { + return productID; + } +} diff --git a/students/769232552/season_two/src/main/java/work01/srp/PromotionMail.java b/students/769232552/season_two/src/main/java/work01/srp/PromotionMail.java new file mode 100644 index 0000000000..52222aea0d --- /dev/null +++ b/students/769232552/season_two/src/main/java/work01/srp/PromotionMail.java @@ -0,0 +1,92 @@ +package work01.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + public static void main(String[] args) throws Exception { + + File f = new File("D:\\worksapce\\gitRepo\\coding2017\\students\\769232552\\season_two\\src\\main\\resources\\work01\\srp\\product_promotion.txt"); + boolean emailDebug = false; + + //配置邮箱 + MailBox mailBox = new MailBox(); + MailBoxConfiguration mailBoxConfiguration = new MailBoxConfiguration(); + mailBoxConfiguration.setMailBox(mailBox); + mailBoxConfiguration.config(); + + //将促销信息发送邮件 + List products = readProductFile(f);//获取促销产品信息 + for (Product product : products){ + Mail mail = new Mail(product); //生成邮件(邮件内容,收发人信息) + sendPromotionMails(emailDebug,mail,mailBox); + } + + } + + + + public static void sendPromotionMails(boolean debug, Mail mail, MailBox mailBox) throws Exception { + + System.out.println("开始发送邮件"); + + List mailingList = mail.loadMailingList(); //获取收件人列表 + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + mail.generateMail((HashMap) iter.next()); //生成邮件内容 + try { + if (mail.getToAddress().length() > 0) + mailBox.sendEmail(mail, mailBox.getSmtpHost(), debug); + } catch (Exception e) { + try { + mailBox.sendEmail(mail, mailBox.getAltSmtpHost(), debug); + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + } else { + System.out.println("没有邮件发送"); + + } + } + + + public static List readProductFile(File file) throws IOException + { + List list = new ArrayList(); + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp; + while ((temp = br.readLine()) != null){ + String[] data = temp.split(" "); + + Product product = new Product(); + product.setProductID(data[0]); + product.setProductDesc(data[1]); + list.add(product); + + System.out.println("产品ID = " + product.getProductID() + "\n"); + System.out.println("产品描述 = " + product.getProductDesc() + "\n"); + } + + return list; + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + +} diff --git a/students/769232552/season_two/src/main/java/work02/ocp/DateUtil.java b/students/769232552/season_two/src/main/java/work02/ocp/DateUtil.java new file mode 100644 index 0000000000..ab721d91aa --- /dev/null +++ b/students/769232552/season_two/src/main/java/work02/ocp/DateUtil.java @@ -0,0 +1,10 @@ +package work02.ocp; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return null; + } + +} diff --git a/students/769232552/season_two/src/main/java/work02/ocp/Formatter.java b/students/769232552/season_two/src/main/java/work02/ocp/Formatter.java new file mode 100644 index 0000000000..ce705806b5 --- /dev/null +++ b/students/769232552/season_two/src/main/java/work02/ocp/Formatter.java @@ -0,0 +1,7 @@ +package work02.ocp; + +public interface Formatter { + + String formatMsg(String msg); + +} diff --git a/students/769232552/season_two/src/main/java/work02/ocp/Logger.java b/students/769232552/season_two/src/main/java/work02/ocp/Logger.java new file mode 100644 index 0000000000..0f0ecd7ae0 --- /dev/null +++ b/students/769232552/season_two/src/main/java/work02/ocp/Logger.java @@ -0,0 +1,29 @@ +package work02.ocp; + +public class Logger { + + public final int RAW_LOG = 1; + public final int RAW_LOG_WITH_DATE = 2; + public final int EMAIL_LOG = 1; + public final int SMS_LOG = 2; + public final int PRINT_LOG = 3; + + int type = 0; + int method = 0; + + public Logger(int logType, int logMethod){ + this.type = logType; + this.method = logMethod; + } + + Sender sender; + Formatter formatter; + + public void log(String msg){ + + String logMsg = formatter.formatMsg(msg); + sender.send(logMsg); + + } +} + diff --git a/students/769232552/season_two/src/main/java/work02/ocp/MailSender.java b/students/769232552/season_two/src/main/java/work02/ocp/MailSender.java new file mode 100644 index 0000000000..1d13f449eb --- /dev/null +++ b/students/769232552/season_two/src/main/java/work02/ocp/MailSender.java @@ -0,0 +1,7 @@ +package work02.ocp; + +public class MailSender implements Sender { + public void send(String msg) { + MailUtil.send(msg); + } +} diff --git a/students/769232552/season_two/src/main/java/work02/ocp/MailUtil.java b/students/769232552/season_two/src/main/java/work02/ocp/MailUtil.java new file mode 100644 index 0000000000..62e26c25be --- /dev/null +++ b/students/769232552/season_two/src/main/java/work02/ocp/MailUtil.java @@ -0,0 +1,10 @@ +package work02.ocp; + +public class MailUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/769232552/season_two/src/main/java/work02/ocp/PrinterSender.java b/students/769232552/season_two/src/main/java/work02/ocp/PrinterSender.java new file mode 100644 index 0000000000..7511b9652f --- /dev/null +++ b/students/769232552/season_two/src/main/java/work02/ocp/PrinterSender.java @@ -0,0 +1,8 @@ +package work02.ocp; + + +public class PrinterSender implements Sender { + public void send(String msg) { + System.out.println(msg); + } +} diff --git a/students/769232552/season_two/src/main/java/work02/ocp/RawDateFormatter.java b/students/769232552/season_two/src/main/java/work02/ocp/RawDateFormatter.java new file mode 100644 index 0000000000..16db075e51 --- /dev/null +++ b/students/769232552/season_two/src/main/java/work02/ocp/RawDateFormatter.java @@ -0,0 +1,9 @@ +package work02.ocp; + +public class RawDateFormatter implements Formatter { + + public String formatMsg(String msg) { + String txtDate = DateUtil.getCurrentDateAsString(); + return txtDate + ": " + msg; + } +} diff --git a/students/769232552/season_two/src/main/java/work02/ocp/RawFormatter.java b/students/769232552/season_two/src/main/java/work02/ocp/RawFormatter.java new file mode 100644 index 0000000000..9ff801b9de --- /dev/null +++ b/students/769232552/season_two/src/main/java/work02/ocp/RawFormatter.java @@ -0,0 +1,8 @@ +package work02.ocp; + +public class RawFormatter implements Formatter { + + public String formatMsg(String msg) { + return msg; + } +} diff --git a/students/769232552/season_two/src/main/java/work02/ocp/SMSSender.java b/students/769232552/season_two/src/main/java/work02/ocp/SMSSender.java new file mode 100644 index 0000000000..9fa42a752f --- /dev/null +++ b/students/769232552/season_two/src/main/java/work02/ocp/SMSSender.java @@ -0,0 +1,8 @@ +package work02.ocp; + + +public class SMSSender implements Sender{ + public void send(String msg) { + SMSUtil.send(msg); + } +} diff --git a/students/769232552/season_two/src/main/java/work02/ocp/SMSUtil.java b/students/769232552/season_two/src/main/java/work02/ocp/SMSUtil.java new file mode 100644 index 0000000000..435e07300a --- /dev/null +++ b/students/769232552/season_two/src/main/java/work02/ocp/SMSUtil.java @@ -0,0 +1,10 @@ +package work02.ocp; + +public class SMSUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/769232552/season_two/src/main/java/work02/ocp/Sender.java b/students/769232552/season_two/src/main/java/work02/ocp/Sender.java new file mode 100644 index 0000000000..746ffdffb5 --- /dev/null +++ b/students/769232552/season_two/src/main/java/work02/ocp/Sender.java @@ -0,0 +1,8 @@ +package work02.ocp; + + +public interface Sender { + + void send(String msg); + +} \ No newline at end of file diff --git a/students/769232552/season_two/src/main/resources/work01/srp/product_promotion.txt b/students/769232552/season_two/src/main/resources/work01/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/769232552/season_two/src/main/resources/work01/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/785396327/first/ood/srp/ConfigParser.java b/students/785396327/first/ood/srp/ConfigParser.java new file mode 100644 index 0000000000..87e00e707e --- /dev/null +++ b/students/785396327/first/ood/srp/ConfigParser.java @@ -0,0 +1,9 @@ +package first.ood.srp; + +/** + * Created by william on 2017/6/14. + */ +public abstract class ConfigParser { + + abstract void parseInfoFromConfig(Email email); +} diff --git a/students/785396327/first/ood/srp/Configuration.java b/students/785396327/first/ood/srp/Configuration.java new file mode 100644 index 0000000000..2d4130423e --- /dev/null +++ b/students/785396327/first/ood/srp/Configuration.java @@ -0,0 +1,28 @@ +package first.ood.srp; + +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap(); + + + static { + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/785396327/first/ood/srp/ConfigurationKeys.java b/students/785396327/first/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..28de2ced0a --- /dev/null +++ b/students/785396327/first/ood/srp/ConfigurationKeys.java @@ -0,0 +1,10 @@ +package first.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + public static final String NAME_KEY = "NAME"; + public static final String EMAIL_KEY = "EMAIL"; +} diff --git a/students/785396327/first/ood/srp/DBParser.java b/students/785396327/first/ood/srp/DBParser.java new file mode 100644 index 0000000000..3e49e6abd7 --- /dev/null +++ b/students/785396327/first/ood/srp/DBParser.java @@ -0,0 +1,24 @@ +package first.ood.srp; + +import java.util.HashMap; +import java.util.List; + +/** + * Created by william on 2017/6/14. + */ +public abstract class DBParser { + protected String sql; + protected Object[] params; + + protected DBParser(String sql, Object[] params) { + this.sql = sql; + this.params = params; + } + + protected List parseInfoFromDB(T email) { + List> data = DBUtil.query(sql, params); + return convertData(email, data); + } + + abstract List convertData(T email, List> data); +} diff --git a/students/785396327/first/ood/srp/DBUtil.java b/students/785396327/first/ood/srp/DBUtil.java new file mode 100644 index 0000000000..473b8b1ca4 --- /dev/null +++ b/students/785396327/first/ood/srp/DBUtil.java @@ -0,0 +1,43 @@ +package first.ood.srp; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * + * @param sql + * @return + */ + public static List> query(String sql, Object[] params) { + formateSQL(sql, params); + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + Map userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } + + private static String formateSQL(String sql, Object[] params) { + if (StringUtils.isEmpty(sql)) + throw new RuntimeException("empty sql"); + String[] sqlFaction = sql.split("\\?"); + if (sqlFaction.length - 1 != params.length) + throw new RuntimeException("wrong number of parameters"); + for (int i = 0; i < params.length; i++) { + sql = sql.replaceFirst("\\?", "'" + params[i].toString() + "'"); + } + + return sql; + } + +} diff --git a/students/785396327/first/ood/srp/Email.java b/students/785396327/first/ood/srp/Email.java new file mode 100644 index 0000000000..ebca19e579 --- /dev/null +++ b/students/785396327/first/ood/srp/Email.java @@ -0,0 +1,46 @@ +package first.ood.srp; + +/** + * Created by william on 2017/6/12. + */ +public class Email { + protected String smtpHost; + protected String altSmtpHost; + protected String fromAddress; + protected String toAddress; + protected String subject; + protected String message; + + protected void setSMTPHost(String smtpHost) { + this.smtpHost = smtpHost; + } + + protected void setAltSMTPHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + + } + + protected void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + protected void setMessage(String message) { + this.message = message; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } +} diff --git a/students/785396327/first/ood/srp/EmailParser.java b/students/785396327/first/ood/srp/EmailParser.java new file mode 100644 index 0000000000..e6f422b52f --- /dev/null +++ b/students/785396327/first/ood/srp/EmailParser.java @@ -0,0 +1,26 @@ +package first.ood.srp; + +import java.util.List; + +/** + * Created by william on 2017/6/12. + */ +public class EmailParser { + private ConfigParser configParser; + private FileParser fileParser; + private DBParser dbParser; + + public EmailParser(ConfigParser configParser,FileParser fileParser,DBParser dbParser) { + this.configParser = configParser; + this.fileParser = fileParser; + this.dbParser = dbParser; + } + + public List parseEmailList() { + PromotionMail promotionMail = new PromotionMail(); + configParser.parseInfoFromConfig(promotionMail); + fileParser.parseInfoFromFile(promotionMail); + return dbParser.parseInfoFromDB(promotionMail); + } + +} diff --git a/students/785396327/first/ood/srp/FileParser.java b/students/785396327/first/ood/srp/FileParser.java new file mode 100644 index 0000000000..1f14c11389 --- /dev/null +++ b/students/785396327/first/ood/srp/FileParser.java @@ -0,0 +1,38 @@ +package first.ood.srp; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +/** + * Created by gongxun on 2017/6/12. + */ +public abstract class FileParser { + protected String[] data; + + protected FileParser(String filePath) { + try { + if (StringUtils.isEmpty(filePath)) + throw new RuntimeException("init file parser must contains a legal file"); + readFile(filePath); + } catch (IOException e) { + throw new RuntimeException("parse file cause errors"); + } + } + + private void readFile(String filePath) throws IOException { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(filePath)); + String temp = br.readLine(); + data = temp.split(" "); + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + protected abstract void parseInfoFromFile(Email email); + +} diff --git a/students/785396327/first/ood/srp/MailSender.java b/students/785396327/first/ood/srp/MailSender.java new file mode 100644 index 0000000000..a2ed82db46 --- /dev/null +++ b/students/785396327/first/ood/srp/MailSender.java @@ -0,0 +1,33 @@ +package first.ood.srp; + +import java.util.Iterator; +import java.util.List; + +/** + * Created by william on 2017/6/12. + */ +public class MailSender { + + private void sendMail(Email mail, boolean isDebug) { + if (!StringUtils.isEmpty(mail.toAddress)) + try { + MailUtil.sendEmail( + mail.toAddress, + mail.fromAddress, + mail.subject, + mail.message, + StringUtils.isEmpty(mail.smtpHost) == true ? mail.smtpHost : mail.altSmtpHost, + isDebug); + } catch (Exception e) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e.getMessage()); + } + } + + public void sendMailList(List mailList, boolean isDebug) { + if (mailList != null) { + for (Iterator iterator = mailList.iterator(); iterator.hasNext(); ) { + sendMail(iterator.next(), isDebug); + } + } + } +} diff --git a/students/785396327/first/ood/srp/MailUtil.java b/students/785396327/first/ood/srp/MailUtil.java new file mode 100644 index 0000000000..2ec9de8c42 --- /dev/null +++ b/students/785396327/first/ood/srp/MailUtil.java @@ -0,0 +1,16 @@ +package first.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } +} diff --git a/students/785396327/first/ood/srp/PromotionFileParser.java b/students/785396327/first/ood/srp/PromotionFileParser.java new file mode 100644 index 0000000000..1d57b8de2e --- /dev/null +++ b/students/785396327/first/ood/srp/PromotionFileParser.java @@ -0,0 +1,27 @@ +package first.ood.srp; + +/** + * Created by william on 2017/6/14. + */ +public class PromotionFileParser extends FileParser { + + + public PromotionFileParser(String filePath) { + super(filePath); + } + + @Override + protected void parseInfoFromFile(Email email) { + PromotionMail promotionMail = (PromotionMail) email; + promotionMail.setProductID(parseProductID()); + promotionMail.setProductDesc(parseProductDesc()); + } + + private String parseProductID() { + return super.data[0]; + } + + private String parseProductDesc() { + return super.data[1]; + } +} diff --git a/students/785396327/first/ood/srp/PromotionMail.java b/students/785396327/first/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..48096fa54a --- /dev/null +++ b/students/785396327/first/ood/srp/PromotionMail.java @@ -0,0 +1,22 @@ +package first.ood.srp; + +public class PromotionMail extends Email { + private String productID; + private String productDesc; + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getproductID() { + return productID; + } + + public void setProductDesc(String desc) { + this.productDesc = desc; + } + + public String getProductDesc() { + return this.productDesc; + } +} diff --git a/students/785396327/first/ood/srp/PromotionMailConfigParser.java b/students/785396327/first/ood/srp/PromotionMailConfigParser.java new file mode 100644 index 0000000000..6fd8feb08c --- /dev/null +++ b/students/785396327/first/ood/srp/PromotionMailConfigParser.java @@ -0,0 +1,15 @@ +package first.ood.srp; + +/** + * Created by william on 2017/6/14. + */ +public class PromotionMailConfigParser extends ConfigParser { + + @Override + void parseInfoFromConfig(Email email) { + Configuration configuration = new Configuration(); + email.setSMTPHost(configuration.getProperty(ConfigurationKeys.SMTP_SERVER)); + email.setFromAddress(configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN)); + email.setAltSMTPHost(configuration.getProperty(ConfigurationKeys.ALT_SMTP_SERVER)); + } +} diff --git a/students/785396327/first/ood/srp/PromotionMailDBParser.java b/students/785396327/first/ood/srp/PromotionMailDBParser.java new file mode 100644 index 0000000000..55e740474f --- /dev/null +++ b/students/785396327/first/ood/srp/PromotionMailDBParser.java @@ -0,0 +1,48 @@ +package first.ood.srp; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * Created by william on 2017/6/14. + */ +public class PromotionMailDBParser extends DBParser { + + protected PromotionMailDBParser(String sql, Object[] params) { + super(sql, params); + } + + /** + * 由于sql参数需要运行时提供所以重写parseInfoFromDB方法 + * @param email + * @return + */ + @Override + protected List parseInfoFromDB(PromotionMail email) { + List> data = DBUtil.query(super.sql, new Object[]{email.getproductID()}); + return convertData(email, data); + } + + @Override + List convertData(PromotionMail email, List> data) { + List mailList = new ArrayList(); + for (HashMap map : data) { + email.setToAddress(parseToAddress(map)); + email.setMessage(parseMessage(map, email)); + email.setSubject("您关注的产品降价了"); + mailList.add(email); + } + return mailList; + } + + private String parseMessage(HashMap map, PromotionMail promotionMail) { + String name = map.get(ConfigurationKeys.NAME_KEY); + String message = "尊敬的 " + name + ", 您关注的产品 " + promotionMail.getProductDesc() + " 降价了,欢迎购买!"; + return message; + } + + private String parseToAddress(HashMap map) { + return map.get(ConfigurationKeys.EMAIL_KEY); + } +} diff --git a/students/785396327/first/ood/srp/SendMailTest.java b/students/785396327/first/ood/srp/SendMailTest.java new file mode 100644 index 0000000000..2b54947c05 --- /dev/null +++ b/students/785396327/first/ood/srp/SendMailTest.java @@ -0,0 +1,24 @@ +package first.ood.srp; + +import java.util.List; + +/** + * Created by william on 2017/6/12. + */ +public class SendMailTest { + + public static void main(String[] args) { + String sql = "Select name from subscriptions where product_id= ? and send_mail=1"; + String filepath = "D:\\workspace\\IDEA\\homework\\coding2017_section2\\coding2017\\students\\785396327\\first\\ood\\srp\\product_promotion.txt"; + boolean isDebug = false; + + ConfigParser configParser = new PromotionMailConfigParser(); + FileParser fileParser = new PromotionFileParser(filepath); + DBParser DBParser = new PromotionMailDBParser(sql, null); + + EmailParser emailParser = new EmailParser(configParser, fileParser, DBParser); + List promotionMails = emailParser.parseEmailList(); + MailSender mailSender = new MailSender(); + mailSender.sendMailList(promotionMails, isDebug); + } +} diff --git a/students/785396327/first/ood/srp/StringUtils.java b/students/785396327/first/ood/srp/StringUtils.java new file mode 100644 index 0000000000..ec0483fa8b --- /dev/null +++ b/students/785396327/first/ood/srp/StringUtils.java @@ -0,0 +1,17 @@ +package first.ood.srp; + +/** + * Created by william on 2017/6/12. + */ +public class StringUtils { + + /** + * 判断字符串是否为空 + * + * @param str + * @return + */ + public static boolean isEmpty(String str) { + return str == null || str.trim().isEmpty(); + } +} diff --git a/students/785396327/first/ood/srp/product_promotion.txt b/students/785396327/first/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/785396327/first/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/799298900/src/com/leipengzj/Configuration.java b/students/799298900/src/com/leipengzj/Configuration.java new file mode 100644 index 0000000000..26665ad1a9 --- /dev/null +++ b/students/799298900/src/com/leipengzj/Configuration.java @@ -0,0 +1,31 @@ +package com.leipengzj; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} + +class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/799298900/src/com/leipengzj/DBUtil.java b/students/799298900/src/com/leipengzj/DBUtil.java new file mode 100644 index 0000000000..ec8ae4aba9 --- /dev/null +++ b/students/799298900/src/com/leipengzj/DBUtil.java @@ -0,0 +1,25 @@ +package com.leipengzj; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/799298900/src/com/leipengzj/MailInfo.java b/students/799298900/src/com/leipengzj/MailInfo.java new file mode 100644 index 0000000000..ecaa0dac9b --- /dev/null +++ b/students/799298900/src/com/leipengzj/MailInfo.java @@ -0,0 +1,92 @@ +package com.leipengzj; + +/** + * Created by pl on 2017/6/19. + */ +public class MailInfo { + + protected String sendMailQuery = null; + + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected String productID = null; + protected String productDesc = null; + + public String getSendMailQuery() { + return sendMailQuery; + } + + public void setSendMailQuery(String sendMailQuery) { + this.sendMailQuery = sendMailQuery; + } + + public String getSmtpHost() { + return smtpHost; + } + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git a/students/799298900/src/com/leipengzj/MailUtil.java b/students/799298900/src/com/leipengzj/MailUtil.java new file mode 100644 index 0000000000..42d4329f96 --- /dev/null +++ b/students/799298900/src/com/leipengzj/MailUtil.java @@ -0,0 +1,18 @@ +package com.leipengzj; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/799298900/src/com/leipengzj/PromotionMail.java b/students/799298900/src/com/leipengzj/PromotionMail.java new file mode 100644 index 0000000000..5d152ac3cb --- /dev/null +++ b/students/799298900/src/com/leipengzj/PromotionMail.java @@ -0,0 +1,139 @@ +package com.leipengzj; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + +// protected String sendMailQuery = null; +// +// +// protected String smtpHost = null; +// protected String altSmtpHost = null; +// protected String fromAddress = null; +// protected String toAddress = null; +// protected String subject = null; +// protected String message = null; +// +// protected String productID = null; +// protected String productDesc = null; + + private static Configuration config; + + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + //发送邮件 + public PromotionMail(File file, boolean mailDebug) throws Exception { + MailInfo mi = new MailInfo(); + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(mi,file); + + + config = new Configuration(); + + mi.setSmtpHost(config.getProperty(ConfigurationKeys.SMTP_SERVER)); + mi.setAltSmtpHost(config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER)); + mi.setFromAddress(config.getProperty(ConfigurationKeys.EMAIL_ADMIN)); + + String sql = "Select name from subscriptions " + + "where product_id= '" + mi.getProductID() +"' " + + "and send_mail=1 "; + //查询出邮件列表 + List query = DBUtil.query(sql); + + sendEMails(mi,mailDebug, query); + + + } + + + //读取产品信息 + protected void readFile(MailInfo mi,File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + mi.setProductID(data[0]); + mi.setProductDesc(data[1]); + + System.out.println("产品ID = " + data[0] + "\n"); + System.out.println("产品描述 = " + data[1] + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + //配置邮件并设置发送的邮件内容 + protected void configureEMail(HashMap userInfo,MailInfo mi) throws IOException + { + String toAddress = (String) userInfo.get(EMAIL_KEY); + String name = (String) userInfo.get(NAME_KEY); + if (toAddress.length() > 0){ + mi.setSubject("您关注的产品降价了"); + mi.setMessage("尊敬的 "+name+", 您关注的产品 " + mi.getProductDesc() + " 降价了,欢迎购买!"); + } + + } + + + protected void sendEMails(MailInfo mi,boolean debug, List mailingList) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next(),mi); + try + { + if (mi.getToAddress().length() > 0) + MailUtil.sendEmail(mi.getToAddress(), mi.getToAddress(), mi.getSubject(), mi.getMessage(), mi.getSmtpHost(), debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(mi.getToAddress(), mi.getToAddress(), mi.getSubject(), mi.getMessage(), mi.getAltSmtpHost(), debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + } + else { + System.out.println("没有邮件发送"); + } + + } +} diff --git a/students/799298900/src/com/leipengzj/myfirstGitFork.java b/students/799298900/src/com/leipengzj/myfirstGitFork.java new file mode 100644 index 0000000000..a87099c226 --- /dev/null +++ b/students/799298900/src/com/leipengzj/myfirstGitFork.java @@ -0,0 +1,10 @@ +package com.leipengzj; + +/** + * Created by tyrion on 2017/6/15. + */ +public class myfirstGitFork { + public static void main(String[] args) { + System.out.println("myfirst git"); + } +} diff --git a/students/799298900/src/com/leipengzj/product_promotion.txt b/students/799298900/src/com/leipengzj/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/799298900/src/com/leipengzj/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/812350401/pom.xml b/students/812350401/pom.xml new file mode 100644 index 0000000000..80ef597876 --- /dev/null +++ b/students/812350401/pom.xml @@ -0,0 +1,60 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + UTF-8 + + + + + + org.apache.commons + commons-lang3 + 3.6 + + + junit + junit + 4.12 + + + + com.google.collections + google-collections + 1.0 + + + commons-codec + commons-codec + 1.6 + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/812350401/src/main/java/com/coderising/mydp/bridge/Circle.java b/students/812350401/src/main/java/com/coderising/mydp/bridge/Circle.java new file mode 100644 index 0000000000..267a5ec13e --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/bridge/Circle.java @@ -0,0 +1,34 @@ +package com.coderising.mydp.bridge; + +/** + * Created by thomas_young on 25/7/2017. + */ +public class Circle implements Shape { + private int x, y, r; + private Drawing drawing; + + @Override + public void draw() { + drawing.drawCircle(x, y, r); + } + + public Circle(int x, int y, int r) { + this.x = x; + this.y = y; + this.r = r; + this.drawing = drawing; + } + + @Override + public void setDrawing(Drawing drawing) { + this.drawing = drawing; + } + + public static void main(String[] args) { + Shape c = new Circle(3,4,0); + c.setDrawing(new DrawGL1()); + c.draw(); + c.setDrawing(new DrawGL2()); + c.draw(); + } +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/bridge/DrawClient.java b/students/812350401/src/main/java/com/coderising/mydp/bridge/DrawClient.java new file mode 100644 index 0000000000..5c8c2cf2c8 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/bridge/DrawClient.java @@ -0,0 +1,26 @@ +package com.coderising.mydp.bridge; + +/** + * Created by thomas_young on 25/7/2017. + */ +public class DrawClient { + public static void main(String[] args) { + Shape r = new Rectangle(1,2,3,4); + Shape c = new Circle(2,3,4); + Drawing d1 = new DrawGL1(); + Drawing d2 = new DrawGL2(); + + r.setDrawing(d1); + r.draw(); + System.out.println(); + r.setDrawing(d2); + r.draw(); + System.out.println(); + + c.setDrawing(d1); + c.draw(); + System.out.println(); + c.setDrawing(d2); + c.draw(); + } +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/bridge/DrawGL1.java b/students/812350401/src/main/java/com/coderising/mydp/bridge/DrawGL1.java new file mode 100644 index 0000000000..a1218aaae5 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/bridge/DrawGL1.java @@ -0,0 +1,24 @@ +package com.coderising.mydp.bridge; + +/** + * Created by thomas_young on 25/7/2017. + */ +public class DrawGL1 implements Drawing { + private GraphicLibrary1 gl1 = new GraphicLibrary1(); + + @Override + public void drawLine(int x1, int y1, int x2, int y2) { + gl1.draw_a_line(x1, y1, x2, y2); + } + + @Override + public void drawCircle(int x, int y, int r) { + gl1.draw_a_circle(x, y, r); + } + + public static void main(String[] args) { + DrawGL1 d1 = new DrawGL1(); + d1.drawCircle(4,5,1); + d1.drawLine(1,2,3,4); + } +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/bridge/DrawGL2.java b/students/812350401/src/main/java/com/coderising/mydp/bridge/DrawGL2.java new file mode 100644 index 0000000000..03faf2a82a --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/bridge/DrawGL2.java @@ -0,0 +1,23 @@ +package com.coderising.mydp.bridge; + +/** + * Created by thomas_young on 25/7/2017. + */ +class DrawGL2 implements Drawing { + private GraphicLibrary2 gl2 = new GraphicLibrary2(); + @Override + public void drawLine(int x1, int y1, int x2, int y2) { + gl2.drawLine(x1, y1, x2, y2); + } + + @Override + public void drawCircle(int x, int y, int r) { + gl2.drawCircle(x, y, r); + } + + public static void main(String[] args) { + DrawGL2 d2 = new DrawGL2(); + d2.drawCircle(4,5,1); + d2.drawLine(1,2,3,4); + } +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/bridge/Drawing.java b/students/812350401/src/main/java/com/coderising/mydp/bridge/Drawing.java new file mode 100644 index 0000000000..2c641784bc --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/bridge/Drawing.java @@ -0,0 +1,9 @@ +package com.coderising.mydp.bridge; + +/** + * Created by thomas_young on 25/7/2017. + */ +public interface Drawing { + void drawLine(int x1, int y1, int x2, int y2); + void drawCircle(int x, int y, int r); +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/bridge/GraphicLibrary1.java b/students/812350401/src/main/java/com/coderising/mydp/bridge/GraphicLibrary1.java new file mode 100644 index 0000000000..7b5bafa6d3 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/bridge/GraphicLibrary1.java @@ -0,0 +1,22 @@ +package com.coderising.mydp.bridge; + +public class GraphicLibrary1 { + public void draw_a_line(int x1,int y1,int x2,int y2){ + System.out.println("Library1_line: " + get_a_line(x1, y1, x2, y2)); + } + + private String get_a_line(int x1,int y1,int x2,int y2) { + return "(" + x1 + ", " + y1 + ")-----"+"(" + x2 + ", " + y2 + ")"; + } + + public void draw_a_circle(int x,int y, int r) { + System.out.println("Library1_circle: " + "(" + x + ", " + y +"), r=" + r); + } + + public static void main(String[] args) { + GraphicLibrary1 library1 = new GraphicLibrary1(); + library1.draw_a_line(1,3,4,5); + library1.draw_a_circle(0,2,4); + } + +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/bridge/GraphicLibrary2.java b/students/812350401/src/main/java/com/coderising/mydp/bridge/GraphicLibrary2.java new file mode 100644 index 0000000000..cac917ffc4 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/bridge/GraphicLibrary2.java @@ -0,0 +1,19 @@ +package com.coderising.mydp.bridge; + +public class GraphicLibrary2 { + public void drawLine(int x1,int x2,int y1,int y2){ + System.out.println("Library2_line: " + getLine(x1, y1, x2, y2)); + } + public void drawCircle(int x,int y, int r){ + System.out.println("Library2_circle: " + "(" + x + ", " + y +"), r=" + r); + } + private String getLine(int x1,int y1,int x2,int y2) { + return "(" + x1 + ", " + y1 + ")-----"+"(" + x2 + ", " + y2 + ")"; + } + + public static void main(String[] args) { + GraphicLibrary2 library2 = new GraphicLibrary2(); + library2.drawLine(1,3,4,5); + library2.drawCircle(0,2,4); + } +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/bridge/Rectangle.java b/students/812350401/src/main/java/com/coderising/mydp/bridge/Rectangle.java new file mode 100644 index 0000000000..9ca3bb9591 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/bridge/Rectangle.java @@ -0,0 +1,37 @@ +package com.coderising.mydp.bridge; + +/** + * Created by thomas_young on 25/7/2017. + */ +public class Rectangle implements Shape { + private Drawing drawing; + private int x1, y1, x2, y2; + + @Override + public void setDrawing(Drawing drawing) { + this.drawing = drawing; + } + + @Override + public void draw() { + drawing.drawLine(x1, y1, x1, y2); + drawing.drawLine(x1, y1, x2, y1); + drawing.drawLine(x1, y2, x2, y2); + drawing.drawLine(x2, y1, x2, y2); + } + + public Rectangle(int x1, int y1, int x2, int y2) { + this.x1 = x1; + this.y1 = y1; + this.x2 = x2; + this.y2 = x2; + } + + public static void main(String[] args) { + Shape r = new Rectangle(1,2,3,4); + r.setDrawing(new DrawGL1()); + r.draw(); + r.setDrawing(new DrawGL2()); + r.draw(); + } +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/bridge/Shape.java b/students/812350401/src/main/java/com/coderising/mydp/bridge/Shape.java new file mode 100644 index 0000000000..4a89d2cbe1 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/bridge/Shape.java @@ -0,0 +1,11 @@ +package com.coderising.mydp.bridge; + +/** + * Created by thomas_young on 25/7/2017. + */ +public interface Shape { + + void setDrawing(Drawing drawing); + + void draw(); +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/builder/TagBuilder.java b/students/812350401/src/main/java/com/coderising/mydp/builder/TagBuilder.java new file mode 100644 index 0000000000..4f6901c459 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/builder/TagBuilder.java @@ -0,0 +1,37 @@ +package com.coderising.mydp.builder; + +public class TagBuilder { + private TagNode rootNode; + private TagNode tagNode; + private TagNode parentTagNode; + public TagBuilder(String rootTagName){ + tagNode = new TagNode(rootTagName); + rootNode = tagNode; + } + + public TagBuilder addChild(String childTagName){ + TagNode newTagNode = new TagNode(childTagName); + tagNode.add(newTagNode); + parentTagNode = tagNode; + tagNode = newTagNode; + return this; + } + public TagBuilder addSibling(String siblingTagName){ + TagNode newTagNode = new TagNode(siblingTagName); + parentTagNode.add(newTagNode); + tagNode = newTagNode; + return this; + + } + public TagBuilder setAttribute(String name, String value){ + tagNode.setAttribute(name, value); + return this; + } + public TagBuilder setText(String value){ + tagNode.setValue(value); + return this; + } + public String toXML(){ + return rootNode.toXML(); + } +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/builder/TagBuilderTest.java b/students/812350401/src/main/java/com/coderising/mydp/builder/TagBuilderTest.java new file mode 100644 index 0000000000..d310d7eb1b --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/builder/TagBuilderTest.java @@ -0,0 +1,45 @@ +package com.coderising.mydp.builder; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class TagBuilderTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testToXML() { + + TagBuilder builder = new TagBuilder("order"); + + String xml = builder.addChild("line-items") + .addChild("line-item").setAttribute("pid", "P3677").setAttribute("qty", "3") + .addSibling("line-item").setAttribute("pid", "P9877").setAttribute("qty", "10") + .addSibling("line-item").setAttribute("pid", "P4455").setAttribute("qty", "12") + .addChild("child-line-item").setAttribute("pid", "P3333").setAttribute("qty", "15") + .toXML(); + + String expected = "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + ""; + + System.out.println(xml); + assertEquals(expected, xml); + } + +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/builder/TagNode.java b/students/812350401/src/main/java/com/coderising/mydp/builder/TagNode.java new file mode 100644 index 0000000000..06b0f1c9de --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/builder/TagNode.java @@ -0,0 +1,83 @@ +package com.coderising.mydp.builder; + +import java.util.ArrayList; +import java.util.List; + +public class TagNode { + private String tagName; + private String tagValue; + private List children = new ArrayList<>(); + private List attributes = new ArrayList<>(); + + public TagNode(String name){ + this.tagName = name; + } + public void add(TagNode child){ + this.children.add(child); + } + public void setAttribute(String name, String value) { + Attribute attr = findAttribute(name); + if(attr != null){ + attr.value = value; + return; + } + + attributes.add(new Attribute(name,value)); + } + private Attribute findAttribute(String name){ + for(Attribute attr : attributes){ + if(attr.name.equals(name)){ + return attr; + } + } + return null; + } + public void setValue(String value) { + this.tagValue = value; + + } + public String getTagName() { + return tagName; + } + public List getChildren() { + return children; + } + + private static class Attribute{ + public Attribute(String name, String value) { + this.name = name; + this.value = value; + } + String name; + String value; + + } + public String toXML(){ + return toXML(this); + } + private String toXML(TagNode node){ + StringBuilder buffer = new StringBuilder(); + buffer.append("<").append(node.tagName); + if(node.attributes.size()> 0){ + for(int i=0;i"); + return buffer.toString(); + } + buffer.append(">"); + for(TagNode childNode : node.children){ + buffer.append(toXML(childNode)); // 递归 + } + buffer.append(""); + + + return buffer.toString(); + } + private String toXML(Attribute attr){ + return attr.name+"=\""+attr.value + "\""; + } +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/builder/tagExample.xml b/students/812350401/src/main/java/com/coderising/mydp/builder/tagExample.xml new file mode 100644 index 0000000000..839e62ddee --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/builder/tagExample.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/mydp/command/Client.java b/students/812350401/src/main/java/com/coderising/mydp/command/Client.java new file mode 100644 index 0000000000..ad8c17699e --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/command/Client.java @@ -0,0 +1,21 @@ +package com.coderising.mydp.command; + +/** + * Created by thomas_young on 11/8/2017. + * 命令模式 + */ +public class Client { + + public static void main(String[] args) { + Cook cook = new Cook(); + Waitor waitor = new Waitor(); + + Command command1 = new OrderPorkCommand(cook); + Command command2 = new OrderSteakCommand(cook); + + waitor.addOrder(command1); + waitor.addOrder(command2); + + waitor.sendOrders(); + } +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/command/Command.java b/students/812350401/src/main/java/com/coderising/mydp/command/Command.java new file mode 100644 index 0000000000..922c774209 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/command/Command.java @@ -0,0 +1,8 @@ +package com.coderising.mydp.command; + +/** + * Created by thomas_young on 11/8/2017. + */ +public interface Command { + void execute(); +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/command/Cook.java b/students/812350401/src/main/java/com/coderising/mydp/command/Cook.java new file mode 100644 index 0000000000..940e17869d --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/command/Cook.java @@ -0,0 +1,23 @@ +package com.coderising.mydp.command; + +/** + * Created by thomas_young on 11/8/2017. + */ +public class Cook { + + public void cookSteak() { + System.out.println("Steak is ok"); + } + + public void cookPork() { + System.out.println("Pork is ok"); + } + + public static void main(String[] args) { + StringBuilder x = new StringBuilder("Hello"); + String r1 = x.append(",world").toString(); + String r2 = x.append(",world").toString(); + System.out.println(r1); + System.out.println(r2); + } +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/command/OrderPorkCommand.java b/students/812350401/src/main/java/com/coderising/mydp/command/OrderPorkCommand.java new file mode 100644 index 0000000000..a887b6f3fa --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/command/OrderPorkCommand.java @@ -0,0 +1,16 @@ +package com.coderising.mydp.command; + +/** + * Created by thomas_young on 11/8/2017. + */ +public class OrderPorkCommand implements Command { + private Cook cook; + + public OrderPorkCommand(Cook cook) { + this.cook = cook; + } + @Override + public void execute() { + cook.cookPork(); + } +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/command/OrderSteakCommand.java b/students/812350401/src/main/java/com/coderising/mydp/command/OrderSteakCommand.java new file mode 100644 index 0000000000..3319d141de --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/command/OrderSteakCommand.java @@ -0,0 +1,16 @@ +package com.coderising.mydp.command; + +/** + * Created by thomas_young on 11/8/2017. + */ +public class OrderSteakCommand implements Command { + private Cook cook; + public OrderSteakCommand(Cook cook) { + this.cook = cook; + } + + @Override + public void execute() { + cook.cookSteak(); + } +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/command/Waitor.java b/students/812350401/src/main/java/com/coderising/mydp/command/Waitor.java new file mode 100644 index 0000000000..5bdf920fcd --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/command/Waitor.java @@ -0,0 +1,20 @@ +package com.coderising.mydp.command; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by thomas_young on 11/8/2017. + */ +public class Waitor { + List commands = new ArrayList<>(); + + public void addOrder(Command command) { + commands.add(command); + } + + public void sendOrders() { + commands.stream().forEach(Command::execute); + } + +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/composite/CompositeTest.java b/students/812350401/src/main/java/com/coderising/mydp/composite/CompositeTest.java new file mode 100644 index 0000000000..1a93f9e60b --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/composite/CompositeTest.java @@ -0,0 +1,26 @@ +package com.coderising.mydp.composite; + +import org.junit.Test; + +/** + * Created by thomas_young on 25/7/2017. + */ +public class CompositeTest { + + @Test + public void testComposite() { + Picture aPicture = new Picture(); + aPicture.add(new Line()); + aPicture.add(new Rectangle()); + + Picture p = new Picture(); + p.add(new Text()); + p.add(new Line()); + p.add(new Square()); + + aPicture.add(p); + aPicture.add(new Picture()); + aPicture.add(new Line()); + aPicture.draw(); + } +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/composite/Line.java b/students/812350401/src/main/java/com/coderising/mydp/composite/Line.java new file mode 100644 index 0000000000..2c469cadc4 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/composite/Line.java @@ -0,0 +1,10 @@ +package com.coderising.mydp.composite; + +public class Line implements Shape { + + @Override + public void draw() { + System.out.println("Line"); + } + +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/composite/Picture.java b/students/812350401/src/main/java/com/coderising/mydp/composite/Picture.java new file mode 100644 index 0000000000..79a434679f --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/composite/Picture.java @@ -0,0 +1,23 @@ +package com.coderising.mydp.composite; + +import java.util.LinkedList; +import java.util.List; + +/** + * Created by thomas_young on 26/7/2017. + */ +public class Picture implements Shape { + private List shapes = new LinkedList<>(); + + @Override + public void draw() { + System.out.println("Picture"); + for (Shape shape: shapes) { + shape.draw(); + } + } + public void add(Shape shape) { + shapes.add(shape); + } + +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/composite/Rectangle.java b/students/812350401/src/main/java/com/coderising/mydp/composite/Rectangle.java new file mode 100644 index 0000000000..f9307eff54 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/composite/Rectangle.java @@ -0,0 +1,10 @@ +package com.coderising.mydp.composite; + +public class Rectangle implements Shape { + + @Override + public void draw() { + System.out.println("Rectangle"); + } + +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/composite/Shape.java b/students/812350401/src/main/java/com/coderising/mydp/composite/Shape.java new file mode 100644 index 0000000000..2ab46ef491 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/composite/Shape.java @@ -0,0 +1,5 @@ +package com.coderising.mydp.composite; + +public interface Shape { + void draw(); +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/composite/Square.java b/students/812350401/src/main/java/com/coderising/mydp/composite/Square.java new file mode 100644 index 0000000000..99ce725ee2 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/composite/Square.java @@ -0,0 +1,10 @@ +package com.coderising.mydp.composite; + +public class Square implements Shape { + + @Override + public void draw() { + System.out.println("Square"); + } + +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/composite/Text.java b/students/812350401/src/main/java/com/coderising/mydp/composite/Text.java new file mode 100644 index 0000000000..0800dd65bc --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/composite/Text.java @@ -0,0 +1,10 @@ +package com.coderising.mydp.composite; + +public class Text implements Shape { + + @Override + public void draw() { + System.out.println("Text"); + } + +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/decorator/Email.java b/students/812350401/src/main/java/com/coderising/mydp/decorator/Email.java new file mode 100644 index 0000000000..d4b4bc12ab --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/decorator/Email.java @@ -0,0 +1,6 @@ +package com.coderising.mydp.decorator; + +public interface Email { + String getContent(); +} + diff --git a/students/812350401/src/main/java/com/coderising/mydp/decorator/EmailDecorator.java b/students/812350401/src/main/java/com/coderising/mydp/decorator/EmailDecorator.java new file mode 100644 index 0000000000..045b344b42 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/decorator/EmailDecorator.java @@ -0,0 +1,6 @@ +package com.coderising.mydp.decorator; + +public abstract class EmailDecorator implements Email{ + + +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/mydp/decorator/EmailEncrypt.java b/students/812350401/src/main/java/com/coderising/mydp/decorator/EmailEncrypt.java new file mode 100644 index 0000000000..b31c09139d --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/decorator/EmailEncrypt.java @@ -0,0 +1,24 @@ +package com.coderising.mydp.decorator; + +import com.coderising.mydp.utils.Encryptor; + +/** + * Created by thomas_young on 25/7/2017. + */ +public class EmailEncrypt extends EmailDecorator { + private Email email; + private String key; + private String initVector; + + public EmailEncrypt(String key, String initVector, Email email) { + this.key = key; + this.initVector = initVector; + this.email = email; + } + + @Override + public String getContent() { + String content = email.getContent(); + return Encryptor.encrypt(key, initVector, content); + } +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/decorator/EmailImpl.java b/students/812350401/src/main/java/com/coderising/mydp/decorator/EmailImpl.java new file mode 100644 index 0000000000..0cedef84a2 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/decorator/EmailImpl.java @@ -0,0 +1,12 @@ +package com.coderising.mydp.decorator; + +public class EmailImpl implements Email { + private String content; + + public EmailImpl(String content) { + this.content = content; + } + public String getContent() { + return content; + } +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/decorator/EmailSendOut.java b/students/812350401/src/main/java/com/coderising/mydp/decorator/EmailSendOut.java new file mode 100644 index 0000000000..a553e7120a --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/decorator/EmailSendOut.java @@ -0,0 +1,19 @@ +package com.coderising.mydp.decorator; + +/** + * Created by thomas_young on 25/7/2017. + */ +public class EmailSendOut extends EmailDecorator { + Email email; + + public EmailSendOut(Email email) { + this.email = email; + } + + @Override + public String getContent() { + String content = email.getContent(); + content += "\n" + "本邮件仅为个人观点,并不代表公司立场."; + return content; + } +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/decorator/EmailTest.java b/students/812350401/src/main/java/com/coderising/mydp/decorator/EmailTest.java new file mode 100644 index 0000000000..48df0f5dd5 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/decorator/EmailTest.java @@ -0,0 +1,42 @@ +package com.coderising.mydp.decorator; + +import com.coderising.mydp.utils.Encryptor; +import org.junit.Test; + +/** + * Created by thomas_young on 25/7/2017. + */ +public class EmailTest { + private Email email = new EmailImpl("Hello World!"); + private String key = "Bar12345Bar12345"; // 128 bit key + private String initVector = "RandomInitVector"; // 16 bytes IV + + @Test + public void testSendToOut() { + Email emailSendOut = new EmailSendOut(email); + System.out.println(emailSendOut.getContent()); + } + + @Test + public void testEncrypt() { + Email emailEncrypt = new EmailEncrypt(key, initVector, email); + String encryptedContent = emailEncrypt.getContent(); + System.out.println("encrypted content: " + encryptedContent); + System.out.println(Encryptor.decrypt(key, initVector, encryptedContent)); + } + + @Test + public void testEncryptSendOut() { + Email emailsendOutEncrypt = new EmailSendOut(new EmailEncrypt(key, initVector, email)); + System.out.println(emailsendOutEncrypt.getContent()); + System.out.println(); + + Email emailEncryptSendOut = new EmailEncrypt(key, initVector, new EmailSendOut(email)); + String encryptedContent = emailEncryptSendOut.getContent(); + System.out.println("encrypted content: " + encryptedContent); + + System.out.println(); + System.out.println(Encryptor.decrypt(key, initVector, encryptedContent)); + + } +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/responseChain/AbstractLogger.java b/students/812350401/src/main/java/com/coderising/mydp/responseChain/AbstractLogger.java new file mode 100644 index 0000000000..778962e2fa --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/responseChain/AbstractLogger.java @@ -0,0 +1,26 @@ +package com.coderising.mydp.responseChain; + +/** + * Created by thomas_young on 11/8/2017. + */ +public abstract class AbstractLogger { + public static final String DEBUG = "DEBUG"; + public static final String NOTICE = "NOTICE"; + public static final String ERR = "ERR"; + + /** + * 持有下一个处理请求的对象 + */ + private AbstractLogger next = null; + + public AbstractLogger getNext() { + return next; + } + + public AbstractLogger setNext(AbstractLogger next) { + this.next = next; + return this; + } + + public abstract void message(String message, String type); +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/responseChain/Client.java b/students/812350401/src/main/java/com/coderising/mydp/responseChain/Client.java new file mode 100644 index 0000000000..30f27b4943 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/responseChain/Client.java @@ -0,0 +1,23 @@ +package com.coderising.mydp.responseChain; + +/** + * Created by thomas_young on 11/8/2017. + */ +public class Client { + + public static void main(String[] args) { + AbstractLogger logger = new StdoutLogger() + .setNext(new EmailLogger() + .setNext(new FileLogger())); + + // 由StdoutLogger处理 + logger.message("进入计算函数", AbstractLogger.DEBUG); + // 由StdoutLogger和EmailLogger处理 + System.out.println("*****************"); + logger.message("第一步已完成", AbstractLogger.NOTICE); + // 由所有logger处理 + System.out.println("*****************"); + logger.message("一个致命的错误发生了", AbstractLogger.ERR); + } + +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/responseChain/EmailLogger.java b/students/812350401/src/main/java/com/coderising/mydp/responseChain/EmailLogger.java new file mode 100644 index 0000000000..54605eba5b --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/responseChain/EmailLogger.java @@ -0,0 +1,15 @@ +package com.coderising.mydp.responseChain; + +/** + * Created by thomas_young on 11/8/2017. + */ +public class EmailLogger extends AbstractLogger { + + @Override + public void message(String message, String type) { + System.out.println("EmailLogger处理:" + message); + if (!AbstractLogger.NOTICE.equals(type)) { + getNext().message(message, type); + } + } +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/responseChain/FileLogger.java b/students/812350401/src/main/java/com/coderising/mydp/responseChain/FileLogger.java new file mode 100644 index 0000000000..2c6d316eea --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/responseChain/FileLogger.java @@ -0,0 +1,11 @@ +package com.coderising.mydp.responseChain; + +/** + * Created by thomas_young on 11/8/2017. + */ +public class FileLogger extends AbstractLogger { + @Override + public void message(String message, String type) { + System.out.println("FileLogger处理:" + message); + } +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/responseChain/StdoutLogger.java b/students/812350401/src/main/java/com/coderising/mydp/responseChain/StdoutLogger.java new file mode 100644 index 0000000000..29ae7a1d19 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/responseChain/StdoutLogger.java @@ -0,0 +1,14 @@ +package com.coderising.mydp.responseChain; + +/** + * Created by thomas_young on 11/8/2017. + */ +public class StdoutLogger extends AbstractLogger { + @Override + public void message(String message, String type) { + System.out.println("StdoutLogger处理:" + message); + if (!AbstractLogger.DEBUG.equals(type)) { + getNext().message(message, type); + } + } +} diff --git a/students/812350401/src/main/java/com/coderising/mydp/utils/Encryptor.java b/students/812350401/src/main/java/com/coderising/mydp/utils/Encryptor.java new file mode 100644 index 0000000000..af177ed678 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/mydp/utils/Encryptor.java @@ -0,0 +1,58 @@ +package com.coderising.mydp.utils; + +/** + * Created by thomas_young on 25/7/2017. + */ +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +import org.apache.commons.codec.binary.Base64; + +public class Encryptor { + public static String encrypt(String key, String initVector, String value) { + try { + IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8")); + SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); + + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); + cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); + + byte[] encrypted = cipher.doFinal(value.getBytes()); + // System.out.println("encrypted string: " + // + Base64.encodeBase64String(encrypted)); + + return Base64.encodeBase64String(encrypted); + } catch (Exception ex) { + ex.printStackTrace(); + } + + return null; + } + + public static String decrypt(String key, String initVector, String encrypted) { + try { + IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8")); + SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); + + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); + cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); + + byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted)); + + return new String(original); + } catch (Exception ex) { + ex.printStackTrace(); + } + + return null; + } + + public static void main(String[] args) { + String key = "Bar12345Bar12345"; // 128 bit key + String initVector = "RandomInitVector"; // 16 bytes IV + + System.out.println(decrypt(key, initVector, + encrypt(key, initVector, "Hello World"))); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myknowledgepoint/cas/CASSequence.java b/students/812350401/src/main/java/com/coderising/myknowledgepoint/cas/CASSequence.java new file mode 100644 index 0000000000..144aa264ff --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myknowledgepoint/cas/CASSequence.java @@ -0,0 +1,18 @@ +package com.coderising.myknowledgepoint.cas; + +import java.util.concurrent.atomic.AtomicInteger; + +public class CASSequence{ + + private AtomicInteger count = new AtomicInteger(0); + + public int next(){ + while(true){ + int current = count.get(); + int next = current +1; + if(count.compareAndSet(current, next)){ + return next; + } + } + } +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myknowledgepoint/cas/NoBlockingStack.java b/students/812350401/src/main/java/com/coderising/myknowledgepoint/cas/NoBlockingStack.java new file mode 100644 index 0000000000..c03c096c78 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myknowledgepoint/cas/NoBlockingStack.java @@ -0,0 +1,34 @@ +package com.coderising.myknowledgepoint.cas; + +import java.util.concurrent.atomic.AtomicReference; + +public class NoBlockingStack { + static class Node { + final E item; + Node next; + public Node(E item) { this.item = item; } + } + + AtomicReference> head = new AtomicReference>(); + + public void push(E item) { + Node newHead = new Node(item); + Node oldHead; + do { + oldHead = head.get(); + newHead.next = oldHead; + } while (!head.compareAndSet(oldHead, newHead)); + } + public E pop() { + Node oldHead; + Node newHead; + do { + oldHead = head.get(); + if (oldHead == null) + return null; + newHead = oldHead.next; + } while (!head.compareAndSet(oldHead,newHead)); + return oldHead.item; + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myknowledgepoint/cas/Sequence.java b/students/812350401/src/main/java/com/coderising/myknowledgepoint/cas/Sequence.java new file mode 100644 index 0000000000..25909d0dd9 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myknowledgepoint/cas/Sequence.java @@ -0,0 +1,11 @@ +package com.coderising.myknowledgepoint.cas; + +public class Sequence{ + + private int value; + + public int next(){ + return value ++; + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myknowledgepoint/closure/Milk.java b/students/812350401/src/main/java/com/coderising/myknowledgepoint/closure/Milk.java new file mode 100644 index 0000000000..326142ccbb --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myknowledgepoint/closure/Milk.java @@ -0,0 +1,49 @@ +package com.coderising.myknowledgepoint.closure; + +/** + * Created by thomas_young on 27/8/2017. + */ +public class Milk { + + public final static String name = "纯牛奶";//名称 + + private static int num = 16;//数量 + + public Milk() + { + System.out.println(name+":16/每箱"); + } + + /** + * 闭包 + * @return 返回一个喝牛奶的动作 + */ + public Active HaveMeals() + { + return () -> { + if(num == 0) + { + System.out.println("木有了,都被你丫喝完了."); + return; + } + num--; + System.out.println("喝掉一瓶牛奶"); + }; + } + + /** + * 获取剩余数量 + */ + public void currentNum() + { + System.out.println(name+"剩余:"+num); + } +} + +/** + * 通用接口 + */ +interface Active +{ + void drink(); +} diff --git a/students/812350401/src/main/java/com/coderising/myknowledgepoint/closure/Person.java b/students/812350401/src/main/java/com/coderising/myknowledgepoint/closure/Person.java new file mode 100644 index 0000000000..de10e875a6 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myknowledgepoint/closure/Person.java @@ -0,0 +1,41 @@ +package com.coderising.myknowledgepoint.closure; + +/** + * Created by thomas_young on 27/8/2017. + */ +public class Person { + + public static void main(String[] args) { + //买一箱牛奶 + Milk m = new Milk(); + + Active haveMeals = m.HaveMeals(); + + //没事喝一瓶 + haveMeals.drink(); + //有事喝一瓶 + haveMeals.drink(); + + //看看还剩多少? + m.currentNum(); + m = null; + haveMeals.drink(); // 闭包会导致资源不被回收 + haveMeals.drink(); + haveMeals.drink(); + haveMeals.drink(); + haveMeals.drink(); + haveMeals.drink(); + haveMeals.drink(); + haveMeals.drink(); + haveMeals.drink(); + haveMeals.drink(); + haveMeals.drink(); + haveMeals.drink(); + haveMeals.drink(); + haveMeals.drink(); + haveMeals.drink(); + haveMeals.drink(); + haveMeals.drink(); + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myknowledgepoint/myResponseChain/Client.java b/students/812350401/src/main/java/com/coderising/myknowledgepoint/myResponseChain/Client.java new file mode 100644 index 0000000000..40aeb59765 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myknowledgepoint/myResponseChain/Client.java @@ -0,0 +1,37 @@ +package com.coderising.myknowledgepoint.myResponseChain; + +/** + * Created by thomas_young on 10/8/2017. + * http://www.cnblogs.com/java-my-life/archive/2012/05/28/2516865.html + */ + +public class Client { + + public static void main(String[] args) { + //先要组装责任链 + Handler h1 = new GeneralManager(); + Handler h2 = new DeptManager(); + Handler h3 = new ProjectManager(); + h3.setSuccessor(h2); + h2.setSuccessor(h1); + + //开始测试 + String test1 = h3.handleFeeRequest("张三", 300); + System.out.println("test1 = " + test1); + String test2 = h3.handleFeeRequest("李四", 300); + System.out.println("test2 = " + test2); + System.out.println("---------------------------------------"); + + String test3 = h3.handleFeeRequest("张三", 700); + System.out.println("test3 = " + test3); + String test4 = h3.handleFeeRequest("李四", 700); + System.out.println("test4 = " + test4); + System.out.println("---------------------------------------"); + + String test5 = h3.handleFeeRequest("张三", 1500); + System.out.println("test5 = " + test5); + String test6 = h3.handleFeeRequest("李四", 1500); + System.out.println("test6 = " + test6); + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myknowledgepoint/myResponseChain/DeptManager.java b/students/812350401/src/main/java/com/coderising/myknowledgepoint/myResponseChain/DeptManager.java new file mode 100644 index 0000000000..d051b7f37a --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myknowledgepoint/myResponseChain/DeptManager.java @@ -0,0 +1,35 @@ +package com.coderising.myknowledgepoint.myResponseChain; + +/** + * Created by thomas_young on 10/8/2017. + */ +public class DeptManager extends Handler { + + @Override + public String handleFeeRequest(String user, double fee) { + + String str = ""; + //部门经理的权限只能在1000以内 + if(fee < 1000) + { + //为了测试,简单点,只同意张三的请求 + if("张三".equals(user)) + { + str = "成功:部门经理同意【" + user + "】的聚餐费用,金额为" + fee + "元"; + }else + { + //其他人一律不同意 + str = "失败:部门经理不同意【" + user + "】的聚餐费用,金额为" + fee + "元"; + } + }else + { + //超过1000,继续传递给级别更高的人处理 + if(getSuccessor() != null) + { + return getSuccessor().handleFeeRequest(user, fee); + } + } + return str; + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myknowledgepoint/myResponseChain/GeneralManager.java b/students/812350401/src/main/java/com/coderising/myknowledgepoint/myResponseChain/GeneralManager.java new file mode 100644 index 0000000000..2d601604c1 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myknowledgepoint/myResponseChain/GeneralManager.java @@ -0,0 +1,34 @@ +package com.coderising.myknowledgepoint.myResponseChain; + +/** + * Created by thomas_young on 10/8/2017. + */ +public class GeneralManager extends Handler { + + @Override + public String handleFeeRequest(String user, double fee) { + + String str = ""; + //总经理的权限很大,只要请求到了这里,他都可以处理 + if(fee >= 1000) + { + //为了测试,简单点,只同意张三的请求 + if("张三".equals(user)) + { + str = "成功:总经理同意【" + user + "】的聚餐费用,金额为" + fee + "元"; + }else + { + //其他人一律不同意 + str = "失败:总经理不同意【" + user + "】的聚餐费用,金额为" + fee + "元"; + } + }else { + //如果还有后继的处理对象,继续传递 + if(getSuccessor() != null) + { + return getSuccessor().handleFeeRequest(user, fee); + } + } + return str; + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myknowledgepoint/myResponseChain/Handler.java b/students/812350401/src/main/java/com/coderising/myknowledgepoint/myResponseChain/Handler.java new file mode 100644 index 0000000000..a032475bd9 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myknowledgepoint/myResponseChain/Handler.java @@ -0,0 +1,30 @@ +package com.coderising.myknowledgepoint.myResponseChain; + +/** + * Created by thomas_young on 10/8/2017. + */ +public abstract class Handler { + /** + * 持有下一个处理请求的对象 + */ + protected Handler successor = null; + /** + * 取值方法 + */ + public Handler getSuccessor() { + return successor; + } + /** + * 设置下一个处理请求的对象 + */ + public void setSuccessor(Handler successor) { + this.successor = successor; + } + /** + * 处理聚餐费用的申请 + * @param user 申请人 + * @param fee 申请的钱数 + * @return 成功或失败的具体通知 + */ + public abstract String handleFeeRequest(String user , double fee); +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myknowledgepoint/myResponseChain/ProjectManager.java b/students/812350401/src/main/java/com/coderising/myknowledgepoint/myResponseChain/ProjectManager.java new file mode 100644 index 0000000000..7fa75aa662 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myknowledgepoint/myResponseChain/ProjectManager.java @@ -0,0 +1,35 @@ +package com.coderising.myknowledgepoint.myResponseChain; + +/** + * Created by thomas_young on 10/8/2017. + */ +public class ProjectManager extends Handler { + + @Override + public String handleFeeRequest(String user, double fee) { + + String str = ""; + //项目经理权限比较小,只能在500以内 + if(fee < 500) + { + //为了测试,简单点,只同意张三的请求 + if("张三".equals(user)) + { + str = "成功:项目经理同意【" + user + "】的聚餐费用,金额为" + fee + "元"; + }else + { + //其他人一律不同意 + str = "失败:项目经理不同意【" + user + "】的聚餐费用,金额为" + fee + "元"; + } + }else + { + //超过500,继续传递给级别更高的人处理 + if(getSuccessor() != null) + { + return getSuccessor().handleFeeRequest(user, fee); + } + } + return str; + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myknowledgepoint/regex/Utils.java b/students/812350401/src/main/java/com/coderising/myknowledgepoint/regex/Utils.java new file mode 100644 index 0000000000..bf2237f452 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myknowledgepoint/regex/Utils.java @@ -0,0 +1,26 @@ +package com.coderising.myknowledgepoint.regex; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +public class Utils { + + public static String readAllFromResouce(String resourceName) { + byte[] fileContentBytes; + try { + Path path = Paths.get(ClassLoader.getSystemResource(resourceName).toURI()); + fileContentBytes = Files.readAllBytes(path); + String fileContentStr = new String(fileContentBytes, StandardCharsets.UTF_8); + + return fileContentStr; + } catch (IOException | URISyntaxException e) { + e.printStackTrace(); + } + + return ""; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myknowledgepoint/regex/UtilsTest.java b/students/812350401/src/main/java/com/coderising/myknowledgepoint/regex/UtilsTest.java new file mode 100644 index 0000000000..6f8a39a806 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myknowledgepoint/regex/UtilsTest.java @@ -0,0 +1,479 @@ +package com.coderising.myknowledgepoint.regex; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.Ignore; +import org.junit.Test; + +// http://www.cnblogs.com/playing/archive/2011/03/15/1984943.html + +public class UtilsTest { + + /** + * 多行模式-1 + */ + @Test + public void test01_01() { + String t1 = Utils.readAllFromResouce("01.txt"); + + // 默认 单行模式 + Pattern p1 = Pattern.compile("^def$"); + Matcher m1 = p1.matcher(t1); + + if (m1.find()) { + System.out.println("found!"); + } else { + System.out.println("not found!"); + } + } + + /** + *

+	 * 多行模式-2 
+	 *  (?m)		Pattern.MULTILINE
+	 * 
+ */ + @Test + public void test01_02() { + String t1 = Utils.readAllFromResouce("01.txt"); + + // 多行模式 写法一 + // Pattern p1 = Pattern.compile("(?m)^def$"); + // 多行模式 写法二 + Pattern p1 = Pattern.compile("^def$", Pattern.MULTILINE); + + Matcher m1 = p1.matcher(t1); + + if (m1.find()) { + System.out.println("found!"); + } else { + System.out.println("not found!"); + } + } + + /** + * flag设定和(?X)的等价关系 + * + *
+	 *  (?m)		Pattern.MULTILINE
+	 *  (?i)		Pattern.CASE_INSENSITIVE
+	 *  (?u)		Pattern.UNICODE_CASE
+	 *  (?s)		Pattern.DOTALL
+	 *  (?d)		Pattern.UNIX_LINES
+	 *  (?x)		Pattern.COMMENTS
+	 * 
+ */ + + /** + *
+	 * ascii大小写
+	 *  (?i)		Pattern.CASE_INSENSITIVE
+	 * 
+ */ + @Test + public void test02_01() { + String t1 = "abc AbC aCd abc ABc 2343"; + String r1 = "abc"; + + // 默认 区分大小写 + // Pattern p1 = Pattern.compile(r1); + + // 忽略ascii大小,写法一 + Pattern p1 = Pattern.compile("(?i)abc"); + + // 忽略ascii大小,写法而 + // Pattern p1 = Pattern.compile(r1, Pattern.CASE_INSENSITIVE ); + + Matcher m1 = p1.matcher(t1); + + while (m1.find()) { + System.out.println(m1.group()); + } + } + + /** + *
+	 * unicode大小写
+	 *  (?u)		Pattern.UNICODE_CASE
+	 * 
+ */ + @Test + public void test03_01() { + String t1 = "abc AbC aCd abc ABc 2343"; + String r1 = "abc";// 日文输入法下,全角abc,也就是宽字体 + + // 默认 区分大小写只适用于ascii + // Pattern p1 = Pattern.compile((?i)abc); + + // 忽略ascii大小,写法一 + Pattern p1 = Pattern.compile("(?iu)abc"); + + // 忽略ascii大小,写法二 + // Pattern p1 = Pattern.compile(r1, Pattern.UNICODE_CASE); + + Matcher m1 = p1.matcher(t1); + + while (m1.find()) { + System.out.println(m1.group()); + } + } + + /** 通过设定标志位忽略大小写 */ + @Test + public void test03_02() { + String t1 = "abc AbC aCd\nABCD 2343"; + String r1 = "(?i)(?m)abc"; + Pattern p1 = Pattern.compile(r1); + Matcher m1 = p1.matcher(t1); + + while (m1.find()) { + System.out.println(m1.group()); + } + } + + @Test + public void test04_01_dotall() { + Pattern p = null; + Matcher m = null; + + String text1 = "width height"; + String text2 = "width\nheight"; + // Pattern p = Pattern.compile("(?s)width.height"); + p = Pattern.compile("width.height", Pattern.DOTALL); // 让.也能匹配换行符 + + m = p.matcher(text1); + boolean result1 = m.find(); + if (result1) { + System.out.println("text1 found"); + } else { + System.out.println("text1 not found"); + } + + m = p.matcher(text2); + boolean result2 = m.find(); + if (result2) { + System.out.println("text2 found"); + } else { + System.out.println("text2 not found"); + } + } + + /** + * group + * + *
+	 * group(0):正则表达式的匹配值 
+	 * group(1):第一个子串
+	 * 
+ */ + @Test + public void test05_01() { + Pattern p = Pattern.compile("([a-z]+)-(\\d+)"); + Matcher m = p.matcher("type x-235, type y-3, type zw-465"); + + while (m.find()) { + for (int i = 0; i < m.groupCount() + 1; i++) { + System.out.println("group(" + i + ")=" + m.group(i)); + } + System.out.println("---------------------"); + } + } + + /** + * 字符串分割的例子 + */ + @Test + public void test05_02() { + String abc = "a///b/c"; + + // 分割后的数组中包含空字符 + String[] array1 = abc.split("/"); // 可以直接写正则 + for (String str : array1) { + System.out.println(str); + } + + System.out.println("---------------------"); + + // 分割后的数组中取出了空字符 + String[] array2 = abc.split("/+"); // 贪婪匹配斜杠"///" + for (String str : array2) { + System.out.println(str); + } + } + + /** + * 替换 + */ + @Test + public void test06_01() { + String str = "Orange is 100yuan, Banana is 180 yuan."; + String regex = "\\d+\\s*yuan"; + Pattern p = Pattern.compile(regex); + + Matcher m = p.matcher(str); + System.out.println(m.find()); + String result = m.replaceFirst("_$0_"); + + System.out.println(result); + } + + /** + * 替换 + */ + @Test + public void test06_02() { + String str = "Orange is 100yuan, Banana is 180 yuan."; + String regex = "(\\d+)\\s*(yuan)"; + + Pattern p = Pattern.compile(regex); + Matcher m = p.matcher(str); + + String result = m.replaceAll("$2_$1"); + + System.out.println(result); + } + + /** + * 命名分组,替换 + */ + @Test + public void test06_03() { + String pathfFilename = "aa/notepad.exe"; + + String regex = "^.+/(?.+)$"; + String replacement = "${filename}"; + + String filename = pathfFilename.replaceFirst(regex, replacement); + System.out.println(filename); + + // 法2 + Pattern p = Pattern.compile(regex); + Matcher m = p.matcher(pathfFilename); + + String result = m.replaceFirst(replacement); + + System.out.println(result); + + } + + /** + * 从文本中读取多行数据后,建议先把回车符删掉 + */ + @Test + public void test07_01() { + String t1 = Utils.readAllFromResouce("07.txt"); + System.out.println("--orignal text start--"); + System.out.print(t1); + System.out.println("--orignal text end --"); + + // 统一换行符 + String ret1 = t1.replaceAll("(\r\n)|\r", "\n"); + System.out.println("--统一换行符 start--"); + System.out.print(ret1); + System.out.println("--统一换行符 end --"); + + // 行单位前后trim + String ret2 = ret1.replaceAll("(?m)^\\s*(.*?)\\s*$", "$1"); + System.out.println("--行单位前后trim start--"); + System.out.println(ret2); + System.out.println("--行单位前后trim end --"); + + assertFalse(ret2.equals(t1)); + } + + @Test + public void test01_04_Zz() { + Pattern p = null; + Matcher m = null; + boolean result1 = false; + boolean result2 = false; + boolean result3 = false; + + String text1 = "abc def"; + String text2 = "def abc"; + String text3 = "def abc\n"; + + p = Pattern.compile("abc\\z"); // \z: asserts position at the end of the string + + m = p.matcher(text1); + result1 = m.find(); + assertFalse(result1); + + m = p.matcher(text2); + result2 = m.find(); + assertTrue(result2); + + m = p.matcher(text3); + result3 = m.find(); + assertFalse(result3); + + p = Pattern.compile("abc\\Z"); // \Z: asserts position at the end of the string, or before the line terminator right at the end of the string (if any) + + m = p.matcher(text1); + result1 = m.find(); + + m = p.matcher(text2); + result2 = m.find(); + + m = p.matcher(text3); + result3 = m.find(); + + assertFalse(result1); + assertTrue(result2); + assertTrue(result3); + } + + @Test + public void testTemplate() { + String origin = "【工银信用卡】于${startTime}至${endTime}申办奋斗卡,无年费,赢郎平签名排球!详情${link}"; + Map map = new HashMap() { + { + put("startTime", "昨天"); + put("endTime", "今天"); + put("link", "没有"); + } + }; + String newStr = renderTemplate(origin, map); + assertTrue(newStr.equals("【工银信用卡】于昨天至今天申办奋斗卡,无年费,赢郎平签名排球!详情没有")); + } + + private String renderTemplate(String origin, Map map) { + Pattern p = Pattern.compile("\\$\\{(.*?)\\}"); + Matcher m = p.matcher(origin); + String newStr = origin; + Matcher newM; + String match; + while (m.find()) { + match = m.group(1); + newM = p.matcher(newStr); + newStr = newM.replaceFirst(map.get(match)); + } + return newStr; + } + + @Test + public void testReverseTemplate() { + String origin = "【工银信用卡】于${startTime}至${endTime}申办奋斗卡,\n" + + "无年费,赢郎平签名排球!详情${link}"; + String newStr = "【工银信用卡】于昨天至今天申办奋斗卡,\n" + + "无年费,赢郎平签名排球!详情没有"; + Map map = extractTemplateMap(origin, newStr); + Map map2 = new HashMap() { + { + put("startTime", "昨天"); + put("endTime", "今天"); + put("link", "没有"); + } + }; + assertEquals( map, map2 ); + + // 我的方法无法用于下面的代码 +// origin = "(【工银信用卡】于${startTime}至${endTime}申办奋斗卡,无年费,赢郎平签名排球!详情${link}."; +// newStr = "(【工银信用卡】于昨天至今天申办奋斗卡,无年费,赢郎平签名排球!详情没有."; +// map = extractTemplateMap(origin, newStr); +// System.out.println(map); + } + + private Map extractTemplateMap(String origin, String newStr) { + Map map = new HashMap<>(10); + List keys = new LinkedList<>(); + Pattern p1 = Pattern.compile("\\$\\{(.+?)\\}"); + Matcher m1 = p1.matcher(origin); + while (m1.find()) { + keys.add(m1.group(1)); + } + String newRegex = "^" + m1.replaceAll("(.*?)") + "$"; // newRegex = "【工银信用卡】于(.*?)至(.*?)申办奋斗卡,无年费,赢郎平签名排球!详情(.*?)." + Pattern p2 = Pattern.compile(newRegex); + Matcher m2 = p2.matcher(newStr); + int index = 0; + while (m2.find()) { + for (int i = 1; i <= m2.groupCount(); i++) { + map.put(keys.get(index), m2.group(i)); + index++; + } + } + return map; + } + + @Test + public void test_template_string() { + String tmpl = null; + String text = null; + + // test data 1 + tmpl = "【工银信用卡】于${startTime}至${endTime}申办奋斗卡,无年费,赢郎平签名排球!详情${link}."; + text = "【工银信用卡】于昨天至今天申办奋斗卡,无年费,赢郎平签名排球!详情没有."; + + // test data 2 + tmpl = "a${startTime}b${endTime}"; + text = "abbc"; + + // test data 3 + tmpl = "(${startTime}至)${endTime}."; + text = "(昨天至)今天."; + + System.out.println("模板字符串:" + tmpl); + System.out.println("文本字符串:" + text); + System.out.println(); + + // 模板字符串中变量的正则表达式 + String keyRegex = "\\$\\{.*?\\}"; + + // 找出模板字符串中变量 + List keyList = new ArrayList<>(); + { + Pattern p = Pattern.compile(keyRegex); + Matcher m = p.matcher(tmpl); + + while (m.find()) { + keyList.add(m.group()); + } + } + + // 找出文本字符串中替换值集合 + List valueList = new ArrayList<>(); + { + // **关键想法** 把模板字符串改装成正则表达式 + + // ** 难点** + // 如果字符串中有元字符,改装后的正则表达式会有语法错误。 + // 例子:如果模板字符串中仅存在一个(,该装后的正则表达式会有语法错误。 + // 所以在每一个字符前都加\,这样(就变成\(,变成匹配(,符合原意。 + // 但是如果模板字符串中仅存在一个t,变成了\t,变成了匹配tab键,又出现了错误。 + // 结合以上的说明,我们要有选择的在字符前加\, 我们在非数字字母的字符前加\ + String tmplEscape = tmpl.replaceAll("([^\\w])", "\\\\$1"); + + // 在原始模板字符串中的占位符中的非数字字母的字符前, + // 已经被加\,所以占位符的正则表达式也要做相应的编辑 + String keyRegexEscape = "\\\\\\$\\\\\\{.*?\\\\\\}"; + + String tmplRegex = "^" + tmplEscape.replaceAll(keyRegexEscape, "(.*?)") + "$"; + System.out.println("模板字符串改装后的正则表达式:" + tmplRegex); + System.out.println(); + // 注: "\至" 也匹配 "至" + Pattern p = Pattern.compile(tmplRegex); + Matcher m = p.matcher(text); + if (m.find()) { + for (int i = 1; i <= m.groupCount(); i++) { + valueList.add(m.group(i)); + } + } + } + + // 输出结果 + if (valueList.isEmpty()) { + System.out.println("the text file format is not correct"); + } else { + for (int i = 0; i < keyList.size(); i++) { + System.out.println(keyList.get(i) + "\t\t" + valueList.get(i)); + } + } + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myknowledgepoint/streams/EntrySetTest.java b/students/812350401/src/main/java/com/coderising/myknowledgepoint/streams/EntrySetTest.java new file mode 100644 index 0000000000..6287afea7e --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myknowledgepoint/streams/EntrySetTest.java @@ -0,0 +1,35 @@ +package com.coderising.myknowledgepoint.streams; + +import org.junit.Test; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * Created by thomas_young on 20/7/2017. + */ +public class EntrySetTest { + @Test + public void test1() { + System.out.println("----test1----"); + Map map = new HashMap<>(); + map.put("01", "zhangsan"); + map.put("02", "lisi"); + map.put("03", "wangwu"); + Collection collection = map.keySet(); // 返回值是个值的Collection集合 + collection.stream().forEach(key -> System.out.println(key + ": " + map.get(key))); + } + + @Test + public void test2() { + System.out.println("----test2----"); + Map map = new HashMap<>(); + map.put("01", "zhangsan"); + map.put("02", "lisi"); + map.put("03", "wangwu"); + Set> entrySet = map.entrySet(); + entrySet.stream().forEach(entry -> System.out.println(entry.getKey() + ": " + entry.getValue())); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myknowledgepoint/threadlocal/Context.java b/students/812350401/src/main/java/com/coderising/myknowledgepoint/threadlocal/Context.java new file mode 100644 index 0000000000..a9b18ddaf4 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myknowledgepoint/threadlocal/Context.java @@ -0,0 +1,21 @@ +package com.coderising.myknowledgepoint.threadlocal; + +import java.util.HashMap; +import java.util.Map; + +public class Context { + + private static final ThreadLocal txThreadLocal + = new ThreadLocal(); + + public static void setTransactionID(String txID) { + txThreadLocal.set(txID); + + } + + public static String getTransactionId() { + return txThreadLocal.get(); + } + +} + diff --git a/students/812350401/src/main/java/com/coderising/myknowledgepoint/threadlocal/TransactionManager.java b/students/812350401/src/main/java/com/coderising/myknowledgepoint/threadlocal/TransactionManager.java new file mode 100644 index 0000000000..2cf9170578 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myknowledgepoint/threadlocal/TransactionManager.java @@ -0,0 +1,22 @@ +package com.coderising.myknowledgepoint.threadlocal; + +public class TransactionManager { + private static final ThreadLocal context = new ThreadLocal(); + + public static void startTransaction() { + // logic to start a transaction + // ... + String txID = null; + context.set(txID); + } + + public static String getTransactionId() { + return context.get(); + } + + public static void endTransaction() { + // logic to end a transaction + // … + context.remove(); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myknowledgepoint/threadpool/BlockingQueue.java b/students/812350401/src/main/java/com/coderising/myknowledgepoint/threadpool/BlockingQueue.java new file mode 100644 index 0000000000..d6e9ec5104 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myknowledgepoint/threadpool/BlockingQueue.java @@ -0,0 +1,36 @@ +package com.coderising.myknowledgepoint.threadpool; + +import java.util.LinkedList; +import java.util.List; + +public class BlockingQueue { + + private List queue = new LinkedList(); + private int limit = 10; + + public BlockingQueue(int limit) { + this.limit = limit; + } + + public synchronized void enqueue(Object item) throws InterruptedException { + while (this.queue.size() == this.limit) { + wait(); + } + if (this.queue.size() == 0) { + notifyAll(); + } + this.queue.add(item); + } + + public synchronized Object dequeue() throws InterruptedException { + while (this.queue.size() == 0) { + wait(); + } + if (this.queue.size() == this.limit) { + notifyAll(); + } + + return this.queue.remove(0); + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myknowledgepoint/threadpool/DriveThreadPool.java b/students/812350401/src/main/java/com/coderising/myknowledgepoint/threadpool/DriveThreadPool.java new file mode 100644 index 0000000000..015317af41 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myknowledgepoint/threadpool/DriveThreadPool.java @@ -0,0 +1,25 @@ +package com.coderising.myknowledgepoint.threadpool; + +/** + * Created by thomas_young on 26/6/2017. + */ +public class DriveThreadPool { + + public static void main(String[] args) throws Exception { + Task task = ()-> { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + System.out.println("I'm killed!"); + } + System.out.println("haha"); + }; + + ThreadPool pool = new ThreadPool(5, 2); + for (int i=1; i<10; i++) { + pool.execute(task); + } + pool.stop(); + + } +} diff --git a/students/812350401/src/main/java/com/coderising/myknowledgepoint/threadpool/Task.java b/students/812350401/src/main/java/com/coderising/myknowledgepoint/threadpool/Task.java new file mode 100644 index 0000000000..418d672f78 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myknowledgepoint/threadpool/Task.java @@ -0,0 +1,5 @@ +package com.coderising.myknowledgepoint.threadpool; + +public interface Task { + void execute(); +} diff --git a/students/812350401/src/main/java/com/coderising/myknowledgepoint/threadpool/ThreadPool.java b/students/812350401/src/main/java/com/coderising/myknowledgepoint/threadpool/ThreadPool.java new file mode 100644 index 0000000000..96472822e2 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myknowledgepoint/threadpool/ThreadPool.java @@ -0,0 +1,48 @@ +package com.coderising.myknowledgepoint.threadpool; + +import java.util.ArrayList; +import java.util.List; + + +public class ThreadPool { + + private BlockingQueue taskQueue = null; + private List threads = new ArrayList<>(); + private boolean isStopped = false; + + /** + * 线程池实例化的时候,线程就都启动了 + * @param numOfThreads + * @param maxNumOfTasks + */ + public ThreadPool(int numOfThreads, int maxNumOfTasks){ + taskQueue = new BlockingQueue(maxNumOfTasks); + + for(int i=0; i10000元 +存款,存款金额<5元 +存款,取款金额<10000元,正常存款 +取款,存款金额>5元,正常取现 +查询 +转账 + diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/ATM.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/ATM.java new file mode 100644 index 0000000000..9d55be57ef --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/ATM.java @@ -0,0 +1,139 @@ +package com.coderising.myood.atmSimulation.impl; + +import com.coderising.myood.atmSimulation.model.*; + +/** + * Created by thomas_young on 30/7/2017. + * ATM对象 + */ +public class ATM { + private CardReader cardReader; + private SuperKeyPad superKeyPad; + private CashDispenser cashDispenser; + private DepositSlot depositSlot; + private Printer printer; + private BankProxy bankProxy; + /** + * 判断取款金额 + * @param amount + * @return + */ + public boolean hasEnoughMoney(Double amount) { + return cashDispenser.hasEnoughMoney(amount); + } + + /** + * 取款 + * @param amount + */ + public void dispenseMoney(Double amount) { + cashDispenser.dispenseMoney(amount); + } + + /** + * 存款 + * @return + */ + public Double retrieveMoney(Double amount) { + return depositSlot.saveMoney(amount); + } + + /** + * 主流程 + */ + public void start() { + // step1. 读卡 + String account; + while(true) { + account = cardReader.getAccount(); + if(account != null) { + System.out.println("读卡成功,卡号是"+account); + break; + } + try { + Thread.sleep(100); + } catch (InterruptedException e) { + } + } + + // step2. 读取密码,并做校验 + int failedCount = 0; + boolean verified = false; + String password = null; + while (failedCount < 3) { + password = superKeyPad.getPassword(); + verified = bankProxy.verify(account, password); + if (verified) { + break; + } + failedCount++; + } + if (!verified) { + System.out.println("输错密码超过3次"); + cardReader.eatCard(); + return; + } + + // step3. 输入交易类型,进行交易 + Transaction transaction = superKeyPad.getTransaction(account, password); + boolean valid = transaction.preProcess(this); + if (!valid) { + cardReader.ejectCard(); + return; + } + boolean success = bankProxy.process(transaction); + if (!success) { + System.out.printf("银行处理出错"); + } else { + System.out.println("银行已经处理完成"); + transaction.postProcess(this); + } + + // last step. 最后记得把卡吐出 + cardReader.ejectCard(); + } + + public CardReader getCardReader() { + return cardReader; + } + + public void setCardReader(CardReader cardReader) { + this.cardReader = cardReader; + } + + public SuperKeyPad getSuperKeyPad() { + return superKeyPad; + } + + public void setSuperKeyPad(SuperKeyPad superKeyPad) { + this.superKeyPad = superKeyPad; + } + + public CashDispenser getCashDispenser() { + return cashDispenser; + } + + public void setCashDispenser(CashDispenser cashDispenser) { + this.cashDispenser = cashDispenser; + } + + public DepositSlot getDepositSlot() { + return depositSlot; + } + + public void setDepositSlot(DepositSlot depositSlot) { + this.depositSlot = depositSlot; + } + + public Printer getPrinter() { + return printer; + } + + public void setPrinter(Printer printer) { + this.printer = printer; + } + + public void setBankProxy(BankProxy bankProxy) { + this.bankProxy = bankProxy; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/BankProxyImpl.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/BankProxyImpl.java new file mode 100644 index 0000000000..59de304cae --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/BankProxyImpl.java @@ -0,0 +1,23 @@ +package com.coderising.myood.atmSimulation.impl; + +import com.coderising.myood.atmSimulation.model.BankProxy; +import com.coderising.myood.atmSimulation.model.Transaction; + +/** + * Created by thomas_young on 30/7/2017. + */ +public class BankProxyImpl extends BankProxy { + + @Override + public boolean verify(String account, String password) { + return networkClient.verify(account, password); + } + + @Override + public boolean process(Transaction transaction) { + System.out.println("开始把transaction发给银行做处理"); + System.out.println(transaction.getClass()); + System.out.println(transaction); + return true; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/CardReaderImpl.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/CardReaderImpl.java new file mode 100644 index 0000000000..5cd59b67d4 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/CardReaderImpl.java @@ -0,0 +1,33 @@ +package com.coderising.myood.atmSimulation.impl; + +import com.coderising.myood.atmSimulation.model.CardReader; + +/** + * Created by thomas_young on 30/7/2017. + */ +public class CardReaderImpl implements CardReader { + private Integer retryTimes = 0; + + @Override + public String getAccount() { + // 模拟读三次才把卡读出 + if (retryTimes <= 2) { + System.out.println("没有卡哟"); + retryTimes++; + return null; + } + return "yangkaiAccount"; + } + + @Override + public void ejectCard() { + System.out.printf("吐出卡片, 请收好"); + retryTimes = 0; + } + + @Override + public void eatCard() { + System.out.printf("吞卡!"); + retryTimes = 0; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/CashDispenserImpl.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/CashDispenserImpl.java new file mode 100644 index 0000000000..22483bb6a6 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/CashDispenserImpl.java @@ -0,0 +1,24 @@ +package com.coderising.myood.atmSimulation.impl; + +import com.coderising.myood.atmSimulation.model.CashDispenser; + +/** + * Created by thomas_young on 30/7/2017. + * 吐钞口/取款口 + */ +public class CashDispenserImpl implements CashDispenser { + // 方便起见,假设atm机子里有这么多前,而且不会变 todo magic number! + private static Double totalAmount = 10000d; + @Override + public boolean hasEnoughMoney(Double amount) { + if (amount <= totalAmount) + return true; + System.out.println("atm没钱啦"); + return false; + } + + @Override + public void dispenseMoney(Double amount) { + System.out.println("取款:吐出"+amount+"元"); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/DepositSlotImpl.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/DepositSlotImpl.java new file mode 100644 index 0000000000..b04b9016db --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/DepositSlotImpl.java @@ -0,0 +1,16 @@ +package com.coderising.myood.atmSimulation.impl; + +import com.coderising.myood.atmSimulation.model.DepositSlot; + +/** + * Created by thomas_young on 30/7/2017. + */ +public class DepositSlotImpl implements DepositSlot { + @Override + public Double saveMoney(Double amount) { + System.out.println("存款: 请放入钞票"+amount+"元"); + // TODO: 30/7/2017 magic number! + Double actualAmount = amount - 5d; // 5元手续费 + return actualAmount < 0d ? 0d:actualAmount; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/DepositTransaction.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/DepositTransaction.java new file mode 100644 index 0000000000..705a01fba5 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/DepositTransaction.java @@ -0,0 +1,56 @@ +package com.coderising.myood.atmSimulation.impl; + +import com.coderising.myood.atmSimulation.model.Transaction; + +/** + * Created by thomas_young on 30/7/2017. + */ +public class DepositTransaction extends Transaction { + // 该取款交易的存款金额 + private Double amount; + private Double actualAmount; + + public DepositTransaction(String account, String password, Double amount) { + super(account, password); + this.amount = amount; + } + + @Override + public boolean preProcess(ATM atm) { + actualAmount = atm.retrieveMoney(amount); + System.out.println("实际存款"+actualAmount+"元"); + return true; + } + + /** + * 什么都不做 + * @param atm + * @return + */ + @Override + public boolean postProcess(ATM atm) { + // TODO: 30/7/2017 只是为了调试,建议删除 + System.out.println("存款postProcess: 什么都不做"); + return true; + } + + @Override + public String toNetworkPackage() { + return null; + } + + @Override + public String toString() { + return super.toString() + " DepositTransaction{" + + "amount=" + amount + ", actualAmount=" + actualAmount + + '}'; + } + + public Double getAmount() { + return amount; + } + + public Double getActualAmount() { + return actualAmount; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/DisplayImpl.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/DisplayImpl.java new file mode 100644 index 0000000000..7a4e638143 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/DisplayImpl.java @@ -0,0 +1,23 @@ +package com.coderising.myood.atmSimulation.impl; + +import com.coderising.myood.atmSimulation.model.Display; +import org.apache.commons.lang3.StringUtils; + +/** + * Created by thomas_young on 30/7/2017. + */ +public class DisplayImpl implements Display { + @Override + public void outputPlainText(String message) { + System.out.printf(message); + } + + @Override + public void outputEncryptedText(String message) { + System.out.println(StringUtils.repeat("*", message.length())); + } + + public static void main(String[] args) { + System.out.printf(StringUtils.repeat("*", "abc".length())); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/KeyBoardImpl.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/KeyBoardImpl.java new file mode 100644 index 0000000000..df98335a78 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/KeyBoardImpl.java @@ -0,0 +1,29 @@ +package com.coderising.myood.atmSimulation.impl; + +import com.coderising.myood.atmSimulation.model.KeyBoard; +import com.coderising.myood.atmSimulation.utils.SingletonScanner; + +import java.util.Scanner; + +/** + * Created by thomas_young on 30/7/2017. + */ +public class KeyBoardImpl implements KeyBoard { + @Override + public String input() { + // TODO: 30/7/2017 强烈建议改成正常的方式,否则后患无穷,现在已经有测试用例跑不过了 +// Scanner sc = SingletonScanner.getInstance(); + Scanner sc = new Scanner(System.in); + String input = sc.nextLine(); + return input; + } + + public static void main(String[] args) { + KeyBoard keyBoard = new KeyBoardImpl(); + String input = keyBoard.input(); + System.out.printf(input); + input = keyBoard.input(); + System.out.printf(input); + + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/NetworkClient.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/NetworkClient.java new file mode 100644 index 0000000000..8339ac8768 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/NetworkClient.java @@ -0,0 +1,16 @@ +package com.coderising.myood.atmSimulation.impl; + +/** + * Created by thomas_young on 30/7/2017. + */ +public class NetworkClient { + private static final String actualPwd = "123456"; + + public boolean verify(String account, String password) { + // TODO: 30/7/2017 暂时写死,以后可以考虑加入银行那边类的交互 + if (account!=null && actualPwd.equals(password)) { + return true; + } + return false; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/QueryTransaction.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/QueryTransaction.java new file mode 100644 index 0000000000..e7f7d39430 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/QueryTransaction.java @@ -0,0 +1,29 @@ +package com.coderising.myood.atmSimulation.impl; + +import com.coderising.myood.atmSimulation.model.Transaction; + +/** + * Created by thomas_young on 30/7/2017. + */ +public class QueryTransaction extends Transaction { + public QueryTransaction(String account, String password) { + super(account, password); + } + + @Override + public boolean preProcess(ATM atm) { + System.out.println("查询:不做前处理"); + return true; + } + + @Override + public boolean postProcess(ATM atm) { + System.out.println("查询:不做后处理"); + return true; + } + + @Override + public String toNetworkPackage() { + return null; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/SuperKeyPad.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/SuperKeyPad.java new file mode 100644 index 0000000000..b0d57463eb --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/SuperKeyPad.java @@ -0,0 +1,123 @@ +package com.coderising.myood.atmSimulation.impl; + +import com.coderising.myood.atmSimulation.model.Display; +import com.coderising.myood.atmSimulation.model.KeyBoard; +import com.coderising.myood.atmSimulation.model.Transaction; + +/** + * Created by thomas_young on 30/7/2017. + * 超级键盘协调用户输入和显示星号的关系 + */ +public class SuperKeyPad { + private Display display; + private KeyBoard keyBoard; + + /** + * 提示用户输入密码,待用户输入完成后,显示星号 + * 并把明文密码返回(为了简单起见) + * @return + */ + public String getPassword() { + System.out.println("请输入密码:"); + String input = keyBoard.input(); + display.outputEncryptedText(input); + return input; + } + + public void displayMessage(String message) { + display.outputPlainText(message); + } + + public Transaction getTransaction(String account, String password) { + display.outputPlainText("请输入交易类型:"); + display.outputPlainText("W: 取款, "); + display.outputPlainText("D: 存款, "); + display.outputPlainText("T: 转账, "); + display.outputPlainText("Q: 查询余额"); + while(true) { + String input = keyBoard.input(); + switch (input) { + case "W": + return getWithdrawTrx(account, password); + case "D": + return getDepositTrx(account, password); + case "T": + return getTransferTrx(account, password); + case "Q": + return getQueryTrx(account, password); + default: + System.out.printf("输入有误,请重新输入"); + } + } + } + + private Transaction getWithdrawTrx(String account, String password) { + while(true) { + display.outputPlainText("请输入取现金额:"); + String input = keyBoard.input(); + try { + Double amount = Double.valueOf(input); + return new WithdrawTransaction(account, password, amount); + } catch (NumberFormatException e) { + System.out.printf("格式有误,请重新输入"); + } + } + } + + private Transaction getDepositTrx(String account, String password) { + while(true) { + display.outputPlainText("请输入存款金额:"); + String input = keyBoard.input(); + try { + Double amount = Double.valueOf(input); + return new DepositTransaction(account, password, amount); + } catch (NumberFormatException e) { + System.out.printf("格式有误,请重新输入"); + } + } + } + + private Transaction getTransferTrx(String account, String password) { + while(true) { + display.outputPlainText("请输入对方账户:"); + String counterAccount = keyBoard.input(); + if ("".equals(counterAccount)) { + System.out.printf("输入账户有误,请重新输入"); + continue; + } + display.outputPlainText("请输入转账金额:"); + String input = keyBoard.input(); + try { + Double amount = Double.valueOf(input); + return new TransferTransaction(account, password, amount, counterAccount); + } catch (NumberFormatException e) { + System.out.printf("格式有误,请重新输入"); + } + } + } + + private Transaction getQueryTrx(String account, String password) { + return new QueryTransaction(account, password); + } + + public void setDisplay(Display display) { + this.display = display; + } + + public void setKeyBoard(KeyBoard keyBoard) { + this.keyBoard = keyBoard; + } + + public static void main(String[] args) { + SuperKeyPad superKeyPad = new SuperKeyPad(); + Display display = new DisplayImpl(); + KeyBoard keyBoard = new KeyBoardImpl(); + superKeyPad.setKeyBoard(keyBoard); + superKeyPad.setDisplay(display); + Transaction transaction = superKeyPad.getTransaction("yangkai", "123456"); + System.out.println(transaction); + + String password = superKeyPad.getPassword(); + System.out.println(password); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/TransferTransaction.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/TransferTransaction.java new file mode 100644 index 0000000000..d34e00b664 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/TransferTransaction.java @@ -0,0 +1,44 @@ +package com.coderising.myood.atmSimulation.impl; + +import com.coderising.myood.atmSimulation.model.Transaction; + +/** + * Created by thomas_young on 30/7/2017. + */ +public class TransferTransaction extends Transaction { + // 转账金额 + private Double amount; + // 对方账户 + private String counterAccount; + + public TransferTransaction(String account, String password, Double amount, String counterAccount) { + super(account, password); + this.amount = amount; + this.counterAccount = counterAccount; + } + + @Override + public boolean preProcess(ATM atm) { + System.out.println("转账: 不做前处理"); + return true; + } + + @Override + public boolean postProcess(ATM atm) { + System.out.println("转账: 不做后处理"); + return true; + } + + @Override + public String toNetworkPackage() { + return null; + } + + @Override + public String toString() { + return super.toString() + " TransferTransaction{" + + "amount=" + amount + + ", counterAccount='" + counterAccount + '\'' + + '}'; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/WithdrawTransaction.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/WithdrawTransaction.java new file mode 100644 index 0000000000..74b9f32113 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/impl/WithdrawTransaction.java @@ -0,0 +1,49 @@ +package com.coderising.myood.atmSimulation.impl; + +import com.coderising.myood.atmSimulation.model.Transaction; + +/** + * Created by thomas_young on 30/7/2017. + * 取款交易 + */ +public class WithdrawTransaction extends Transaction { + // 该取款交易的取款金额 + private Double amount; + + public WithdrawTransaction(String account, String password, Double amount) { + super(account, password); + this.amount = amount; + } + + /** + * 判断atm里的钱是否足够 + * @param atm + * @return + */ + @Override + public boolean preProcess(ATM atm) { + return atm.hasEnoughMoney(amount); + } + + @Override + public boolean postProcess(ATM atm) { + atm.dispenseMoney(amount); + return true; + } + + @Override + public String toNetworkPackage() { + return null; + } + + public Double getAmount() { + return amount; + } + + @Override + public String toString() { + return super.toString() + " WithdrawTransaction{" + + "amount=" + amount + + '}'; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/BankProxy.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/BankProxy.java new file mode 100644 index 0000000000..bd1ae67ee5 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/BankProxy.java @@ -0,0 +1,22 @@ +package com.coderising.myood.atmSimulation.model; + +import com.coderising.myood.atmSimulation.impl.NetworkClient; + +/** + * Created by thomas_young on 30/7/2017. + */ +public abstract class BankProxy { + protected NetworkClient networkClient; + + public abstract boolean verify(String account, String password); + + /** + * 交易发送到银行做处理 + * @param transaction + */ + public abstract boolean process(Transaction transaction); + + public void setNetworkClient(NetworkClient networkClient) { + this.networkClient = networkClient; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/CardReader.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/CardReader.java new file mode 100644 index 0000000000..4488591a45 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/CardReader.java @@ -0,0 +1,10 @@ +package com.coderising.myood.atmSimulation.model; + +/** + * Created by thomas_young on 30/7/2017. + */ +public interface CardReader { + String getAccount(); + void ejectCard(); + void eatCard(); +} diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/CashDispenser.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/CashDispenser.java new file mode 100644 index 0000000000..81d167eeb7 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/CashDispenser.java @@ -0,0 +1,22 @@ +package com.coderising.myood.atmSimulation.model; + + +/** + * Created by thomas_young on 30/7/2017. + * 吐钞口/取款口 + * 判断金额是否足够(我们用它来负责管理atm的金额,不再专门搞一个储钱箱了) + */ +public interface CashDispenser { + /** + * 取款amount,判断余额是否足够 + * @param amount + * @return + */ + boolean hasEnoughMoney(Double amount); + + /** + * 吐出amount的钞票 + * @param amount + */ + void dispenseMoney(Double amount); +} diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/DepositSlot.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/DepositSlot.java new file mode 100644 index 0000000000..797efc3ba1 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/DepositSlot.java @@ -0,0 +1,14 @@ +package com.coderising.myood.atmSimulation.model; + +/** + * Created by thomas_young on 30/7/2017. + * 入钞口/存款口 + */ +public interface DepositSlot { + /** + * 存款,可能会口手续费,返回实际存款金额 + * @param amount + * @return + */ + Double saveMoney(Double amount); +} diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/Display.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/Display.java new file mode 100644 index 0000000000..fb9be85412 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/Display.java @@ -0,0 +1,9 @@ +package com.coderising.myood.atmSimulation.model; + +/** + * Created by thomas_young on 30/7/2017. + */ +public interface Display { + void outputPlainText(String message); + void outputEncryptedText(String message); +} diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/KeyBoard.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/KeyBoard.java new file mode 100644 index 0000000000..4bafd55dc0 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/KeyBoard.java @@ -0,0 +1,8 @@ +package com.coderising.myood.atmSimulation.model; + +/** + * Created by thomas_young on 30/7/2017. + */ +public interface KeyBoard { + String input(); +} diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/Printer.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/Printer.java new file mode 100644 index 0000000000..0399b65110 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/Printer.java @@ -0,0 +1,8 @@ +package com.coderising.myood.atmSimulation.model; + +/** + * Created by thomas_young on 30/7/2017. + */ +public interface Printer { + void print(Transaction t); +} diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/Transaction.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/Transaction.java new file mode 100644 index 0000000000..5880b4248b --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/model/Transaction.java @@ -0,0 +1,45 @@ +package com.coderising.myood.atmSimulation.model; + +import com.coderising.myood.atmSimulation.impl.ATM; + +/** + * Created by thomas_young on 30/7/2017. + * 该对象并不持有ATM的实例,它只是依赖ATM罢了 + */ +public abstract class Transaction { + private String account; + private String password; + + public Transaction(String account, String password) { + this.account = account; + this.password = password; + } + + public abstract boolean preProcess(ATM atm); + public abstract boolean postProcess(ATM atm); + public abstract String toNetworkPackage(); + + public String getAccount() { + return account; + } + + public void setAccount(String account) { + this.account = account; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public String toString() { + return "Transaction{" + + "account='" + account + '\'' + + ", password='" + password + '\'' + + '}'; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/atmSimulation/utils/SingletonScanner.java b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/utils/SingletonScanner.java new file mode 100644 index 0000000000..3fc5002dca --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/atmSimulation/utils/SingletonScanner.java @@ -0,0 +1,18 @@ +package com.coderising.myood.atmSimulation.utils; + +import java.util.Scanner; + +/** + * Created by thomas_young on 30/7/2017. + * todo 不得已这么做,因为没法测试连续的控制台输入,强烈建议删除 + */ +public class SingletonScanner { + private static Scanner ourInstance = new Scanner(System.in); + + public static Scanner getInstance() { + return ourInstance; + } + + private SingletonScanner() { + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/Assert.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/Assert.java new file mode 100644 index 0000000000..d542213642 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/Assert.java @@ -0,0 +1,225 @@ +package com.coderising.myood.litejunit.liuxinv1; + +/** + * A set of assert methods. + */ + +public class Assert { + /** + * Protect constructor since it is a static only class + */ + protected Assert() { + } + + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError with the given message. + */ + static public void assertTrue(String message, boolean condition) { + if (!condition) + fail(message); + } + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError. + */ + static public void assertTrue(boolean condition) { + assertTrue(null, condition); + } + /** + * Fails a test with the given message. + */ + static public void fail(String message) { + throw new AssertionFailedError(message); + } + /** + * Fails a test with no message. + */ + static public void fail() { + fail(null); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(String message, Object expected, Object actual) { + if (expected == null && actual == null) + return; + if (expected != null && expected.equals(actual)) + return; + failNotEquals(message, expected, actual); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(Object expected, Object actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, double expected, double actual, double delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Double.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Double(expected), new Double(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) // Because comparison with NaN always returns false + failNotEquals(message, new Double(expected), new Double(actual)); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(double expected, double actual, double delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, float expected, float actual, float delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Float.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Float(expected), new Float(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) + failNotEquals(message, new Float(expected), new Float(actual)); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(float expected, float actual, float delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(String message, long expected, long actual) { + assertEquals(message, new Long(expected), new Long(actual)); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(long expected, long actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(String message, boolean expected, boolean actual) { + assertEquals(message, new Boolean(expected), new Boolean(actual)); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(boolean expected, boolean actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(String message, byte expected, byte actual) { + assertEquals(message, new Byte(expected), new Byte(actual)); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(byte expected, byte actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(String message, char expected, char actual) { + assertEquals(message, new Character(expected), new Character(actual)); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(char expected, char actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(String message, short expected, short actual) { + assertEquals(message, new Short(expected), new Short(actual)); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(short expected, short actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(String message, int expected, int actual) { + assertEquals(message, new Integer(expected), new Integer(actual)); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(int expected, int actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(Object object) { + assertNotNull(null, object); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(String message, Object object) { + assertTrue(message, object != null); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(Object object) { + assertNull(null, object); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(String message, Object object) { + assertTrue(message, object == null); + } + /** + * Asserts that two objects refer to the same object. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertSame(String message, Object expected, Object actual) { + if (expected == actual) + return; + failNotSame(message, expected, actual); + } + /** + * Asserts that two objects refer to the same object. If they are not + * the same an AssertionFailedError is thrown. + */ + static public void assertSame(Object expected, Object actual) { + assertSame(null, expected, actual); + } + + static private void failNotEquals(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected:<"+expected+"> but was:<"+actual+">"); + } + + static private void failNotSame(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected same"); + } +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/AssertionFailedError.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/AssertionFailedError.java new file mode 100644 index 0000000000..9724d5bd99 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/AssertionFailedError.java @@ -0,0 +1,13 @@ +package com.coderising.myood.litejunit.liuxinv1; + +/** + * Thrown when an assertion failed. + */ +public class AssertionFailedError extends Error { + + public AssertionFailedError () { + } + public AssertionFailedError (String message) { + super (message); + } +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/Calculator.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/Calculator.java new file mode 100644 index 0000000000..7ff741ee8b --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/Calculator.java @@ -0,0 +1,22 @@ +package com.coderising.myood.litejunit.liuxinv1; + +public class Calculator { + + private int result = 0; + public void add(int x){ + result += x; + } + public void subtract(int x){ + result -=x; + } + + public int getResult(){ + return this.result; + } + public static void main(String[] args){ + Calculator calculator = new Calculator(); + calculator.add(10); + calculator.subtract(5); + System.out.println(calculator.getResult()); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/CalculatorTest.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/CalculatorTest.java new file mode 100644 index 0000000000..cb2d8cd2c5 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/CalculatorTest.java @@ -0,0 +1,77 @@ +package com.coderising.myood.litejunit.liuxinv1; + + +public class CalculatorTest extends TestCase { + public CalculatorTest(String name) { + super(name); + + } + Calculator calculator =null; + public void setUp(){ + calculator = new Calculator(); + } + public void tearDown(){ + calculator = null; + } + public void testAdd(){ + + calculator.add(10); + assertEquals(10,calculator.getResult()); + } + public void testSubtract(){ + calculator.add(10); + calculator.subtract(5); + assertEquals(4,calculator.getResult()); + } + + private void testXX() { + + } + + public static void main(String[] args){ + TestSuite ts = new TestSuite(CalculatorTest.class); + TestResult tr = new TestResult(); + ts.run(tr); + System.out.println(tr.wasSuccessful()); + for(TestFailure failure : tr.failures){ + System.err.println(failure); + } + /* + Iterator iterator = tr.failures(); + while(iterator.hasNext()) { + System.err.println(iterator.next()); + } + */ +// TestSuite ts2 = new TestSuite(); +// ts2.addTest(ts); +// ts2.run(tr); + /*{ + TestCase tc1 = new CalculatorTest("testAdd"){ + protected void runTest() { + testAdd(); + } + }; + + TestCase tc2 = new CalculatorTest("testSubtract"){ + protected void runTest() { + testSubtract(); + } + }; + tc1.run(); + tc2.run(); + } + + + TestSuite ts = new TestSuite(); + ts.addTest(new CalculatorTest("testAdd")); + ts.addTest(new CalculatorTest("testSubtract")); + + + { + TestCase tc1 = new CalculatorTest("test1"); + TestCase tc2 = new CalculatorTest("test2"); + tc1.run(); + tc2.run(); + }*/ + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/Test.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/Test.java new file mode 100644 index 0000000000..c2e3903826 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/Test.java @@ -0,0 +1,6 @@ +package com.coderising.myood.litejunit.liuxinv1; + +public interface Test { + public abstract int countTestCases(); // command模式,一个测试用例是一个command + public void run(TestResult tr); // 分离测试用例和测试结果,收集参数模式 +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/TestCase.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/TestCase.java new file mode 100644 index 0000000000..1a0887f2a1 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/TestCase.java @@ -0,0 +1,63 @@ +package com.coderising.myood.litejunit.liuxinv1; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + + + +public abstract class TestCase extends Assert implements Test { + private String name; + + TestCase() {} + public TestCase(String name) { + this.name = name; + } + + public int countTestCases() { + return 1; + } + + protected void runTest() throws Throwable { + Method runMethod= null; + try { + runMethod= getClass().getMethod(name, null); + } catch (NoSuchMethodException e) { + fail("Method \""+name+"\" not found"); + } + if (!Modifier.isPublic(runMethod.getModifiers())) { + fail("Method \""+name+"\" should be public"); + } + + try { + runMethod.invoke(this, new Class[0]); + } + catch (InvocationTargetException e) { + e.fillInStackTrace(); + throw e.getTargetException(); + } + catch (IllegalAccessException e) { + e.fillInStackTrace(); + throw e; + } + } + + protected void setUp() { + } + + protected void tearDown() { + } + + public void run(TestResult tr) { + tr.run(this); + } + public void doRun() throws Throwable{ + setUp(); + try{ + runTest(); + } + finally{ + tearDown(); + } + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/TestFailure.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/TestFailure.java new file mode 100644 index 0000000000..08d75a5e90 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/TestFailure.java @@ -0,0 +1,39 @@ +package com.coderising.myood.litejunit.liuxinv1; + +/** + * A TestFailure collects a failed test together with + * the caught exception. + * @see TestResult + */ +public class TestFailure { + protected Test failedTest; + protected Throwable thrownException; + + /** + * Constructs a TestFailure with the given test and exception. + */ + public TestFailure(Test failedTest, Throwable thrownException) { + this.failedTest= failedTest; + this.thrownException= thrownException; + } + /** + * Gets the failed test. + */ + public Test failedTest() { + return failedTest; + } + /** + * Gets the thrown exception. + */ + public Throwable thrownException() { + return thrownException; + } + /** + * Returns a short description of the failure. + */ + public String toString() { + StringBuffer buffer= new StringBuffer(); + buffer.append(failedTest+": "+thrownException.getMessage()); + return buffer.toString(); + } +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/TestResult.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/TestResult.java new file mode 100644 index 0000000000..69b09b8920 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/TestResult.java @@ -0,0 +1,92 @@ +package com.coderising.myood.litejunit.liuxinv1; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + + +public class TestResult extends Object { + protected List failures; // 存储assert失败 + protected List errors; // 存储业务代码异常,比如空指针 + + protected int testCount; + private boolean stop; + + public TestResult() { + failures= new ArrayList<>(); + errors= new ArrayList<>(); + + testCount= 0; + stop= false; + } + + public void addError(Test test, Throwable t) { + errors.add(new TestFailure(test, t)); + } + + public void addFailure(Test test, AssertionFailedError t) { + failures.add(new TestFailure(test, t)); + } + + public void startTest(Test test) { + int count= test.countTestCases(); + testCount+= count; + } + public void endTest(Test test) { + } + + /** + * Runs a TestCase. + */ + protected void run(final TestCase test) { + startTest(test); + try { + test.doRun(); + } + catch (AssertionFailedError e) { + addFailure(test, e); + } + catch (Throwable e) { + addError(test, e); + } + + endTest(test); + } + /** + * Gets the number of run tests. + */ + public int runCount() { + return testCount; + } + + + public boolean shouldStop() { + return stop; + } + + public void stop() { + stop= true; + } + + public int errorCount() { + return errors.size(); + } + + public Iterator errors() { + return errors.iterator(); + } + + public int failureCount() { + return failures.size(); + } + + public Iterator failures() { + return failures.iterator(); + } + /** + * Returns whether the entire test was successful or not. + */ + public boolean wasSuccessful() { + return this.failureCount() == 0 && this.errorCount() == 0; + } +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/TestSuite.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/TestSuite.java new file mode 100644 index 0000000000..32ff05d934 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv1/TestSuite.java @@ -0,0 +1,130 @@ +package com.coderising.myood.litejunit.liuxinv1; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; + +import java.util.Iterator; +import java.util.List; +import java.util.Vector; + + + + +public class TestSuite extends Assert implements Test { + private List tests= new ArrayList<>(10); // 组合模式,可以放TestSuite,也可以放TestCase + private String name; + public TestSuite(){ + + } + public TestSuite(final Class theClass) { + this.name= theClass.getName(); + Constructor constructor= null; + try { + constructor= getConstructor(theClass); + } catch (NoSuchMethodException e) { + addTest(warning("Class "+theClass.getName()+" has no public constructor TestCase(String name)")); + return; + } + + if (!Modifier.isPublic(theClass.getModifiers())) { + addTest(warning("Class "+theClass.getName()+" is not public")); + return; + } + + Vector names= new Vector<>(); + Method[] methods= theClass.getDeclaredMethods(); + for (int i= 0; i < methods.length; i++) { + addTestMethod(methods[i], names, constructor); // 该方法挺重要的 + } + + if (tests.size() == 0) + addTest(warning("No tests found in "+theClass.getName())); + } + + private Constructor getConstructor(Class theClass) throws NoSuchMethodException { + Class[] args= { String.class }; + return theClass.getConstructor(args); + } + private void addTestMethod(Method m, Vector names, Constructor constructor) { + String name= m.getName(); + if (names.contains(name)) + return; + if (isPublicTestMethod(m)) { + names.addElement(name); + + Object[] args= new Object[]{name}; + try { + addTest((Test)constructor.newInstance(args)); + } catch (InstantiationException e) { + addTest(warning("Cannot instantiate test case: "+name+" ("+exceptionToString(e)+")")); + } catch (InvocationTargetException e) { + addTest(warning("Exception in constructor: "+name+" ("+exceptionToString(e.getTargetException())+")")); + } catch (IllegalAccessException e) { + addTest(warning("Cannot access test case: "+name+" ("+exceptionToString(e)+")")); + } + + } else { // almost a test method + if (isTestMethod(m)) + addTest(warning("Test method isn't public: "+m.getName())); + } + } + private boolean isPublicTestMethod(Method m) { + return isTestMethod(m) && Modifier.isPublic(m.getModifiers()); + } + private boolean isTestMethod(Method m) { + String name= m.getName(); + Class[] parameters= m.getParameterTypes(); + Class returnType= m.getReturnType(); + return parameters.length == 0 && name.startsWith("test") && returnType.equals(Void.TYPE); + } + public void addTest(Test test) { + tests.add(test); + } + + private Test warning(final String message) { + return new TestCase("warning") { + public void doRun() { + fail(message); + } + }; + } + private String exceptionToString(Throwable t) { + StringWriter stringWriter= new StringWriter(); + PrintWriter writer= new PrintWriter(stringWriter); + t.printStackTrace(writer); + return stringWriter.toString(); + + } + + + + @Override + public void run(TestResult result) { + for (Iterator e= tests(); e.hasNext(); ) { + if (result.shouldStop() ){ + break; + } + Test test= e.next(); + test.run(result); + } + + } + + public int countTestCases() { + int count= 0; + + for (Iterator e= tests(); e.hasNext(); ) { + Test test= e.next(); + count= count + test.countTestCases(); + } + return count; + } + public Iterator tests() { + return tests.iterator(); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/Assert.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/Assert.java new file mode 100644 index 0000000000..363e4fd7ec --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/Assert.java @@ -0,0 +1,243 @@ +package com.coderising.myood.litejunit.liuxinv2; + +/** + * A set of assert methods. + */ + +public class Assert { + /** + * Protect constructor since it is a static only class + */ + protected Assert() { + } + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError with the given message. + * @deprecated use assertTrue + */ + /*static public void assert(String message, boolean condition) { + if (!condition) + fail(message); + }*/ + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError. + * @deprecated use assertTrue + * + */ + /*static public void assert(boolean condition) { + assert(null, condition); + } +*/ + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError with the given message. + */ + static public void assertTrue(String message, boolean condition) { + if (!condition) + fail(message); + } + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError. + */ + static public void assertTrue(boolean condition) { + assertTrue(null, condition); + } + /** + * Fails a test with the given message. + */ + static public void fail(String message) { + throw new AssertionFailedError(message); + } + /** + * Fails a test with no message. + */ + static public void fail() { + fail(null); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(String message, Object expected, Object actual) { + if (expected == null && actual == null) + return; + if (expected != null && expected.equals(actual)) + return; + failNotEquals(message, expected, actual); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(Object expected, Object actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, double expected, double actual, double delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Double.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Double(expected), new Double(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) // Because comparison with NaN always returns false + failNotEquals(message, new Double(expected), new Double(actual)); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(double expected, double actual, double delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, float expected, float actual, float delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Float.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Float(expected), new Float(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) + failNotEquals(message, new Float(expected), new Float(actual)); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(float expected, float actual, float delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(String message, long expected, long actual) { + assertEquals(message, new Long(expected), new Long(actual)); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(long expected, long actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(String message, boolean expected, boolean actual) { + assertEquals(message, new Boolean(expected), new Boolean(actual)); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(boolean expected, boolean actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(String message, byte expected, byte actual) { + assertEquals(message, new Byte(expected), new Byte(actual)); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(byte expected, byte actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(String message, char expected, char actual) { + assertEquals(message, new Character(expected), new Character(actual)); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(char expected, char actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(String message, short expected, short actual) { + assertEquals(message, new Short(expected), new Short(actual)); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(short expected, short actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(String message, int expected, int actual) { + assertEquals(message, new Integer(expected), new Integer(actual)); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(int expected, int actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(Object object) { + assertNotNull(null, object); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(String message, Object object) { + assertTrue(message, object != null); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(Object object) { + assertNull(null, object); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(String message, Object object) { + assertTrue(message, object == null); + } + /** + * Asserts that two objects refer to the same object. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertSame(String message, Object expected, Object actual) { + if (expected == actual) + return; + failNotSame(message, expected, actual); + } + /** + * Asserts that two objects refer to the same object. If they are not + * the same an AssertionFailedError is thrown. + */ + static public void assertSame(Object expected, Object actual) { + assertSame(null, expected, actual); + } + + static private void failNotEquals(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected:<"+expected+"> but was:<"+actual+">"); + } + + static private void failNotSame(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected same"); + } +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/AssertionFailedError.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/AssertionFailedError.java new file mode 100644 index 0000000000..c65fe3342d --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/AssertionFailedError.java @@ -0,0 +1,13 @@ +package com.coderising.myood.litejunit.liuxinv2; + +/** + * Thrown when an assertion failed. + */ +public class AssertionFailedError extends Error { + + public AssertionFailedError () { + } + public AssertionFailedError (String message) { + super (message); + } +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/Protectable.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/Protectable.java new file mode 100644 index 0000000000..73ef7d573f --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/Protectable.java @@ -0,0 +1,14 @@ +package com.coderising.myood.litejunit.liuxinv2; + +/** + * A Protectable can be run and can throw a Throwable. + * + * @see TestResult + */ +public interface Protectable { + + /** + * Run the the following method protected. + */ + public abstract void protect() throws Throwable; +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/README.md b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/README.md new file mode 100644 index 0000000000..ddba4cb7fd --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/README.md @@ -0,0 +1 @@ +请运行com.coderising.myood.litejunit.liuxinv2.textui.TestRunner.main函数来触发运行 \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/Test.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/Test.java new file mode 100644 index 0000000000..4e3893b5e4 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/Test.java @@ -0,0 +1,6 @@ +package com.coderising.myood.litejunit.liuxinv2; + +public interface Test { + int countTestCases(); + void run(TestResult tr); +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/TestCase.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/TestCase.java new file mode 100644 index 0000000000..be96ba91dd --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/TestCase.java @@ -0,0 +1,64 @@ +package com.coderising.myood.litejunit.liuxinv2; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + + + +public abstract class TestCase extends Assert implements Test { + private String name; + + + public TestCase(String name) { + this.name = name; + } + + + public int countTestCases() { + return 1; + } + + protected void runTest() throws Throwable{ + Method runMethod= null; + try { + runMethod= getClass().getMethod(name, null); + } catch (NoSuchMethodException e) { + fail("Method \""+name+"\" not found"); + } + if (!Modifier.isPublic(runMethod.getModifiers())) { + fail("Method \""+name+"\" should be public"); + } + + try { + runMethod.invoke(this, new Class[0]); + } + catch (InvocationTargetException e) { + e.fillInStackTrace(); + throw e.getTargetException(); + } + catch (IllegalAccessException e) { + e.fillInStackTrace(); + throw e; + } + } + + protected void setUp() { + } + + protected void tearDown() { + } + + public void run(TestResult tr) { + tr.run(this); + } + public void doRun() throws Throwable{ + setUp(); + try{ + runTest(); + } + finally{ + tearDown(); + } + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/TestFailure.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/TestFailure.java new file mode 100644 index 0000000000..66456180f3 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/TestFailure.java @@ -0,0 +1,39 @@ +package com.coderising.myood.litejunit.liuxinv2; + +/** + * A TestFailure collects a failed test together with + * the caught exception. + * @see TestResult + */ +public class TestFailure { + protected Test failedTest; + protected Throwable thrownException; + + /** + * Constructs a TestFailure with the given test and exception. + */ + public TestFailure(Test failedTest, Throwable thrownException) { + this.failedTest= failedTest; + this.thrownException= thrownException; + } + /** + * Gets the failed test. + */ + public Test failedTest() { + return failedTest; + } + /** + * Gets the thrown exception. + */ + public Throwable thrownException() { + return thrownException; + } + /** + * Returns a short description of the failure. + */ + public String toString() { + StringBuffer buffer= new StringBuffer(); + buffer.append(failedTest+": "+thrownException.getMessage()); + return buffer.toString(); + } +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/TestListener.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/TestListener.java new file mode 100644 index 0000000000..82fa647c32 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/TestListener.java @@ -0,0 +1,15 @@ +package com.coderising.myood.litejunit.liuxinv2; + +/** + * A TestListener for test progress + */ +public interface TestListener { + + void addError(Test test, Throwable t); + + void addFailure(Test test, AssertionFailedError t); + + void endTest(Test test); + + void startTest(Test test); +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/TestResult.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/TestResult.java new file mode 100644 index 0000000000..22a1a3130b --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/TestResult.java @@ -0,0 +1,121 @@ +package com.coderising.myood.litejunit.liuxinv2; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + + +public class TestResult extends Object { + protected List failures; + protected List errors; + protected List listeners; + protected int testCount; + private boolean stop; + + public TestResult() { + failures= new ArrayList<>(); + errors= new ArrayList<>(); + listeners = new ArrayList<>(); + testCount= 0; + stop= false; + } + + public void addError(Test test, Throwable t) { + errors.add(new TestFailure(test, t)); + for(TestListener listener: listeners){ + listener.addError(test, t); + } + } + + public void addFailure(Test test, AssertionFailedError t) { + failures.add(new TestFailure(test, t)); + for(TestListener listener: listeners){ + listener.addFailure(test, t); + } + } + + public void startTest(Test test) { + int count= test.countTestCases(); + testCount+= count; + for(TestListener listener: listeners){ + listener.startTest(test); + } + } + public void endTest(Test test) { + for(TestListener listener: listeners){ + listener.endTest(test); + } + } + + /** + * Runs a TestCase. + */ + protected void run(final TestCase test) { + startTest(test); + try { + test.doRun(); + } + catch (AssertionFailedError e) { + addFailure(test, e); + } + catch (Throwable e) { + addError(test, e); + } + + endTest(test); + } + /** + * Gets the number of run tests. + */ + public int runCount() { + return testCount; + } + public void runProtected(final Test test, Protectable p) { + try { + p.protect(); + } + catch (AssertionFailedError e) { + addFailure(test, e); + } + catch (Throwable e) { + addError(test, e); + } + } + + public boolean shouldStop() { + return stop; + } + + public void stop() { + stop= true; + } + + public int errorCount() { + return errors.size(); + } + + public Iterator errors() { + return errors.iterator(); + } + + public int failureCount() { + return failures.size(); + } + + public Iterator failures() { + return failures.iterator(); + } + /** + * Returns whether the entire test was successful or not. + */ + public boolean wasSuccessful() { + return this.failureCount() == 0 && this.errorCount() == 0; + } + public void addListener(TestListener listener) { + listeners.add(listener); + } + + public void removeListener(TestListener listener) { + listeners.remove(listener); + } +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/TestSuite.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/TestSuite.java new file mode 100644 index 0000000000..c91ed237eb --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/TestSuite.java @@ -0,0 +1,132 @@ +package com.coderising.myood.litejunit.liuxinv2; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; + +import java.util.Iterator; +import java.util.List; +import java.util.Vector; + +public class TestSuite extends Assert implements Test { + private List tests= new ArrayList<>(10); + private String name; + public TestSuite(){ + + } + public TestSuite(final Class theClass) { + this.name= theClass.getName(); + Constructor constructor= null; + try { + constructor= getConstructor(theClass); + } catch (NoSuchMethodException e) { + addTest(warning("Class "+theClass.getName()+" has no public constructor TestCase(String name)")); + return; + } + + if (!Modifier.isPublic(theClass.getModifiers())) { + addTest(warning("Class "+theClass.getName()+" is not public")); + return; + } + + Vector names= new Vector<>(); + Method[] methods= theClass.getDeclaredMethods(); + for (int i= 0; i < methods.length; i++) { + addTestMethod(methods[i], names, constructor); + } + + if (tests.size() == 0) + addTest(warning("No tests found in "+theClass.getName())); + } + + public TestSuite(String name) { + this.name = name; + } + private Constructor getConstructor(Class theClass) throws NoSuchMethodException { + Class[] args= { String.class }; + return theClass.getConstructor(args); + } + private void addTestMethod(Method m, Vector names, Constructor constructor) { + String name= m.getName(); + if (names.contains(name)) + return; + if (isPublicTestMethod(m)) { + names.addElement(name); + + Object[] args= new Object[]{name}; + try { + addTest((Test)constructor.newInstance(args)); + } catch (InstantiationException e) { + addTest(warning("Cannot instantiate test case: "+name+" ("+exceptionToString(e)+")")); + } catch (InvocationTargetException e) { + addTest(warning("Exception in constructor: "+name+" ("+exceptionToString(e.getTargetException())+")")); + } catch (IllegalAccessException e) { + addTest(warning("Cannot access test case: "+name+" ("+exceptionToString(e)+")")); + } + + } else { // almost a test method + if (isTestMethod(m)) + addTest(warning("Test method isn't public: "+m.getName())); + } + } + private boolean isPublicTestMethod(Method m) { + return isTestMethod(m) && Modifier.isPublic(m.getModifiers()); + } + private boolean isTestMethod(Method m) { + String name= m.getName(); + Class[] parameters= m.getParameterTypes(); + Class returnType= m.getReturnType(); + return parameters.length == 0 && name.startsWith("test") && returnType.equals(Void.TYPE); + } + public void addTest(Test test) { + tests.add(test); + } + public void addTestSuite(Class testClass) { + addTest(new TestSuite(testClass)); + } + private Test warning(final String message) { + return new TestCase("warning") { + public void doRun() { + fail(message); + } + }; + } + private String exceptionToString(Throwable t) { + StringWriter stringWriter= new StringWriter(); + PrintWriter writer= new PrintWriter(stringWriter); + t.printStackTrace(writer); + return stringWriter.toString(); + + } + + + + @Override + public void run(TestResult result) { + for (Iterator e= tests(); e.hasNext(); ) { + if (result.shouldStop() ){ + break; + } + Test test= (Test)e.next(); + test.run(result); + } + + } + + public int countTestCases() { + int count= 0; + + for (Iterator e= tests(); e.hasNext(); ) { + Test test= e.next(); + count= count + test.countTestCases(); + } + return count; + } + public Iterator tests() { + return tests.iterator(); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/extension/RepeatedTest.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/extension/RepeatedTest.java new file mode 100644 index 0000000000..bddaa55518 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/extension/RepeatedTest.java @@ -0,0 +1,33 @@ +package com.coderising.myood.litejunit.liuxinv2.extension; + +import com.coderising.myood.litejunit.liuxinv2.Test; +import com.coderising.myood.litejunit.liuxinv2.TestResult; + +/** + * A Decorator that runs a test repeatedly. + * + */ +public class RepeatedTest extends TestDecorator { + private int fTimesRepeat; + + public RepeatedTest(Test test, int repeat) { + super(test); + if (repeat < 0) + throw new IllegalArgumentException("Repetition count must be > 0"); + fTimesRepeat= repeat; + } + public int countTestCases() { + return super.countTestCases()*fTimesRepeat; + } + @Override + public void run(TestResult result) { + for (int i= 0; i < fTimesRepeat; i++) { + if (result.shouldStop()) + break; + super.run(result); + } + } + public String toString() { + return super.toString()+"(repeated)"; + } +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/extension/TestDecorator.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/extension/TestDecorator.java new file mode 100644 index 0000000000..47a94ce82c --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/extension/TestDecorator.java @@ -0,0 +1,40 @@ +package com.coderising.myood.litejunit.liuxinv2.extension; + +import com.coderising.myood.litejunit.liuxinv2.Assert; +import com.coderising.myood.litejunit.liuxinv2.Test; +import com.coderising.myood.litejunit.liuxinv2.TestResult; + +/** + * A Decorator for Tests. Use TestDecorator as the base class + * for defining new test decorators. Test decorator subclasses + * can be introduced to add behaviour before or after a test + * is run. + * + */ +public class TestDecorator extends Assert implements Test { + protected Test test; + + public TestDecorator(Test test) { + this.test= test; + } + /** + * The basic run behaviour. + */ + public void basicRun(TestResult result) { + test.run(result); + } + public int countTestCases() { + return test.countTestCases(); + } + public void run(TestResult result) { + basicRun(result); + } + + public String toString() { + return test.toString(); + } + + public Test getTest() { + return test; + } +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/extension/TestSetup.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/extension/TestSetup.java new file mode 100644 index 0000000000..20b5390bfe --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/extension/TestSetup.java @@ -0,0 +1,40 @@ +package com.coderising.myood.litejunit.liuxinv2.extension; + + +import com.coderising.myood.litejunit.liuxinv2.Protectable; +import com.coderising.myood.litejunit.liuxinv2.Test; +import com.coderising.myood.litejunit.liuxinv2.TestResult; + +/** + * A Decorator to set up and tear down additional fixture state. + * Subclass TestSetup and insert it into your tests when you want + * to set up additional state once before the tests are run. + */ +public class TestSetup extends TestDecorator { + + public TestSetup(Test test) { + super(test); + } + public void run(final TestResult result) { + Protectable p= new Protectable() { + public void protect() throws Exception { + setUp(); + basicRun(result); + tearDown(); + } + }; + result.runProtected(this, p); + } + /** + * Sets up the fixture. Override to set up additional fixture + * state. + */ + protected void setUp() throws Exception { + } + /** + * Tears down the fixture. Override to tear down the additional + * fixture state. + */ + protected void tearDown() throws Exception { + } +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/runner/BaseTestRunner.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/runner/BaseTestRunner.java new file mode 100644 index 0000000000..ea4716ef8c --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/runner/BaseTestRunner.java @@ -0,0 +1,86 @@ +package com.coderising.myood.litejunit.liuxinv2.runner; + +import com.coderising.myood.litejunit.liuxinv2.Test; +import com.coderising.myood.litejunit.liuxinv2.TestListener; +import com.coderising.myood.litejunit.liuxinv2.TestSuite; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.text.NumberFormat; + + + +public abstract class BaseTestRunner implements TestListener { + public static final String SUITE_METHODNAME= "suite"; + /** + * Returns a filtered stack trace + */ + public static String getFilteredTrace(Throwable t) { + StringWriter stringWriter= new StringWriter(); + PrintWriter writer= new PrintWriter(stringWriter); + t.printStackTrace(writer); + StringBuffer buffer= stringWriter.getBuffer(); + String trace= buffer.toString(); + return trace; + //return BaseTestRunner.filterStack(trace); + } + + public Test getTest(String suiteClassName) { + if (suiteClassName.length() <= 0) { + return null; + } + Class testClass= null; + try { + testClass= loadSuiteClass(suiteClassName); + } catch (ClassNotFoundException e) { + String clazz= e.getMessage(); + if (clazz == null) + clazz= suiteClassName; + runFailed("Class not found \""+clazz+"\""); + return null; + } catch(Exception e) { + runFailed("Error: "+e.toString()); + return null; + } + Method suiteMethod= null; + try { + suiteMethod= testClass.getMethod(SUITE_METHODNAME, new Class[0]); + } catch(Exception e) { + // try to extract a test suite automatically + //clearStatus(); + return new TestSuite(testClass); + } + Test test= null; + try { + test= (Test)suiteMethod.invoke(null, new Class[0]); // static method + if (test == null) + return test; + } + catch (InvocationTargetException e) { + runFailed("Failed to invoke suite():" + e.getTargetException().toString()); + return null; + } + catch (IllegalAccessException e) { + runFailed("Failed to invoke suite():" + e.toString()); + return null; + } + + //clearStatus(); + return test; + } + protected Class loadSuiteClass(String suiteClassName) throws ClassNotFoundException { + + //TODO + return Class.forName(suiteClassName); + + + //return getLoader().load(suiteClassName); + } + protected abstract void runFailed(String message); + + public String elapsedTimeAsString(long runTime) { + return NumberFormat.getInstance().format((double)runTime/1000); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/sample/AllTest.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/sample/AllTest.java new file mode 100644 index 0000000000..4b598ce48f --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/sample/AllTest.java @@ -0,0 +1,43 @@ +package com.coderising.myood.litejunit.liuxinv2.sample; + + +import com.coderising.myood.litejunit.liuxinv2.Test; +import com.coderising.myood.litejunit.liuxinv2.TestSuite; +import com.coderising.myood.litejunit.liuxinv2.extension.RepeatedTest; +import com.coderising.myood.litejunit.liuxinv2.extension.TestSetup; +import com.coderising.myood.litejunit.liuxinv2.sample.calculator.CalculatorSuite; + +public class AllTest { + /*public static Test suite(){ + + TestSuite suite= new TestSuite("All Test"); + suite.addTest(CalculatorSuite.suite()); + suite.addTestSuite(PersonTest.class); + return suite; + + }*/ + + public static Test suite(){ + + TestSuite suite= new TestSuite("All Test"); + suite.addTest(new RepeatedTest(new TestSuite(PersonTest.class), 2)); // 装饰者模式 + suite.addTest(new RepeatedTest(CalculatorSuite.suite(), 2)); + return new OverallTestSetup(suite); // 装饰者模式 + } + + + static class OverallTestSetup extends TestSetup { + + public OverallTestSetup(Test test) { + super(test); + + } + protected void setUp() throws Exception { + System.out.println("this is overall testsetup"); + } + protected void tearDown() throws Exception { + System.out.println("this is overall teardown"); + } + + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/sample/PersonTest.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/sample/PersonTest.java new file mode 100644 index 0000000000..29e15e7f68 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/sample/PersonTest.java @@ -0,0 +1,39 @@ +package com.coderising.myood.litejunit.liuxinv2.sample; + + +import com.coderising.myood.litejunit.liuxinv2.TestCase; + +public class PersonTest extends TestCase { + + Person p = null; + protected void setUp() { + p = new Person("andy",30); + } + public PersonTest(String name) { + super(name); + } + public void testAge(){ + this.assertEquals(30, p.getAge()); + } + public void testName(){ + this.assertEquals("andy", p.getName()); + } +} +class Person{ + private String name; + private int age; + + public Person(String name, int age) { + + this.name = name; + this.age = age; + } + public String getName() { + return name; + } + public int getAge() { + return age; + } + + +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/sample/calculator/Calculator.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/sample/calculator/Calculator.java new file mode 100644 index 0000000000..3acad7b062 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/sample/calculator/Calculator.java @@ -0,0 +1,22 @@ +package com.coderising.myood.litejunit.liuxinv2.sample.calculator; + +public class Calculator { + + private int result = 0; + public void add(int x){ + result += x; + } + public void subtract(int x){ + result -=x; + } + + public int getResult(){ + return this.result; + } + public static void main(String[] args){ + Calculator calculator = new Calculator(); + calculator.add(10); + calculator.subtract(5); + System.out.println(calculator.getResult()); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/sample/calculator/CalculatorSuite.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/sample/calculator/CalculatorSuite.java new file mode 100644 index 0000000000..22260c24a1 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/sample/calculator/CalculatorSuite.java @@ -0,0 +1,13 @@ +package com.coderising.myood.litejunit.liuxinv2.sample.calculator; + + +import com.coderising.myood.litejunit.liuxinv2.Test; +import com.coderising.myood.litejunit.liuxinv2.TestSuite; + +public class CalculatorSuite { + public static Test suite(){ + TestSuite suite= new TestSuite("Calculator All Test"); + suite.addTestSuite(CalculatorTest.class); + return suite; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/sample/calculator/CalculatorTest.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/sample/calculator/CalculatorTest.java new file mode 100644 index 0000000000..c9822ac80a --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/sample/calculator/CalculatorTest.java @@ -0,0 +1,60 @@ +package com.coderising.myood.litejunit.liuxinv2.sample.calculator; + + +import com.coderising.myood.litejunit.liuxinv2.TestCase; + +public class CalculatorTest extends TestCase { + public CalculatorTest(String name) { + super(name); + + } + Calculator calculator =null; + public void setUp(){ + calculator = new Calculator(); + } + public void tearDown(){ + calculator = null; + } + public void testAdd(){ + + calculator.add(10); + assertEquals(5,calculator.getResult()); + } + public void testSubtract(){ + calculator.add(10); + calculator.subtract(5); + throw new RuntimeException("this is a test"); + //assertEquals(5,calculator.getResult()); + } + + public static void main(String[] args){ + /*{ + TestCase tc1 = new CalculatorTest("testAdd"){ + protected void runTest() { + testAdd(); + } + }; + + TestCase tc2 = new CalculatorTest("testSubtract"){ + protected void runTest() { + testSubtract(); + } + }; + tc1.run(); + tc2.run(); + } + + + TestSuite ts = new TestSuite(); + ts.addTest(new CalculatorTest("testAdd")); + ts.addTest(new CalculatorTest("testSubtract")); + + + { + TestCase tc1 = new CalculatorTest("test1"); + TestCase tc2 = new CalculatorTest("test2"); + tc1.run(); + tc2.run(); + }*/ + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/textui/TestRunner.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/textui/TestRunner.java new file mode 100644 index 0000000000..59d5318d55 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/liuxinv2/textui/TestRunner.java @@ -0,0 +1,199 @@ +package com.coderising.myood.litejunit.liuxinv2.textui; + + +import com.coderising.myood.litejunit.liuxinv2.*; +import com.coderising.myood.litejunit.liuxinv2.runner.BaseTestRunner; +import java.util.*; + +import java.io.PrintStream; + +/** + * Runner是测试的驱动者,同时也是Listener + */ +public class TestRunner extends BaseTestRunner { + PrintStream writer= System.out; + int column= 0; + + /** + * Constructs a TestRunner. + */ + public TestRunner() { + } + + + /** + * Always use the StandardTestSuiteLoader. Overridden from + * BaseTestRunner. + */ + /*public TestSuiteLoader getLoader() { + return new StandardTestSuiteLoader(); + }*/ + + public synchronized void addError(Test test, Throwable t) { + writer().print("E"); + } + + public synchronized void addFailure(Test test, AssertionFailedError t) { + writer().print("F"); + } + + + + public TestResult doRun(Test suite) { + TestResult result= new TestResult(); + result.addListener(this); + long startTime= System.currentTimeMillis(); + suite.run(result); + long endTime= System.currentTimeMillis(); + long runTime= endTime-startTime; + writer().println(); + writer().println("Time: "+elapsedTimeAsString(runTime)); + print(result); + + writer().println(); + + + return result; + } + + + + public synchronized void startTest(Test test) { + writer().print("."); + if (column++ >= 40) { + writer().println(); + column= 0; + } + } + + public void endTest(Test test) { + } + + public static void main(String args[]) { + // todo: 实际中,是通过命令行传入进来的 + args = new String[] {"com.coderising.myood.litejunit.liuxinv2.sample.AllTest"}; + TestRunner testRunner= new TestRunner(); + try { + TestResult r= testRunner.start(args); + if (!r.wasSuccessful()) + System.exit(-1); + System.exit(0); + } catch(Exception e) { + System.err.println(e.getMessage()); + System.exit(-2); + } + } + /** + * Prints failures to the standard output + */ + public synchronized void print(TestResult result) { + printErrors(result); + printFailures(result); + printHeader(result); + } + /** + * Prints the errors to the standard output + */ + public void printErrors(TestResult result) { + if (result.errorCount() != 0) { + if (result.errorCount() == 1) + writer().println("There was "+result.errorCount()+" error:"); + else + writer().println("There were "+result.errorCount()+" errors:"); + + int i= 1; + for (Iterator e = result.errors(); e.hasNext(); i++) { + TestFailure failure= e.next(); + writer().println(i+") "+failure.failedTest()); + writer().print(getFilteredTrace(failure.thrownException())); + } + } + } + /** + * Prints failures to the standard output + */ + public void printFailures(TestResult result) { + if (result.failureCount() != 0) { + if (result.failureCount() == 1) + writer().println("There was " + result.failureCount() + " failure:"); + else + writer().println("There were " + result.failureCount() + " failures:"); + int i = 1; + for (Iterator e= result.failures(); e.hasNext(); i++) { + TestFailure failure= (TestFailure) e.next(); + writer().print(i + ") " + failure.failedTest()); + Throwable t= failure.thrownException(); + writer().print(getFilteredTrace(failure.thrownException())); + } + } + } + /** + * Prints the header of the report + */ + public void printHeader(TestResult result) { + if (result.wasSuccessful()) { + writer().println(); + writer().print("OK"); + writer().println (" (" + result.runCount() + " tests)"); + + } else { + writer().println(); + writer().println("FAILURES!!!"); + writer().println("Tests run: "+result.runCount()+ + ", Failures: "+result.failureCount()+ + ", Errors: "+result.errorCount()); + } + } + + + /** + * Starts a test run. Analyzes the command line arguments + * and runs the given test suite. + */ + protected TestResult start(String args[]) throws Exception { + if(args.length == 0){ + throw new Exception("Usage: TestRunner testCaseName"); + } + String testCase= args[0]; + + try { + Test suite= getTest(testCase); + return doRun(suite); + } + catch(Exception e) { + throw new Exception("Could not create and run test suite: "+e); + } + } + + protected void runFailed(String message) { + System.err.println(message); + System.exit(-1); + } + + /** + * Runs a suite extracted from a TestCase subclass. + */ + static public void run(Class testClass) { + run(new TestSuite(testClass)); + } + /** + * Runs a single test and collects its results. + * This method can be used to start a test run + * from your program. + *
+	 * public static void main (String[] args) {
+	 *     test.textui.TestRunner.run(suite());
+	 * }
+	 * 
+ */ + static public void run(Test suite) { + TestRunner aTestRunner= new TestRunner(); + aTestRunner.doRun(suite); + } + + protected PrintStream writer() { + return writer; + } + + +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/Assert.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/Assert.java new file mode 100644 index 0000000000..8afbd15679 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/Assert.java @@ -0,0 +1,226 @@ +package com.coderising.myood.litejunit.v1; + + +/** + * A set of assert methods. + */ + +public class Assert { + /** + * Protect constructor since it is a static only class + */ + protected Assert() { + } + + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError with the given message. + */ + static public void assertTrue(String message, boolean condition) { + if (!condition) + fail(message); + } + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError. + */ + static public void assertTrue(boolean condition) { + assertTrue(null, condition); + } + /** + * Fails a test with the given message. + */ + static public void fail(String message) { + throw new AssertionFailedError(message); + } + /** + * Fails a test with no message. + */ + static public void fail() { + fail(null); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(String message, Object expected, Object actual) { + if (expected == null && actual == null) + return; + if (expected != null && expected.equals(actual)) + return; + failNotEquals(message, expected, actual); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(Object expected, Object actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, double expected, double actual, double delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Double.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Double(expected), new Double(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) // Because comparison with NaN always returns false + failNotEquals(message, new Double(expected), new Double(actual)); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(double expected, double actual, double delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, float expected, float actual, float delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Float.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Float(expected), new Float(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) + failNotEquals(message, new Float(expected), new Float(actual)); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(float expected, float actual, float delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(String message, long expected, long actual) { + assertEquals(message, new Long(expected), new Long(actual)); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(long expected, long actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(String message, boolean expected, boolean actual) { + assertEquals(message, new Boolean(expected), new Boolean(actual)); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(boolean expected, boolean actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(String message, byte expected, byte actual) { + assertEquals(message, new Byte(expected), new Byte(actual)); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(byte expected, byte actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(String message, char expected, char actual) { + assertEquals(message, new Character(expected), new Character(actual)); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(char expected, char actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(String message, short expected, short actual) { + assertEquals(message, new Short(expected), new Short(actual)); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(short expected, short actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(String message, int expected, int actual) { + assertEquals(message, new Integer(expected), new Integer(actual)); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(int expected, int actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(Object object) { + assertNotNull(null, object); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(String message, Object object) { + assertTrue(message, object != null); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(Object object) { + assertNull(null, object); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(String message, Object object) { + assertTrue(message, object == null); + } + /** + * Asserts that two objects refer to the same object. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertSame(String message, Object expected, Object actual) { + if (expected == actual) + return; + failNotSame(message, expected, actual); + } + /** + * Asserts that two objects refer to the same object. If they are not + * the same an AssertionFailedError is thrown. + */ + static public void assertSame(Object expected, Object actual) { + assertSame(null, expected, actual); + } + + static private void failNotEquals(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected:<"+expected+"> but was:<"+actual+">"); + } + + static private void failNotSame(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected same"); + } +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/AssertionFailedError.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/AssertionFailedError.java new file mode 100644 index 0000000000..3de657c3bd --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/AssertionFailedError.java @@ -0,0 +1,13 @@ +package com.coderising.myood.litejunit.v1; + +/** + * Thrown when an assertion failed. + */ +public class AssertionFailedError extends Error { + + public AssertionFailedError() { + } + public AssertionFailedError(String message) { + super (message); + } +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/Calculator.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/Calculator.java new file mode 100644 index 0000000000..fba48eb1ed --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/Calculator.java @@ -0,0 +1,22 @@ +package com.coderising.myood.litejunit.v1; + +public class Calculator { + + private int result = 0; + public void add(int x){ + result += x; + } + public void subtract(int x){ + result -=x; + } + + public int getResult(){ + return this.result; + } + public static void main(String[] args){ + Calculator calculator = new Calculator(); + calculator.add(10); + calculator.subtract(5); + System.out.println(calculator.getResult()); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/CalculatorTest.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/CalculatorTest.java new file mode 100644 index 0000000000..aa8dce80ee --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/CalculatorTest.java @@ -0,0 +1,37 @@ +package com.coderising.myood.litejunit.v1; + + +public class CalculatorTest extends TestCase { + public CalculatorTest(String name) { + super(name); + + } + private Calculator calculator =null; + + public void setUp(){ + System.out.println("init a calculator instance"); + calculator = new Calculator(); + } + public void tearDown(){ + System.out.println("destroy a calculator instance"); + calculator = null; + } + public void testAdd(){ + + calculator.add(10); + assertEquals(10,calculator.getResult()); + } + public void testSubtract(){ + calculator.add(10); + calculator.subtract(5); + assertEquals(4, calculator.getResult()); + } + + public void haha() { + System.out.println("haha is not test case"); + } + + private void testXX() { + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/ClientToTest.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/ClientToTest.java new file mode 100644 index 0000000000..ef58899fa9 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/ClientToTest.java @@ -0,0 +1,39 @@ +package com.coderising.myood.litejunit.v1; + + +/** + * Created by thomas_young on 21/8/2017. + */ +public class ClientToTest { + + public static void main(String[] args) { + TestResult tr = new TestResult(); + + Test cs1 = new CalculatorTest("testAdd"); + tryTest(cs1, tr); +// Test cs2 = new CalculatorTest("testSubtract"); +// tryTest(cs2, tr); + +// System.out.println("---------------------------------"); +// tr.clearResult(); +// Test ts1 = new TestSuite("AllTest1"); +// ((TestSuite)ts).addTest(new CalculatorTest("haha")); +// ((TestSuite)ts1).addTest(new TestSuite(CalculatorTest.class)); +// tryTest(ts1, tr); + + System.out.println("---------------------------------"); + tr.clearResult(); + Test ts2 = new TestSuite(CalculatorTest.class); + tryTest(ts2, tr); + + } + + private static void tryTest(Test test, TestResult tr) { + test.run(tr); + System.out.println(tr.wasSuccessful()); + for (TestFailure failure: tr.failures) { + System.err.println(failure); + } + System.out.println("runCount=" + tr.runCount()); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/Test.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/Test.java new file mode 100644 index 0000000000..07c74cce4e --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/Test.java @@ -0,0 +1,7 @@ +package com.coderising.myood.litejunit.v1; + + +public interface Test { + int countTestCases(); // command模式,一个测试用例是一个command + void run(TestResult tr); // 分离测试用例和测试结果,收集参数模式 +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/TestCase.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/TestCase.java new file mode 100644 index 0000000000..df35306908 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/TestCase.java @@ -0,0 +1,68 @@ +package com.coderising.myood.litejunit.v1; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +/** + * Created by thomas_young on 21/8/2017. + */ +public abstract class TestCase extends Assert implements Test { + private String name; + protected TestCase(String name) { + this.name = name; + } + @Override + public int countTestCases() { + return 1; + } + + @Override + public void run(TestResult tr) { + tr.run(this); + } + + public void doRun() throws Throwable { + setUp(); + try{ + runTest(); + } + finally{ + tearDown(); + } + } + + private void runTest() throws Throwable { + Method method = null; + try { + method = getClass().getMethod(name, new Class[0]); + } catch (NoSuchMethodException e) { + fail("Method \""+name+"\" not found"); + } + if (!Modifier.isPublic(method.getModifiers())) { + fail("Method \""+name+"\" should be public"); + } + try { + method.invoke(this, null); + } catch (IllegalAccessException e) { + e.fillInStackTrace(); + throw e; + } catch (InvocationTargetException e) { + e.fillInStackTrace(); + throw e.getTargetException(); + } + } + + protected void setUp() { + } + + protected void tearDown() { + } + + @Override + public String toString() { + return "TestCase{" + + "name='" + getClass().getName() + "." + name + '\'' + + '}'; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/TestFailure.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/TestFailure.java new file mode 100644 index 0000000000..9f4455f43c --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/TestFailure.java @@ -0,0 +1,40 @@ +package com.coderising.myood.litejunit.v1; + + +/** + * A TestFailure collects a failed test together with + * the caught exception. + * @see TestResult + */ +public class TestFailure { + protected Test failedTest; + protected Throwable thrownException; + + /** + * Constructs a TestFailure with the given test and exception. + */ + public TestFailure(Test failedTest, Throwable thrownException) { + this.failedTest= failedTest; + this.thrownException= thrownException; + } + /** + * Gets the failed test. + */ + public Test failedTest() { + return failedTest; + } + /** + * Gets the thrown exception. + */ + public Throwable thrownException() { + return thrownException; + } + /** + * Returns a short description of the failure. + */ + public String toString() { + StringBuffer buffer= new StringBuffer(); + buffer.append(failedTest+": "+thrownException.getMessage()); + return buffer.toString(); + } +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/TestResult.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/TestResult.java new file mode 100644 index 0000000000..0a6d967402 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/TestResult.java @@ -0,0 +1,88 @@ +package com.coderising.myood.litejunit.v1; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** + * Created by thomas_young on 21/8/2017. + */ +public class TestResult { + protected List failures; // 存储assert失败 + protected List errors; // 存储业务代码异常,比如空指针 + private int testCount; + private boolean stop; + + public TestResult() { + failures= new ArrayList<>(); + errors= new ArrayList<>(); + + testCount= 0; + stop= false; + } + + public void run(TestCase testCase) { + startTest(testCase); + try { + testCase.doRun(); + } catch (AssertionFailedError e) { + failures.add(new TestFailure(testCase, e)); + } catch (Throwable e) { + errors.add(new TestFailure(testCase, e)); + } + endTest(testCase); + } + + private void startTest(TestCase testCase) { + int count= testCase.countTestCases(); + testCount+= count; + } + + private void endTest(TestCase testCase) { + } + /** + * Gets the number of run tests. + */ + public int runCount() { + return testCount; + } + + + public boolean shouldStop() { + return stop; + } + + public void stop() { + stop= true; + } + + public int errorCount() { + return errors.size(); + } + + public Iterator errors() { + return errors.iterator(); + } + + public int failureCount() { + return failures.size(); + } + + public Iterator failures() { + return failures.iterator(); + } + /** + * Returns whether the entire test was successful or not. + */ + public boolean wasSuccessful() { + return this.failureCount() == 0 && this.errorCount() == 0; + } + + public void clearResult() { + failures.clear(); + errors.clear(); + testCount = 0; + stop= false; + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/TestSuite.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/TestSuite.java new file mode 100644 index 0000000000..19ee4caf16 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v1/TestSuite.java @@ -0,0 +1,127 @@ +package com.coderising.myood.litejunit.v1; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.*; + +/** + * Created by thomas_young on 21/8/2017. + */ +public class TestSuite implements Test { + private String name; + private List tests = new ArrayList<>(10); + + @Override + public int countTestCases() { + int totalCount = 0; + for (Test test: tests) { + totalCount += test.countTestCases(); + } + return totalCount; + } + + public TestSuite(String name) { + this.name = name; + } + + // 把某个测试类中的所有pulic的test方法构造成对象,塞入tests + public TestSuite(final Class theClass) { + this.name = theClass.getName(); + Constructor constructor = null; + try { + constructor = getConstructor(theClass); + } catch (NoSuchMethodException e) { + addTest(warning("Class "+theClass.getName()+" has no public constructor TestCase(String name)")); + } + + if (!Modifier.isPublic(theClass.getModifiers())) { + addTest(warning("Class "+theClass.getName()+" is not public")); + return; + } + + Method[] methods = theClass.getDeclaredMethods(); + Set names = new TreeSet<>(); + for (Method method: methods) { + addTestInstance(method, names, constructor); + } + + if (tests.size() == 0) + addTest(warning("No tests found in "+theClass.getName())); + } + + private Constructor getConstructor(Class theClass) throws NoSuchMethodException { + Class[] args = {String.class}; + return theClass.getConstructor(args); + } + + @Override + public void run(TestResult tr) { + for (Test test: tests) { + if (tr.shouldStop()) break; + test.run(tr); + } + } + + public void addTest(Test test) { + tests.add(test); + } + + public Iterator tests() { + return tests.iterator(); + } + + // --------------------- private --------------------------- + private void addTestInstance(Method method, Set names, Constructor constructor) { + String name = method.getName(); + if (names.contains(name)) { + return; + } + if (!isTestMethod(method)) { + return; + } + if (!Modifier.isPublic(method.getModifiers())) { + addTest(warning("Test method isn't public: "+name)); + return; + } + + names.add(name); + Object[] args= new Object[]{name}; + try { + addTest((Test)constructor.newInstance(args)); + } catch (InstantiationException e) { + addTest(warning("Cannot instantiate test case: "+name+" ("+exceptionToString(e)+")")); + } catch (InvocationTargetException e) { + addTest(warning("Exception in constructor: "+name+" ("+exceptionToString(e.getTargetException())+")")); + } catch (IllegalAccessException e) { + addTest(warning("Cannot access test case: "+name+" ("+exceptionToString(e)+")")); + } + } + + private boolean isTestMethod(Method method) { + String methodName = method.getName(); + int paraCount = method.getParameterCount(); + Class returnType = method.getReturnType(); + return paraCount == 0 && returnType.equals(Void.TYPE) && methodName.startsWith("test"); + } + + private Test warning(final String message) { + return new TestCase("warning") { + public void doRun() { + fail(message); + } + }; + } + + private String exceptionToString(Throwable t) { + StringWriter stringWriter= new StringWriter(); + PrintWriter writer= new PrintWriter(stringWriter); + t.printStackTrace(writer); + return stringWriter.toString(); + + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/Assert.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/Assert.java new file mode 100644 index 0000000000..728ee3ecd0 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/Assert.java @@ -0,0 +1,226 @@ +package com.coderising.myood.litejunit.v2; + + +/** + * A set of assert methods. + */ + +public class Assert { + /** + * Protect constructor since it is a static only class + */ + protected Assert() { + } + + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError with the given message. + */ + static public void assertTrue(String message, boolean condition) { + if (!condition) + fail(message); + } + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError. + */ + static public void assertTrue(boolean condition) { + assertTrue(null, condition); + } + /** + * Fails a test with the given message. + */ + static public void fail(String message) { + throw new AssertionFailedError(message); + } + /** + * Fails a test with no message. + */ + static public void fail() { + fail(null); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(String message, Object expected, Object actual) { + if (expected == null && actual == null) + return; + if (expected != null && expected.equals(actual)) + return; + failNotEquals(message, expected, actual); + } + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(Object expected, Object actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, double expected, double actual, double delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Double.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Double(expected), new Double(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) // Because comparison with NaN always returns false + failNotEquals(message, new Double(expected), new Double(actual)); + } + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(double expected, double actual, double delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, float expected, float actual, float delta) { + // handle infinity specially since subtracting to infinite values gives NaN and the + // the following test fails + if (Float.isInfinite(expected)) { + if (!(expected == actual)) + failNotEquals(message, new Float(expected), new Float(actual)); + } else if (!(Math.abs(expected-actual) <= delta)) + failNotEquals(message, new Float(expected), new Float(actual)); + } + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(float expected, float actual, float delta) { + assertEquals(null, expected, actual, delta); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(String message, long expected, long actual) { + assertEquals(message, new Long(expected), new Long(actual)); + } + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(long expected, long actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(String message, boolean expected, boolean actual) { + assertEquals(message, new Boolean(expected), new Boolean(actual)); + } + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(boolean expected, boolean actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(String message, byte expected, byte actual) { + assertEquals(message, new Byte(expected), new Byte(actual)); + } + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(byte expected, byte actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(String message, char expected, char actual) { + assertEquals(message, new Character(expected), new Character(actual)); + } + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(char expected, char actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(String message, short expected, short actual) { + assertEquals(message, new Short(expected), new Short(actual)); + } + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(short expected, short actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(String message, int expected, int actual) { + assertEquals(message, new Integer(expected), new Integer(actual)); + } + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(int expected, int actual) { + assertEquals(null, expected, actual); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(Object object) { + assertNotNull(null, object); + } + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(String message, Object object) { + assertTrue(message, object != null); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(Object object) { + assertNull(null, object); + } + /** + * Asserts that an object is null. + */ + static public void assertNull(String message, Object object) { + assertTrue(message, object == null); + } + /** + * Asserts that two objects refer to the same object. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertSame(String message, Object expected, Object actual) { + if (expected == actual) + return; + failNotSame(message, expected, actual); + } + /** + * Asserts that two objects refer to the same object. If they are not + * the same an AssertionFailedError is thrown. + */ + static public void assertSame(Object expected, Object actual) { + assertSame(null, expected, actual); + } + + static private void failNotEquals(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected:<"+expected+"> but was:<"+actual+">"); + } + + static private void failNotSame(String message, Object expected, Object actual) { + String formatted= ""; + if (message != null) + formatted= message+" "; + fail(formatted+"expected same"); + } +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/AssertionFailedError.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/AssertionFailedError.java new file mode 100644 index 0000000000..b216b6ef7f --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/AssertionFailedError.java @@ -0,0 +1,13 @@ +package com.coderising.myood.litejunit.v2; + +/** + * Thrown when an assertion failed. + */ +public class AssertionFailedError extends Error { + + public AssertionFailedError() { + } + public AssertionFailedError(String message) { + super (message); + } +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/Calculator.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/Calculator.java new file mode 100644 index 0000000000..9b870f25ae --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/Calculator.java @@ -0,0 +1,22 @@ +package com.coderising.myood.litejunit.v2; + +public class Calculator { + + private int result = 0; + public void add(int x){ + result += x; + } + public void subtract(int x){ + result -=x; + } + + public int getResult(){ + return this.result; + } + public static void main(String[] args){ + Calculator calculator = new Calculator(); + calculator.add(10); + calculator.subtract(5); + System.out.println(calculator.getResult()); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/README.md b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/README.md new file mode 100644 index 0000000000..db5ad14684 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/README.md @@ -0,0 +1,18 @@ +请运行com.coderising.myood.litejunit.v2.TestRunner.main函数来查看结果 + + +### 使用模式 +1. 命令模式: 每个TestCase都有个run方法,run内部包含了业务代码,但是对TestCase来讲不用管, 只要运行run即可 +2. 观察者模式: TestResult是主题, Listener是观察者, 解耦了测试结果和结果显示逻辑 +3. 参数收集: TestResult收集了测试结果, 和测试用例的运行进行了解耦 +4. 组合模式: TestSuite组合了TestCase, 因此可以对类、包、模块进行测试 +5. 装饰器模式: 在Test外面包裹了装饰器, 从而实现重复运行测试用例或者对包整体进行setUp, tearDown +6. 模板方法: setUp, runTest(), tearDown() +7. 协议: 规定了public static Test suite(), 测试用例以test开头, 从而方便反射的运用 + +--------------------------------------- + +### 改进点 +1. TestRunner没有使用反射来寻找suite方法 +2. junit-v4版本后续有空可以实现 +3. 两个装饰器的异常判断不足, 可能意外跳出 \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/Test.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/Test.java new file mode 100644 index 0000000000..ce45f48ee5 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/Test.java @@ -0,0 +1,7 @@ +package com.coderising.myood.litejunit.v2; + + +public interface Test { + int countTestCases(); // command模式,一个测试用例是一个command + void run(TestResult tr); // 分离测试用例和测试结果,收集参数模式 +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/TestCase.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/TestCase.java new file mode 100644 index 0000000000..e9275d988a --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/TestCase.java @@ -0,0 +1,68 @@ +package com.coderising.myood.litejunit.v2; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +/** + * Created by thomas_young on 21/8/2017. + */ +public abstract class TestCase extends Assert implements Test { + private String name; + public TestCase(String name) { + this.name = name; + } + @Override + public int countTestCases() { + return 1; + } + + @Override + public void run(TestResult tr) { + tr.run(this); + } + + public void doRun() throws Throwable { + setUp(); + try{ + runTest(); + } + finally{ + tearDown(); + } + } + + private void runTest() throws Throwable { + Method method = null; + try { + method = getClass().getMethod(name, null); + } catch (NoSuchMethodException e) { + fail("Method \""+name+"\" not found"); + } + if (!Modifier.isPublic(method.getModifiers())) { + fail("Method \""+name+"\" should be public"); + } + try { + method.invoke(this, null); + } catch (IllegalAccessException e) { + e.fillInStackTrace(); + throw e; + } catch (InvocationTargetException e) { + e.fillInStackTrace(); + throw e.getTargetException(); + } + } + + protected void setUp() { + } + + protected void tearDown() { + } + + @Override + public String toString() { + return "TestCase{" + + "name='" + getClass().getName() + "." + name + '\'' + + '}'; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/TestFailure.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/TestFailure.java new file mode 100644 index 0000000000..e306538fc5 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/TestFailure.java @@ -0,0 +1,40 @@ +package com.coderising.myood.litejunit.v2; + + +/** + * A TestFailure collects a failed test together with + * the caught exception. + * @see TestResult + */ +public class TestFailure { + protected Test failedTest; + protected Throwable thrownException; + + /** + * Constructs a TestFailure with the given test and exception. + */ + public TestFailure(Test failedTest, Throwable thrownException) { + this.failedTest= failedTest; + this.thrownException= thrownException; + } + /** + * Gets the failed test. + */ + public Test failedTest() { + return failedTest; + } + /** + * Gets the thrown exception. + */ + public Throwable thrownException() { + return thrownException; + } + /** + * Returns a short description of the failure. + */ + public String toString() { + StringBuffer buffer= new StringBuffer(); + buffer.append(failedTest+": "+thrownException.getMessage()); + return buffer.toString(); + } +} \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/TestListener.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/TestListener.java new file mode 100644 index 0000000000..ec26d6adcc --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/TestListener.java @@ -0,0 +1,11 @@ +package com.coderising.myood.litejunit.v2; + +/** + * Created by thomas_young on 17/9/2017. + */ +public interface TestListener { + void addError(Test test, Throwable t); + void addFailure(Test test, Throwable t); + void startTest(Test test); + void endTest(Test test); +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/TestResult.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/TestResult.java new file mode 100644 index 0000000000..a68e9d5200 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/TestResult.java @@ -0,0 +1,117 @@ +package com.coderising.myood.litejunit.v2; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** + * Created by thomas_young on 21/8/2017. + */ +public class TestResult { + protected List failures; // 存储assert失败 + protected List errors; // 存储业务代码异常,比如空指针 + private List listeners; + private int testCount; + private boolean stop; + + public TestResult() { + failures= new ArrayList<>(); + errors= new ArrayList<>(); + listeners = new ArrayList<>(); + testCount= 0; + stop= false; + } + + public void run(TestCase testCase) { + startTest(testCase); + try { + testCase.doRun(); + } catch (AssertionFailedError e) { + addFailure(testCase, e); + } catch (Throwable e) { + addError(testCase, e); + } + endTest(testCase); + } + + private void addError(TestCase testCase, Throwable e) { + errors.add(new TestFailure(testCase, e)); + for (TestListener listener: listeners) { + listener.addError(testCase, e); + } + } + + private void addFailure(TestCase testCase, AssertionFailedError e) { + failures.add(new TestFailure(testCase, e)); + for (TestListener listener: listeners) { + listener.addFailure(testCase, e); + } + } + + private void startTest(TestCase testCase) { + int count= testCase.countTestCases(); + testCount+= count; + for (TestListener listener: listeners) { + listener.startTest(testCase); + } + } + + private void endTest(TestCase testCase) { + for (TestListener listener: listeners) { + listener.endTest(testCase); + } + } + /** + * Gets the number of run tests. + */ + public int runCount() { + return testCount; + } + + + public boolean shouldStop() { + return stop; + } + + public void stop() { + stop= true; + } + + public int errorCount() { + return errors.size(); + } + + public Iterator errors() { + return errors.iterator(); + } + + public int failureCount() { + return failures.size(); + } + + public Iterator failures() { + return failures.iterator(); + } + /** + * Returns whether the entire test was successful or not. + */ + public boolean wasSuccessful() { + return this.failureCount() == 0 && this.errorCount() == 0; + } + + public void clearResult() { + failures.clear(); + errors.clear(); + testCount = 0; + stop= false; + } + + public void addListener(TestListener listener) { + this.listeners.add(listener); + } + + public void removeListener(TestListener listener) { + this.listeners.remove(listener); + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/TestRunner.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/TestRunner.java new file mode 100644 index 0000000000..12a4fd755d --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/TestRunner.java @@ -0,0 +1,132 @@ +package com.coderising.myood.litejunit.v2; + + +import com.coderising.myood.litejunit.v2.example_test.AllTest; + +import java.io.PrintStream; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Iterator; + +/** + * Created by thomas_young on 21/8/2017. + */ +public class TestRunner implements TestListener { + PrintStream writer = System.out; + + public static void main(String[] args) { + TestRunner testRunner = new TestRunner(); + TestResult tr = new TestResult(); + tr.addListener(testRunner); + Test testAll = AllTest.suite(); // TODO: 17/9/2017 后续要用反射实现这一步 + testRunner.tryTest(testAll, tr); + } + + private void tryTest(Test test, TestResult tr) { + test.run(tr); + System.out.println(); + print(tr); + } + + @Override + public void addError(Test test, Throwable t) { + System.out.print("E"); + } + + @Override + public void addFailure(Test test, Throwable t) { + System.out.print("F"); + } + + @Override + public void startTest(Test test) { + System.out.print("."); + } + + @Override + public void endTest(Test test) { + + } + + /** + * Prints failures to the standard output + */ + public void print(TestResult result) { + printErrors(result); + printFailures(result); + printHeader(result); + } + + /** + * Prints the errors to the standard output + */ + public void printErrors(TestResult result) { + if (result.errorCount() != 0) { + if (result.errorCount() == 1) + writer().println("There was "+result.errorCount()+" error:"); + else + writer().println("There were "+result.errorCount()+" errors:"); + + int i= 1; + for (Iterator e = result.errors(); e.hasNext(); i++) { + TestFailure failure= e.next(); + writer().println(i+") "+failure.failedTest()); + writer().print(getFilteredTrace(failure.thrownException())); + } + } + } + + /** + * Prints failures to the standard output + */ + public void printFailures(TestResult result) { + if (result.failureCount() != 0) { + if (result.failureCount() == 1) + writer().println("There was " + result.failureCount() + " failure:"); + else + writer().println("There were " + result.failureCount() + " failures:"); + int i = 1; + for (Iterator e = result.failures(); e.hasNext(); i++) { + TestFailure failure= (TestFailure) e.next(); + writer().print(i + ") " + failure.failedTest()); + Throwable t= failure.thrownException(); + writer().print(getFilteredTrace(failure.thrownException())); + } + } + } + + protected PrintStream writer() { + return writer; + } + + /** + * Prints the header of the report + */ + public void printHeader(TestResult result) { + if (result.wasSuccessful()) { + writer().println(); + writer().print("OK"); + writer().println (" (" + result.runCount() + " tests)"); + + } else { + writer().println(); + writer().println("FAILURES!!!"); + writer().println("Tests run: "+result.runCount()+ + ", Failures: "+result.failureCount()+ + ", Errors: "+result.errorCount()); + } + } + + /** + * Returns a filtered stack trace + */ + public static String getFilteredTrace(Throwable t) { + StringWriter stringWriter= new StringWriter(); + PrintWriter writer= new PrintWriter(stringWriter); + t.printStackTrace(writer); + StringBuffer buffer= stringWriter.getBuffer(); + String trace= buffer.toString(); + return trace; + //return BaseTestRunner.filterStack(trace); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/TestSuite.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/TestSuite.java new file mode 100644 index 0000000000..63a2c46912 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/TestSuite.java @@ -0,0 +1,133 @@ +package com.coderising.myood.litejunit.v2; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.*; + +/** + * Created by thomas_young on 21/8/2017. + */ +public class TestSuite implements Test { + private String name; + private List tests = new ArrayList<>(10); + + @Override + public int countTestCases() { + int totalCount = 0; + for (Test test: tests) { + totalCount += test.countTestCases(); + } + return totalCount; + } + + public TestSuite(){ + } + public TestSuite(String name) { + this.name = name; + } + + // 把某个测试类中的所有pulic的test方法构造成对象,塞入tests + public TestSuite(final Class theClass) { + this.name = theClass.getName(); + Constructor constructor = null; + try { + constructor = getConstructor(theClass); + } catch (NoSuchMethodException e) { + addTest(warning("Class "+theClass.getName()+" has no public constructor TestCase(String name)")); + } + + if (!Modifier.isPublic(theClass.getModifiers())) { + addTest(warning("Class "+theClass.getName()+" is not public")); + return; + } + + Method[] methods = theClass.getDeclaredMethods(); + Set names = new TreeSet<>(); + for (Method method: methods) { + addTestInstance(method, names, constructor); + } + + if (tests.size() == 0) + addTest(warning("No tests found in "+theClass.getName())); + } + + private Constructor getConstructor(Class theClass) throws NoSuchMethodException { + Class[] args = {String.class}; + return theClass.getConstructor(args); + } + + @Override + public void run(TestResult tr) { + for (Test test: tests) { + if (tr.shouldStop()) break; + test.run(tr); + } + } + + public void addTest(Test test) { + tests.add(test); + } + + public Iterator tests() { + return tests.iterator(); + } + + // --------------------- private --------------------------- + private void addTestInstance(Method method, Set names, Constructor constructor) { + String name = method.getName(); + if (names.contains(name)) { + return; + } + if (!isTestMethod(method)) { + return; + } + + if (!Modifier.isPublic(method.getModifiers())) { + addTest(warning("Test method isn't public: "+name)); + return; + } + + names.add(name); + Object[] args= new Object[]{name}; + try { + addTest((Test)constructor.newInstance(args)); + } catch (InstantiationException e) { + addTest(warning("Cannot instantiate test case: "+name+" ("+exceptionToString(e)+")")); + } catch (InvocationTargetException e) { + addTest(warning("Exception in constructor: "+name+" ("+exceptionToString(e.getTargetException())+")")); + } catch (IllegalAccessException e) { + addTest(warning("Cannot access test case: "+name+" ("+exceptionToString(e)+")")); + } + } + + private boolean isTestMethod(Method method) { + String methodName = method.getName(); + int paraCount = method.getParameterCount(); + Class returnType = method.getReturnType(); + return paraCount == 0 && returnType.equals(Void.TYPE) && methodName.startsWith("test"); + } + + private Test warning(final String message) { + return new TestCase("warning") { + public void doRun() { + fail(message); + } + }; + } + + private String exceptionToString(Throwable t) { + StringWriter stringWriter= new StringWriter(); + PrintWriter writer= new PrintWriter(stringWriter); + t.printStackTrace(writer); + return stringWriter.toString(); + + } + + public void addTestSuite(Class testClass) { + addTest(new TestSuite(testClass)); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example/a/Calculator.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example/a/Calculator.java new file mode 100644 index 0000000000..a87b7e6c77 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example/a/Calculator.java @@ -0,0 +1,23 @@ +package com.coderising.myood.litejunit.v2.example.a; + +/** + * Created by thomas_young on 17/9/2017. + */ +public class Calculator { + public int add(int a,int b){ + return a + b; + } + public int minus(int a,int b){ + return a - b; + } + public int multiply(int a, int b ){ + return a * b; + } + public int divide(int a , int b )throws Exception + { + if(b == 0){ + throw new Exception("除数不能为零"); + } + return a / b; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example/b/Byebye.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example/b/Byebye.java new file mode 100644 index 0000000000..7605c902ce --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example/b/Byebye.java @@ -0,0 +1,10 @@ +package com.coderising.myood.litejunit.v2.example.b; + +/** + * Created by thomas_young on 17/9/2017. + */ +public class Byebye { + public String Say(){ + return "Byebye!"; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example/b/HelloWorld.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example/b/HelloWorld.java new file mode 100644 index 0000000000..6b70522db1 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example/b/HelloWorld.java @@ -0,0 +1,10 @@ +package com.coderising.myood.litejunit.v2.example.b; + +/** + * Created by thomas_young on 17/9/2017. + */ +public class HelloWorld { + public String Say(){ + return "Hello,World!"; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example_test/AllTest.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example_test/AllTest.java new file mode 100644 index 0000000000..1446099836 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example_test/AllTest.java @@ -0,0 +1,30 @@ +package com.coderising.myood.litejunit.v2.example_test; + +import com.coderising.myood.litejunit.v2.Test; +import com.coderising.myood.litejunit.v2.TestSuite; +import com.coderising.myood.litejunit.v2.example_test.a.AAllTest; +import com.coderising.myood.litejunit.v2.example_test.b.BAllTest; +import com.coderising.myood.litejunit.v2.extension.RepeatedTest; +import com.coderising.myood.litejunit.v2.extension.SetUpTest; + +/** + * Created by thomas_young on 17/9/2017. + */ +public class AllTest { + public static Test suite() { + TestSuite suite = new TestSuite(); + suite.addTest(new RepeatedTest(AAllTest.suite(), 2)); // 5 * 2个用例 + suite.addTest(BAllTest.suite()); // 2个用例 + return new SetUpTest(suite) { + @Override + protected void setUp() { + System.out.printf("All start!\n"); + } + + @Override + protected void tearDown() { + System.out.printf("All end!"); + } + }; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example_test/a/AAllTest.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example_test/a/AAllTest.java new file mode 100644 index 0000000000..85900b60ce --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example_test/a/AAllTest.java @@ -0,0 +1,28 @@ +package com.coderising.myood.litejunit.v2.example_test.a; + + +import com.coderising.myood.litejunit.v2.Test; +import com.coderising.myood.litejunit.v2.TestSuite; +import com.coderising.myood.litejunit.v2.extension.SetUpTest; + +/** + * Created by thomas_young on 17/9/2017. + */ +public class AAllTest { + public static Test suite() { + TestSuite suite = new TestSuite(); + suite.addTestSuite(CalculatorTest.class); + return new SetUpTest(suite) { + + @Override + protected void setUp() { + System.out.println("AAll start!"); + } + + @Override + protected void tearDown() { + System.out.println("AAll end!"); + } + }; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example_test/a/CalculatorTest.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example_test/a/CalculatorTest.java new file mode 100644 index 0000000000..ff2638fa37 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example_test/a/CalculatorTest.java @@ -0,0 +1,89 @@ +package com.coderising.myood.litejunit.v2.example_test.a; + +import com.coderising.myood.litejunit.v2.Assert; +import com.coderising.myood.litejunit.v2.TestCase; +import com.coderising.myood.litejunit.v2.example.a.Calculator; + +/** + * Created by thomas_young on 17/9/2017. + */ +public class CalculatorTest extends TestCase { + public CalculatorTest(String name) { + super(name); + } + + /** *//** + * 在Junit3.8中,测试方法满足如下原则 + * 1)public + * 2)void + * 3)无方法参数 + * 4)最重要的方法名称必须以test开头 + */ + private Calculator cal; + + //在执行每个test之前,都执行setUp; + public void setUp(){ + cal = new Calculator(); + } + + //在执行每个test之后,都要执行tearDown + public void tearDown(){ + } + + public void testAdd() + { + Calculator cal = new Calculator(); + int result = cal.add(1, 2); + //断言assert + Assert.assertEquals(3, result); + } + + public void testMinus() + { + Calculator cal = new Calculator(); + int result = cal.minus(5, 2); + throw new RuntimeException("我是异常"); +// Assert.assertEquals(3, result); + } + + public void testMultiply() + { + Calculator cal = new Calculator(); + int result = cal.multiply(4, 2); + Assert.assertEquals(8,result); + } + + public void testDivide() + { + Calculator cal = new Calculator(); + int result = 0; + try { + result = cal.divide(10,5); + } catch (Exception e) { + e.printStackTrace(); + //我们期望result = cal.divide(10,5);正常执行;如果进入到catch中说明失败; + //所以我们加上fail。 + Assert.fail();//如果这行没有执行。说明这部分正确。 + } + Assert.assertEquals(2,result); + } + + public void testDivide2() + { + Throwable tx = null; + try + { + // Calculator cal = new Calculator(); + cal.divide(10,0); + //正常来讲cal.divide(10,0);已经抛出异常,之后的代码不会被执行。 + //我们也期望是这样的。所以说如果下面的Assert.fail();执行了。 + //我的的测试就失败了。 + Assert.fail();//当执行到这里测试失败,后面的代码将不被执行。 + } catch (Exception e) { + tx = e; + } + Assert.assertNotNull(tx); //断言tx不为空。也就是说肯定有异常。 + Assert.assertEquals(Exception.class,tx.getClass());//断言tx的类型为Exception类型 + Assert.assertEquals("除数不能为零", tx.getMessage()); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example_test/b/BAllTest.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example_test/b/BAllTest.java new file mode 100644 index 0000000000..a6691f1558 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example_test/b/BAllTest.java @@ -0,0 +1,16 @@ +package com.coderising.myood.litejunit.v2.example_test.b; + +import com.coderising.myood.litejunit.v2.Test; +import com.coderising.myood.litejunit.v2.TestSuite; + +/** + * Created by thomas_young on 17/9/2017. + */ +public class BAllTest { + public static Test suite() { + TestSuite suite = new TestSuite(); + suite.addTestSuite(HelloWorldTest.class); + suite.addTestSuite(ByebyeTest.class); + return suite; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example_test/b/ByebyeTest.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example_test/b/ByebyeTest.java new file mode 100644 index 0000000000..937cfd5ce4 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example_test/b/ByebyeTest.java @@ -0,0 +1,17 @@ +package com.coderising.myood.litejunit.v2.example_test.b; + +import com.coderising.myood.litejunit.v2.TestCase; +import com.coderising.myood.litejunit.v2.example.b.Byebye; + +/** + * Created by thomas_young on 17/9/2017. + */ +public class ByebyeTest extends TestCase { + public ByebyeTest(String name) { + super(name); + } + public void testSay(){ + Byebye bye = new Byebye(); + assertEquals("Byebye!", bye.Say()); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example_test/b/HelloWorldTest.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example_test/b/HelloWorldTest.java new file mode 100644 index 0000000000..892f85892a --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/example_test/b/HelloWorldTest.java @@ -0,0 +1,19 @@ +package com.coderising.myood.litejunit.v2.example_test.b; + +import com.coderising.myood.litejunit.v2.TestCase; +import com.coderising.myood.litejunit.v2.example.b.HelloWorld; + +/** + * Created by thomas_young on 17/9/2017. + */ +public class HelloWorldTest extends TestCase { + + public HelloWorldTest(String name) { + super(name); + } + + public void testSay(){ + HelloWorld hi = new HelloWorld(); + assertEquals("Hello,World1!", hi.Say()); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/extension/RepeatedTest.java b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/extension/RepeatedTest.java new file mode 100644 index 0000000000..3409a1ab60 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/litejunit/v2/extension/RepeatedTest.java @@ -0,0 +1,23 @@ +package com.coderising.myood.litejunit.v2.extension; + +import com.coderising.myood.litejunit.v2.Test; +import com.coderising.myood.litejunit.v2.TestResult; + +/** + * Created by thomas_young on 17/9/2017. + */ +public class RepeatedTest extends TestDecorate { + private int repeatedTimes; + public RepeatedTest(Test test, int repeatedTimes) { + super(test); + this.repeatedTimes = repeatedTimes; + } + @Override + public void run(TestResult tr) { + for (int i=0; i { + initPayJob(d); + payTransaction.execute(); + System.out.printf(DateUtil.toDateStr(d) + "*******************************\n"); + }); + // 查看Paycheck的在数据库中是否落表 + System.out.println(paycheckTable); + } + + private static void initPayJob(Date date) { + payTransaction = new PayTransaction(); + PayrollService payrollService = new PayrollService(); + payrollService.setEmployeeTable(employeeTable); + payrollService.setPaycheckTable(paycheckTable); + payTransaction.setDate(date); + payTransaction.setPayrollService(payrollService); + } + + private static void prepareData() { + // 创建数据库,插入员工数据 + payrollDataBase = new DataBase("payroll"); + employeeTable = new EmployeeTable(); + paycheckTable = new PaycheckTable(); + payrollDataBase.addTable(paycheckTable); + payrollDataBase.addTable(employeeTable); + + EmployeeTable.EmployeeBuilder employeeBuilder = new EmployeeTable.EmployeeBuilder(); + employeeBuilder + .id(1) + .name("yangkai") + .address("shanghai") + .emp_type("0") + .salary(10000) + .schedule_type("0") + .payment_type("2") + .affiliation_type("0") + .insert(employeeTable); + employeeBuilder.clear(); + employeeBuilder + .id(2) + .name("xiecantou") + .emp_type("2") + .address("changzhou") + .commission_rate(0.2) + .base_salary(5000) + .schedule_type("2") + .payment_type("0") + .affiliation_type("1") + .insert(employeeTable); + employeeBuilder.clear(); + employeeBuilder + .id(3) + .name("guzhelun") + .emp_type("1") + .address("xianggang") + .hourly_rate(500) + .schedule_type("1") + .payment_type("1") + .affiliation_type("1") + .insert(employeeTable); + + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/PayrollService.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/PayrollService.java new file mode 100644 index 0000000000..b9b5a636e1 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/PayrollService.java @@ -0,0 +1,164 @@ +package com.coderising.myood.payroll.my_payroll; + + +import com.coderising.myood.payroll.my_payroll.affiliantion.NonAffiliation; +import com.coderising.myood.payroll.my_payroll.affiliantion.UnionAffiliation; +import com.coderising.myood.payroll.my_payroll.database.EmployeeTable; +import com.coderising.myood.payroll.my_payroll.database.PaycheckTable; +import com.coderising.myood.payroll.my_payroll.domain.*; +import com.coderising.myood.payroll.my_payroll.paymentclassification.CommissionClassification; +import com.coderising.myood.payroll.my_payroll.paymentclassification.HourlyClassification; +import com.coderising.myood.payroll.my_payroll.paymentclassification.SalariedClassification; +import com.coderising.myood.payroll.my_payroll.paymentmethod.BankMethod; +import com.coderising.myood.payroll.my_payroll.paymentmethod.HoldMethod; +import com.coderising.myood.payroll.my_payroll.paymentmethod.PostOfficeMethod; +import com.coderising.myood.payroll.my_payroll.paymentschedule.BiWeeklySchedule; +import com.coderising.myood.payroll.my_payroll.paymentschedule.MonthlySchedule; +import com.coderising.myood.payroll.my_payroll.paymentschedule.WeeklySchedule; +import com.coderising.myood.payroll.my_payroll.util.DateUtil; +import com.coderising.myood.payroll.my_payroll.util.PayrollException; + +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Created by thomas_young on 17/9/2017. + */ +public class PayrollService { + private EmployeeTable employeeTable; + private PaycheckTable paycheckTable; + + public void savePaycheck(Paycheck pc) { + PaycheckTable.PaycheckBuilder pb = new PaycheckTable.PaycheckBuilder(); + pb.deductions(pc.getDeductions()) + .employee_id(pc.getEmployeeId()) + .gross_pay(pc.getGrossPay()) + .net_pay(pc.getNetPay()) + .pay_period_start(pc.getPayPeriodStart()) + .pay_period_end(pc.getPayPeriodEnd()) + .insert(paycheckTable); + } + + public List getAllEmployees() { + List> employeeList = employeeTable.getRows(); + return employeeList.stream() + .map(em -> { + Employee e = buildEmployee(em); + return e; + }) + .collect(Collectors.toList()); + } + + public boolean checkRepeatedPay(Paycheck pc) { + List> rows = paycheckTable.getRows(); + long repeatedNum = rows.stream() + .filter(m -> + (m.get("pay_period_end")).equals(pc.getPayPeriodEnd()) && m.get("employee_id").equals(pc.getEmployeeId()) + ) + .count(); + if (repeatedNum != 0) { + System.err.println((String.format("有%s条重复的发薪记录: ", repeatedNum) + +"employee_id: " + pc.getEmployeeId()+", payPeriodEnd: "+ DateUtil.toDateStr(pc.getPayPeriodEnd()))); + return false; + } + return true; + } + + public void setEmployeeTable(EmployeeTable employeeTable) { + this.employeeTable = employeeTable; + } + + public void setPaycheckTable(PaycheckTable paycheckTable) { + this.paycheckTable = paycheckTable; + } + + // ------------------------- private ---------------------------- + private Employee buildEmployee(Map em) { + Employee employee = new Employee((int) em.get("id"), (String) em.get("name"), (String) em.get("address")); + setClassification(employee, em); + setSchedule(employee, em); + setMethod(employee, em); + setAffiliation(employee, em); + return employee; + } + + private void setAffiliation(Employee employee, Map em) { + String affiliationType = (String) em.get("affiliation_type"); + Affiliation affiliation; + switch (affiliationType) { + case "0": + affiliation = new NonAffiliation(); + break; + case "1": + affiliation = new UnionAffiliation(300); + break; + default: + throw new PayrollException("无效支付类型"); + } + employee.setAffiliation(affiliation); + } + + private void setMethod(Employee employee, Map em) { + String paymentType = (String) em.get("payment_type"); + PaymentMethod pm; + switch (paymentType) { + case "0": + pm = new PostOfficeMethod(); + break; + case "1": + pm = new HoldMethod(); + break; + case "2": + pm = new BankMethod(); + break; + default: + throw new PayrollException("无效支付类型"); + } + employee.setPaymentMethod(pm); + } + + private void setSchedule(Employee employee, Map em) { + String scheduleType = (String) em.get("schedule_type"); + PaymentSchedule ps; + switch (scheduleType) { + case "0": + ps = new MonthlySchedule(); + break; + case "1": + ps = new WeeklySchedule(); + break; + case "2": + ps = new BiWeeklySchedule(); + break; + default: + throw new PayrollException("无效付薪日类型"); + } + employee.setSchedule(ps); + } + + private void setClassification(Employee employee, Map em) { + String empType = (String) em.get("emp_type"); + PaymentClassification pc; + switch (empType) { + case "0": + double salary = (double) em.get("salary"); + pc = new SalariedClassification(salary); + break; + case "1": + double hourlyRate = (double) em.get("hourly_rate"); + pc = new HourlyClassification(hourlyRate); + break; + case "2": + double baseSalary = (double) em.get("base_salary"); + double commissionRate = (double) em.get("commission_rate"); + pc = new CommissionClassification(baseSalary, commissionRate); + break; + default: + throw new PayrollException("无效工资计算类型"); + } + employee.setClassification(pc); + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/README.md b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/README.md new file mode 100644 index 0000000000..d0d65876b3 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/README.md @@ -0,0 +1,18 @@ +需求: +该系统由一个公司数据库以及和雇员相关的数据(例如工作时间卡)组成,系统需要准时地按照规则给员工支付薪水,同时,必须从薪水中扣除各种扣款 + +有些雇员是钟点工, 会按照他们雇员记录中每小时的报酬字段的值对他们进行支付,他们每天提交工作时间卡,其中记录了日期以及工作小时数,如果每天工作超过8小时,按1.5倍进行支付。 每周五对他们进行支付。 + +有些雇员完全以月薪进行支付,每个月的最后一个工作日对他们进行支付,在他们的雇员记录中有个月薪字段 + +同时,对于一些带薪的雇员,会根据他们的销售情况,支付给他们一定数量的佣金,他们会提交销售凭条,其中记录了销售的日期和数量。在他们的雇员记录中有一个酬金报酬字段。 每隔一周的周五对他们进行支付。 + +请运行JobInvoker来查看薪水发放情况 + +注: +1. 定时任务在PayTransaction、PayrollService里面 +2. 测试驱动在JobInvoker里面 +3. 发薪逻辑考虑了不能对同一个员工重复发薪 +4. 为了模拟数据库行为, 专门见了Table类和DataBase类, 用起来还不错 +5. 测试用例在com.coderising.myood.payroll.my_payroll,后修改请保证测试用例的通过 +6. 虽然测试用例已经覆盖了"时间卡"、"销售凭条"、"协会服务费",但是JobInvoker以及相关数据准备的代码中还缺乏TimeCard, aleReceipt和ServiceCharge的数据, 因此建议后续再添加几张表以及相关逻辑 \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/affiliantion/NonAffiliation.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/affiliantion/NonAffiliation.java new file mode 100644 index 0000000000..95b4121caa --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/affiliantion/NonAffiliation.java @@ -0,0 +1,16 @@ +package com.coderising.myood.payroll.my_payroll.affiliantion; + + +import com.coderising.myood.payroll.my_payroll.domain.Affiliation; +import com.coderising.myood.payroll.my_payroll.domain.Paycheck; + +public class NonAffiliation implements Affiliation { + + public NonAffiliation() { + } + + public double calculateDeductions(Paycheck pc){ + return 0.0d; + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/affiliantion/ServiseCharge.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/affiliantion/ServiseCharge.java new file mode 100644 index 0000000000..9baac4f585 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/affiliantion/ServiseCharge.java @@ -0,0 +1,26 @@ +package com.coderising.myood.payroll.my_payroll.affiliantion; + +import com.coderising.myood.payroll.my_payroll.util.DateUtil; + +import java.util.Date; + +/** + * Created by thomas_young on 16/9/2017. + */ +public class ServiseCharge { + private Date date; + private double amount; + + public ServiseCharge(String dateStr, double amount) { + this.date = DateUtil.parseDate(dateStr); + this.amount = amount; + } + + public Date getDate() { + return date; + } + + public double getAmount() { + return amount; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/affiliantion/UnionAffiliation.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/affiliantion/UnionAffiliation.java new file mode 100644 index 0000000000..6034bd0522 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/affiliantion/UnionAffiliation.java @@ -0,0 +1,36 @@ +package com.coderising.myood.payroll.my_payroll.affiliantion; + + +import com.coderising.myood.payroll.my_payroll.domain.Affiliation; +import com.coderising.myood.payroll.my_payroll.domain.Paycheck; +import com.coderising.myood.payroll.my_payroll.util.DateUtil; + +import java.util.LinkedList; +import java.util.List; + +public class UnionAffiliation implements Affiliation { + private List serviseCharges; + private double weeklyDue; + + public UnionAffiliation(double weeklyDue) { + this.weeklyDue = weeklyDue; + serviseCharges = new LinkedList<>(); + } + + @Override + public double calculateDeductions(Paycheck pc) { + double totalCharge = serviseCharges.stream() + .filter(s -> DateUtil.between(s.getDate(), pc.getPayPeriodStart(), pc.getPayPeriodEnd())) + .map(s -> s.getAmount()) + .reduce(0d, Double::sum); + double totalDue = weeklyDue * DateUtil.dateBetween(pc.getPayPeriodStart(), pc.getPayPeriodEnd()) + .filter(d -> DateUtil.isFriday(d)) + .count(); + return totalCharge + totalDue; + } + + public void addServiceCharge(ServiseCharge serviseCharge) { + this.serviseCharges.add(serviseCharge); + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/database/AbstractTable.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/database/AbstractTable.java new file mode 100644 index 0000000000..108112971e --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/database/AbstractTable.java @@ -0,0 +1,41 @@ +package com.coderising.myood.payroll.my_payroll.database; + +import java.util.*; + +/** + * Created by thomas_young on 16/9/2017. + */ +public abstract class AbstractTable implements Table { + private String name; + protected List> rows = new LinkedList<>(); + + public String getName() { + return name; + } + + // 不考虑唯一键问题 + public void addRow(Map row) { + Map cloneRow = new HashMap<>(); + cloneRow.putAll(row); + rows.add(cloneRow); + } + + public List> getRows() { + return rows; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + StringBuilder ret = new StringBuilder(); + ret.append("table name: ") + .append(name) + .append("\n") + .append(rows.toString()); + return ret.toString(); + } +} + diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/database/DataBase.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/database/DataBase.java new file mode 100644 index 0000000000..54c3ee7866 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/database/DataBase.java @@ -0,0 +1,60 @@ +package com.coderising.myood.payroll.my_payroll.database; + + +import javax.xml.crypto.Data; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; + +/** + * Created by thomas_young on 16/9/2017. + */ +public class DataBase { + private String name; + private List tables = new LinkedList<>(); + + public DataBase(String name) { + this.name = name; + } + + public boolean addTable(Table table) { + if (!tables.stream() + .map(Table::getName) + .collect(Collectors.toList()) + .contains(table.getName())) { + tables.add(table); + return true; + } + return false; + } + + public Table getTable(String name) { + return tables.stream() + .filter(t -> name.equals(t.getName())) + .findFirst() + .orElse(null); + } + + public boolean drop(String name) { + Table table = tables + .stream() + .filter(t -> name.equals(t.getName())) + .findFirst() + .orElse(null); + if (table != null) { + tables.remove(table); + return true; + } else { + return false; + } + } + + @Override + public String toString() { + return "DataBase{" + + "database name='" + name + "', " + + "\n" + + "tables=" + tables + + '}'; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/database/EmployeeTable.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/database/EmployeeTable.java new file mode 100644 index 0000000000..91e57102fb --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/database/EmployeeTable.java @@ -0,0 +1,111 @@ +package com.coderising.myood.payroll.my_payroll.database; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by thomas_young on 16/9/2017. + */ +public class EmployeeTable extends AbstractTable { + public EmployeeTable() { + setName("Employee"); + } + + public static class EmployeeBuilder { + private Map row; + + public EmployeeBuilder() { + row = new HashMap<>(); + } + + public EmployeeBuilder id(int id) { + row.put("id", id); + return this; + } + + public EmployeeBuilder name(String name) { + row.put("name", name); + return this; + } + + public EmployeeBuilder address(String address) { + row.put("address", address); + return this; + } + + /** + * 员工类型 + * @param emp_type "0": salary, "1": hourly, "2": commission + * @return + */ + public EmployeeBuilder emp_type(String emp_type) { + row.put("emp_type", emp_type); + return this; + } + + public EmployeeBuilder hourly_rate(double hourly_rate) { + row.put("hourly_rate", hourly_rate); + return this; + } + + public EmployeeBuilder salary(double salary) { + row.put("salary", salary); + return this; + } + + /** + * 销售底薪 + * @param base_salary commission base salary + * @return + */ + public EmployeeBuilder base_salary(double base_salary) { + row.put("base_salary", base_salary); + return this; + } + + public EmployeeBuilder commission_rate(double commission_rate) { + row.put("commission_rate", commission_rate); + return this; + } + + /** + * 发薪日类型 + * @param schedule_type "0": monthly, "1": weekly, "2": double weekly + * @return + */ + public EmployeeBuilder schedule_type(String schedule_type) { + row.put("schedule_type", schedule_type); + return this; + } + + /** + * 支付方式类型 + * @param payment_type "0": post office, "1": hold, "2": bank + * @return + */ + public EmployeeBuilder payment_type(String payment_type) { + row.put("payment_type", payment_type); + return this; + } + + /** + * 是否参加协会 + * @param affiliation_type "0": 未参加, "1": 参加 + * @return + */ + public EmployeeBuilder affiliation_type(String affiliation_type) { + row.put("affiliation_type", affiliation_type); + return this; + } + + public void clear() { + row.clear(); + } + + public void insert(EmployeeTable employeeTable) { + employeeTable.addRow(row); + } + + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/database/PaycheckTable.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/database/PaycheckTable.java new file mode 100644 index 0000000000..959da58ab6 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/database/PaycheckTable.java @@ -0,0 +1,62 @@ +package com.coderising.myood.payroll.my_payroll.database; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +/** + * Created by thomas_young on 17/9/2017. + */ +public class PaycheckTable extends AbstractTable { + public PaycheckTable() { + setName("Paycheck"); + } + + public static class PaycheckBuilder { + private Map row; + + public PaycheckBuilder() { + row = new HashMap<>(); + } + + public PaycheckBuilder pay_period_start(Date pay_period_start) { + row.put("pay_period_start", pay_period_start); + return this; + } + + public PaycheckBuilder pay_period_end(Date pay_period_end) { + row.put("pay_period_end", pay_period_end); + return this; + } + + public PaycheckBuilder gross_pay(double gross_pay) { + row.put("gross_pay", gross_pay); + return this; + } + + public PaycheckBuilder net_pay(double net_pay) { + row.put("net_pay", net_pay); + return this; + } + + public PaycheckBuilder employee_id(int employee_id) { + row.put("employee_id", employee_id); + return this; + } + + public PaycheckBuilder deductions(double deductions) { + row.put("deductions", deductions); + return this; + } + + public void clear() { + row.clear(); + } + + public void insert(PaycheckTable paycheckTable) { + paycheckTable.addRow(row); + } + + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/database/Table.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/database/Table.java new file mode 100644 index 0000000000..27e7ed3e38 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/database/Table.java @@ -0,0 +1,13 @@ +package com.coderising.myood.payroll.my_payroll.database; + +import java.util.List; +import java.util.Map; + +/** + * Created by thomas_young on 16/9/2017. + */ +public interface Table { + String getName(); + List> getRows(); + void addRow(Map row); +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/Affiliation.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/Affiliation.java new file mode 100644 index 0000000000..a32b72282c --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/Affiliation.java @@ -0,0 +1,5 @@ +package com.coderising.myood.payroll.my_payroll.domain; + +public interface Affiliation { + double calculateDeductions(Paycheck pc); +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/Employee.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/Employee.java new file mode 100644 index 0000000000..27511650a6 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/Employee.java @@ -0,0 +1,92 @@ +package com.coderising.myood.payroll.my_payroll.domain; + +import java.util.Date; + +public class Employee { + int id; + String name; + String address; + Affiliation affiliation; + + + PaymentClassification classification; + PaymentSchedule schedule; + PaymentMethod paymentMethod; + + public Employee(int id, String name, String address){ + this.id = id; + this.name = name; + this.address = address; + } + public boolean isPayDay(Date d) { + return schedule.isPayDate(d); + } + + public Date getPayPeriodStart(Date d) { + return schedule.getPayPeriodStartDate(d); + } + + public void payDay(Paycheck pc){ + double grossPay = classification.calculatePay(pc); + pc.setGrossPay(grossPay); + double deductions = affiliation.calculateDeductions(pc); + pc.setDeductions(deductions); + pc.setNetPay(grossPay - deductions); + paymentMethod.pay(pc); + } + + public void setClassification(PaymentClassification classification) { + this.classification = classification; + } + public void setSchedule(PaymentSchedule schedule) { + this.schedule = schedule; + } + public void setPaymentMethod(PaymentMethod paymentMethod) { + this.paymentMethod = paymentMethod; + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public String getAddress() { + return address; + } + + public Affiliation getAffiliation() { + return affiliation; + } + + public PaymentClassification getClassification() { + return classification; + } + + public PaymentSchedule getSchedule() { + return schedule; + } + + public PaymentMethod getPaymentMethod() { + return paymentMethod; + } + + public void setId(int id) { + this.id = id; + } + + public void setName(String name) { + this.name = name; + } + + public void setAddress(String address) { + this.address = address; + } + + public void setAffiliation(Affiliation affiliation) { + this.affiliation = affiliation; + } +} + diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/PayTransaction.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/PayTransaction.java new file mode 100644 index 0000000000..4e592ffb75 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/PayTransaction.java @@ -0,0 +1,38 @@ +package com.coderising.myood.payroll.my_payroll.domain; + +import com.coderising.myood.payroll.my_payroll.PayrollService; + +import java.util.Date; +import java.util.List; + +/** + * Created by thomas_young on 17/9/2017. + * 这是一个定时任务 + */ +public class PayTransaction { + private Date date; + private PayrollService payrollService; + + public void execute(){ + List employees = payrollService.getAllEmployees(); + for(Employee e : employees){ + if(e.isPayDay(date)){ + + Paycheck pc = new Paycheck(e.getId(), e.getPayPeriodStart(date), date); + if (!payrollService.checkRepeatedPay(pc)) { + continue; + } + e.payDay(pc); + payrollService.savePaycheck(pc); + } + } + } + + public void setDate(Date date) { + this.date = date; + } + + public void setPayrollService(PayrollService payrollService) { + this.payrollService = payrollService; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/Paycheck.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/Paycheck.java new file mode 100644 index 0000000000..695a05af7b --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/Paycheck.java @@ -0,0 +1,78 @@ +package com.coderising.myood.payroll.my_payroll.domain; + +import java.util.Date; + +public class Paycheck { + private Date payPeriodStart; + private Date payPeriodEnd; + private double grossPay; + private double netPay; + private double deductions; + private int employeeId; + + public Paycheck(int employeeId, Date payPeriodStart, Date payPeriodEnd){ + this.payPeriodStart = payPeriodStart; + this.payPeriodEnd = payPeriodEnd; + this.employeeId = employeeId; + } + + public Date getPayPeriodStart() { + return payPeriodStart; + } + + public void setPayPeriodStart(Date payPeriodStart) { + this.payPeriodStart = payPeriodStart; + } + + public Date getPayPeriodEnd() { + return payPeriodEnd; + } + + public void setPayPeriodEnd(Date payPeriodEnd) { + this.payPeriodEnd = payPeriodEnd; + } + + public double getGrossPay() { + return grossPay; + } + + public double getNetPay() { + return netPay; + } + + public double getDeductions() { + return deductions; + } + + public int getEmployeeId() { + return employeeId; + } + + public void setEmployeeId(int employeeId) { + this.employeeId = employeeId; + } + + public void setGrossPay(double grossPay) { + this.grossPay = grossPay; + + } + public void setDeductions(double deductions) { + this.deductions = deductions; + } + + public void setNetPay(double netPay){ + this.netPay = netPay; + } + + @Override + public String toString() { + return "Paycheck{" + + "payPeriodStart=" + payPeriodStart + + ", payPeriodEnd=" + payPeriodEnd + + ", grossPay=" + grossPay + + ", netPay=" + netPay + + ", deductions=" + deductions + + ", employeeId=" + employeeId + + '}'; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/PaymentClassification.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/PaymentClassification.java new file mode 100644 index 0000000000..8d939a0555 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/PaymentClassification.java @@ -0,0 +1,5 @@ +package com.coderising.myood.payroll.my_payroll.domain; + +public interface PaymentClassification { + double calculatePay(Paycheck pc); +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/PaymentMethod.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/PaymentMethod.java new file mode 100644 index 0000000000..c30e4a439a --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/PaymentMethod.java @@ -0,0 +1,5 @@ +package com.coderising.myood.payroll.my_payroll.domain; + +public interface PaymentMethod { + void pay(Paycheck pc); +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/PaymentSchedule.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/PaymentSchedule.java new file mode 100644 index 0000000000..5fce609053 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/PaymentSchedule.java @@ -0,0 +1,8 @@ +package com.coderising.myood.payroll.my_payroll.domain; + +import java.util.Date; + +public interface PaymentSchedule { + public boolean isPayDate(Date date); + public Date getPayPeriodStartDate(Date payPeriodEndDate); +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/SalesReceipt.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/SalesReceipt.java new file mode 100644 index 0000000000..0c7b8f5803 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/domain/SalesReceipt.java @@ -0,0 +1,14 @@ +package com.coderising.myood.payroll.my_payroll.domain; + +import java.util.Date; + +public class SalesReceipt { + private Date saleDate; + private double amount; + public Date getSaleDate() { + return saleDate; + } + public double getAmount() { + return amount; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentclassification/CommissionClassification.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentclassification/CommissionClassification.java new file mode 100644 index 0000000000..a02428f771 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentclassification/CommissionClassification.java @@ -0,0 +1,42 @@ +package com.coderising.myood.payroll.my_payroll.paymentclassification; + +import com.coderising.myood.payroll.my_payroll.domain.Paycheck; +import com.coderising.myood.payroll.my_payroll.domain.PaymentClassification; +import com.coderising.myood.payroll.my_payroll.util.DateUtil; +import com.sun.istack.internal.NotNull; + +import java.util.LinkedList; +import java.util.List; + +/** + * Created by thomas_young on 16/9/2017. + * 销售计算工资 + */ +public class CommissionClassification implements PaymentClassification { + private double baseSalary; + private double commissionRate; + private List salesReceipts; + + public CommissionClassification(double baseSalary, double commissionRate) { + this.baseSalary = baseSalary; + this.commissionRate = commissionRate; + salesReceipts = new LinkedList<>(); + } + + @Override + public double calculatePay(Paycheck pc) { + if (pc == null) return baseSalary; + return salesReceipts.stream() + .filter(s -> DateUtil.between(s.getSaleDate(), pc.getPayPeriodStart(), pc.getPayPeriodEnd())) + .map(this::calculateSalePay) + .reduce(baseSalary, Double::sum); + } + + public void addSalesReceipt(SalesReceipt salesReceipt) { + this.salesReceipts.add(salesReceipt); + } + + private double calculateSalePay(SalesReceipt salesReceipt) { + return salesReceipt.getAmount() * commissionRate; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentclassification/HourlyClassification.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentclassification/HourlyClassification.java new file mode 100644 index 0000000000..f079b7c7d6 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentclassification/HourlyClassification.java @@ -0,0 +1,49 @@ +package com.coderising.myood.payroll.my_payroll.paymentclassification; + +import com.coderising.myood.payroll.my_payroll.domain.Paycheck; +import com.coderising.myood.payroll.my_payroll.domain.PaymentClassification; +import com.coderising.myood.payroll.my_payroll.util.DateUtil; + +import java.util.LinkedList; +import java.util.List; + +/** + * Created by thomas_young on 16/9/2017. + * 临时工工资计算 + */ +public class HourlyClassification implements PaymentClassification { + private int MAX_HOURS = 8; + private double EXTRA_SCALE= 1.5; + private double hourlyRate; + private List timeCards; + + public HourlyClassification(double hourlyRate) { + this.hourlyRate = hourlyRate; + timeCards = new LinkedList<>(); + } + + @Override + public double calculatePay(Paycheck pc) { + double totalPay = timeCards.stream() + .filter(t -> DateUtil.between(t.getDate(), pc.getPayPeriodStart(), pc.getPayPeriodEnd())) + .map(this::calulateTimeCardPay) + .reduce(0d, Double::sum); + return totalPay; + } + + public void addTimeCard(TimeCard timeCard) { + timeCards.add(timeCard); + } + + public List getTimeCards() { + return timeCards; + } + + private double calulateTimeCardPay(TimeCard timeCard) { + if (timeCard.getHours() <= MAX_HOURS) { + return hourlyRate * timeCard.getHours(); + } else { + return hourlyRate * MAX_HOURS + EXTRA_SCALE * hourlyRate * (timeCard.getHours() - MAX_HOURS); + } + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentclassification/SalariedClassification.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentclassification/SalariedClassification.java new file mode 100644 index 0000000000..a89128714f --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentclassification/SalariedClassification.java @@ -0,0 +1,29 @@ +package com.coderising.myood.payroll.my_payroll.paymentclassification; + +import com.coderising.myood.payroll.my_payroll.domain.Paycheck; +import com.coderising.myood.payroll.my_payroll.domain.PaymentClassification; + +/** + * Created by thomas_young on 16/9/2017. + * 雇员工资计算 + */ +public class SalariedClassification implements PaymentClassification { + private double salary; // 月工资 + + public SalariedClassification(double salary) { + this.salary = salary; + } + + @Override + public double calculatePay(Paycheck pc) { + return salary; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentclassification/SalesReceipt.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentclassification/SalesReceipt.java new file mode 100644 index 0000000000..a54636c861 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentclassification/SalesReceipt.java @@ -0,0 +1,22 @@ +package com.coderising.myood.payroll.my_payroll.paymentclassification; + +import com.coderising.myood.payroll.my_payroll.util.DateUtil; + +import java.util.Date; + +public class SalesReceipt { + private Date saleDate; + private double amount; + + public SalesReceipt(String dateStr, double amount) { + this.saleDate = DateUtil.parseDate(dateStr); + this.amount = amount; + } + + public Date getSaleDate() { + return saleDate; + } + public double getAmount() { + return amount; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentclassification/TimeCard.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentclassification/TimeCard.java new file mode 100644 index 0000000000..54a4227d75 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentclassification/TimeCard.java @@ -0,0 +1,37 @@ +package com.coderising.myood.payroll.my_payroll.paymentclassification; + + +import com.coderising.myood.payroll.my_payroll.util.DateUtil; + +import java.util.Date; + +/** + * Created by thomas_young on 16/9/2017. + */ +public class TimeCard { + + + private Date date; + private int hours; + + public TimeCard(String dateStr, int hours) { + this.date = DateUtil.parseDate(dateStr); + this.hours = hours; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public int getHours() { + return hours; + } + + public void setHours(int hours) { + this.hours = hours; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentmethod/BankMethod.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentmethod/BankMethod.java new file mode 100644 index 0000000000..f61d4d39c3 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentmethod/BankMethod.java @@ -0,0 +1,23 @@ +package com.coderising.myood.payroll.my_payroll.paymentmethod; + +import com.coderising.myood.payroll.my_payroll.domain.Paycheck; +import com.coderising.myood.payroll.my_payroll.domain.PaymentMethod; + +import java.text.SimpleDateFormat; + +/** + * Created by thomas_young on 16/9/2017. + */ +public class BankMethod implements PaymentMethod { + @Override + public void pay(Paycheck pc) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + StringBuilder desp = new StringBuilder(); + desp.append("银行入账:\n") + .append("employee_id: ").append(pc.getEmployeeId()) + .append(", 金额: ").append(pc.getNetPay()) + .append(", 区间: ").append(sdf.format(pc.getPayPeriodStart())) + .append("~").append(sdf.format(pc.getPayPeriodEnd())); + System.out.println(desp.toString()); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentmethod/HoldMethod.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentmethod/HoldMethod.java new file mode 100644 index 0000000000..895095e084 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentmethod/HoldMethod.java @@ -0,0 +1,24 @@ +package com.coderising.myood.payroll.my_payroll.paymentmethod; + +import com.coderising.myood.payroll.my_payroll.domain.Paycheck; +import com.coderising.myood.payroll.my_payroll.domain.PaymentMethod; + +import java.text.SimpleDateFormat; + +/** + * Created by thomas_young on 16/9/2017. + * 把钱发到财务那里,所示支取 + */ +public class HoldMethod implements PaymentMethod { + @Override + public void pay(Paycheck pc) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + StringBuilder desp = new StringBuilder(); + desp.append("财务入账:\n") + .append("employee_id: ").append(pc.getEmployeeId()) + .append(", 金额: ").append(pc.getNetPay()) + .append(", 区间: ").append(sdf.format(pc.getPayPeriodStart())) + .append("~").append(sdf.format(pc.getPayPeriodEnd())); + System.out.println(desp.toString()); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentmethod/PostOfficeMethod.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentmethod/PostOfficeMethod.java new file mode 100644 index 0000000000..56bc412351 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentmethod/PostOfficeMethod.java @@ -0,0 +1,23 @@ +package com.coderising.myood.payroll.my_payroll.paymentmethod; + +import com.coderising.myood.payroll.my_payroll.domain.Paycheck; +import com.coderising.myood.payroll.my_payroll.domain.PaymentMethod; + +import java.text.SimpleDateFormat; + +/** + * Created by thomas_young on 16/9/2017. + */ +public class PostOfficeMethod implements PaymentMethod { + @Override + public void pay(Paycheck pc) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + StringBuilder desp = new StringBuilder(); + desp.append("邮局入账:\n") + .append("employee_id: ").append(pc.getEmployeeId()) + .append(", 金额: ").append(pc.getNetPay()) + .append(", 区间: ").append(sdf.format(pc.getPayPeriodStart())) + .append("~").append(sdf.format(pc.getPayPeriodEnd())); + System.out.println(desp.toString()); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentschedule/BiWeeklySchedule.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentschedule/BiWeeklySchedule.java new file mode 100644 index 0000000000..a6e8cd99f0 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentschedule/BiWeeklySchedule.java @@ -0,0 +1,23 @@ +package com.coderising.myood.payroll.my_payroll.paymentschedule; + +import com.coderising.myood.payroll.my_payroll.domain.PaymentSchedule; +import com.coderising.myood.payroll.my_payroll.util.DateUtil; + +import java.util.Date; + +/** + * Created by thomas_young on 16/9/2017. + */ +public class BiWeeklySchedule implements PaymentSchedule { + private static Date FIRST_PAYABLE_FRIDAY = DateUtil.parseDate("2017-6-2"); + @Override + public boolean isPayDate(Date date) { + long interval = DateUtil.getDaysBetween(FIRST_PAYABLE_FRIDAY, date); + return interval % 14 == 0; + } + + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.add(payPeriodEndDate, -13); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentschedule/MonthlySchedule.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentschedule/MonthlySchedule.java new file mode 100644 index 0000000000..2a12380950 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentschedule/MonthlySchedule.java @@ -0,0 +1,22 @@ +package com.coderising.myood.payroll.my_payroll.paymentschedule; + +import com.coderising.myood.payroll.my_payroll.domain.PaymentSchedule; +import com.coderising.myood.payroll.my_payroll.util.DateUtil; + +import java.util.Date; + +/** + * Created by thomas_young on 16/9/2017. + */ +public class MonthlySchedule implements PaymentSchedule { + + @Override + public boolean isPayDate(Date date) { + return DateUtil.isLastDayOfMonth(date); + } + + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.getFirstDay(payPeriodEndDate); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentschedule/WeeklySchedule.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentschedule/WeeklySchedule.java new file mode 100644 index 0000000000..76b651b096 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/paymentschedule/WeeklySchedule.java @@ -0,0 +1,21 @@ +package com.coderising.myood.payroll.my_payroll.paymentschedule; + +import com.coderising.myood.payroll.my_payroll.domain.PaymentSchedule; +import com.coderising.myood.payroll.my_payroll.util.DateUtil; + +import java.util.Date; + +/** + * Created by thomas_young on 16/9/2017. + */ +public class WeeklySchedule implements PaymentSchedule { + @Override + public boolean isPayDate(Date date) { + return DateUtil.isFriday(date); + } + + @Override + public Date getPayPeriodStartDate(Date payPeriodEndDate) { + return DateUtil.add(payPeriodEndDate, -6); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/util/DateUtil.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/util/DateUtil.java new file mode 100644 index 0000000000..c20616b36f --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/util/DateUtil.java @@ -0,0 +1,131 @@ +package com.coderising.myood.payroll.my_payroll.util; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.temporal.ChronoUnit; +import java.util.*; +import java.util.stream.Stream; + +public class DateUtil { + public static long getDaysBetween(Date d1, Date d2){ + + return (d2.getTime() - d1.getTime())/(24*60*60*1000); + } + + public static Date parseDate(String txtDate){ + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); + try { + return sdf.parse(txtDate); + } catch (ParseException e) { + e.printStackTrace(); + return null; + } + } + + public static String toDateStr(Date date) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + return sdf.format(date); + } + + public static boolean isFriday(Date d){ + Calendar calendar = Calendar.getInstance(); + calendar.setTime(d); + return calendar.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY; + } + + public static Date add(Date d, int days){ + Calendar calendar = Calendar.getInstance(); + calendar.setTime(d); + calendar.add(Calendar.DATE, days); + return calendar.getTime(); + } + + public static boolean isLastDayOfMonth(Date d){ + Calendar calendar=Calendar.getInstance(); + calendar.setTime(d); + return calendar.get(Calendar.DATE)==calendar.getActualMaximum(Calendar.DAY_OF_MONTH); + } + + public static Date getFirstDay(Date d){ + Calendar calendar=Calendar.getInstance(); + calendar.setTime(d); + int day = calendar.get(Calendar.DATE); + calendar.add(Calendar.DATE, -(day-1)); + return calendar.getTime(); + } + + public static Date asDate(LocalDate localDate) { + return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()); + } + + public static Date asDate(LocalDateTime localDateTime) { + return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); + } + + public static LocalDate asLocalDate(Date date) { + return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate(); + } + + public static LocalDateTime asLocalDateTime(Date date) { + return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime(); + } + + /** + * 闭区间[d1, d2] + * @param d1 + * @param d2 + * @return + */ + public static Stream dateBetween(Date d1, Date d2) { + DateRange dr = new DateRange(asLocalDate(d1), asLocalDate(d2)); + return dr.stream().map(ld -> asDate(ld)); + } + + public static class DateRange implements Iterable { + + private final LocalDate startDate; + private final LocalDate endDate; + + public DateRange(LocalDate startDate, LocalDate endDate) { + //check that range is valid (null, start < end) + this.startDate = startDate; + this.endDate = endDate; + } + + @Override + public Iterator iterator() { + return stream().iterator(); + } + + public Stream stream() { + return Stream.iterate(startDate, d -> d.plusDays(1)) + .limit(ChronoUnit.DAYS.between(startDate, endDate) + 1); + } + + public List toList() { //could also be built from the stream() method + List dates = new ArrayList<>(); + for (LocalDate d = startDate; !d.isAfter(endDate); d = d.plusDays(1)) { + dates.add(d); + } + return dates; + } + } + + public static boolean between(Date d, Date date1, Date date2){ + return (d.after(date1) && d.before(date2)) || d.equals(date1) || d.equals(date2); + } + + public static void main(String [] args) throws Exception{ + System.out.println(DateUtil.isLastDayOfMonth(DateUtil.parseDate("2017-6-29"))); + + System.out.println(DateUtil.getFirstDay(DateUtil.parseDate("2017-6-30"))); + System.out.println("**************"); + dateBetween(parseDate("2017-06-02"), parseDate("2017-06-05")).forEach(System.out::println); + } + + +} diff --git a/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/util/PayrollException.java b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/util/PayrollException.java new file mode 100644 index 0000000000..87adace874 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/payroll/my_payroll/util/PayrollException.java @@ -0,0 +1,11 @@ +package com.coderising.myood.payroll.my_payroll.util; + + +/** + * Created by thomas_young on 17/9/2017. + */ +public class PayrollException extends RuntimeException { + public PayrollException(String msg) { + super(msg); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/Configuration.java b/students/812350401/src/main/java/com/coderising/myood/srp/Configuration.java new file mode 100644 index 0000000000..ff38f5a1b3 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.myood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/ConfigurationKeys.java b/students/812350401/src/main/java/com/coderising/myood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..0ec546beee --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.myood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/DBUtil.java b/students/812350401/src/main/java/com/coderising/myood/srp/DBUtil.java new file mode 100644 index 0000000000..bf0db8a811 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.myood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com" + i); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/EmailParam.java b/students/812350401/src/main/java/com/coderising/myood/srp/EmailParam.java new file mode 100644 index 0000000000..71b5d30b40 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/EmailParam.java @@ -0,0 +1,49 @@ +package com.coderising.myood.srp; + + +/** + * Created by thomas_young on 20/6/2017. + */ +public class EmailParam { + private String smtpHost = null; + private String altSmtpHost = null; + private static Configuration config = new Configuration(); + private String fromAddress = null; + + protected void setFromAddress() + { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + private void loadEmailConfig() { + setFromAddress(); + setSMTPHost(); + setAltSMTPHost(); + } + + public EmailParam() { + loadEmailConfig(); + } + + public String getSmtpHost() { + return smtpHost; + } + + private void setSMTPHost() + { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public String getFromAddress() { + return fromAddress; + } + + private void setAltSMTPHost() + { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/MailService.java b/students/812350401/src/main/java/com/coderising/myood/srp/MailService.java new file mode 100644 index 0000000000..ec5809ba74 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/MailService.java @@ -0,0 +1,116 @@ +package com.coderising.myood.srp; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +/** + * Created by thomas_young on 20/6/2017. + */ +public class MailService { + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + private static String fromAddress; + private static EmailParam emailParam; + + static { + emailParam = new EmailParam(); + fromAddress = emailParam.getFromAddress(); + } + + public void sendMails(boolean debug) throws Exception { + ProductInfo productInfo = new ProductInfo(); + UserDao userDao = new UserDao(); + List userInfos = userDao.loadMailingList(productInfo.getProductID()); + List mailInfos = convertToMails(userInfos, productInfo); + System.out.println("开始发送邮件"); + for (MailInfo mail: mailInfos) { + sendOneMail(mail, debug); + } + + } + + private void sendOneMail(MailInfo mail, boolean debug) { + try { + MailUtil.sendEmail( + mail.getToAddress(), + fromAddress, + mail.getSubject(), + mail.getMessage(), + emailParam.getSmtpHost(), debug); + } catch (Exception e) { + + try { + MailUtil.sendEmail(mail.getToAddress(), + fromAddress, + mail.getSubject(), + mail.getMessage(), + emailParam.getAltSmtpHost(), + debug); + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + public static class MailInfo { + + public String getFromAddress() { + return fromAddress; + } + + public String getToAddress() { + return toAddress; + } + + public String getSubject() { + return subject; + } + + public String getMessage() { + return message; + } + + private String fromAddress = null; + private String toAddress = null; + private String subject = null; + private String message = null; + + + public MailInfo(String fromAddress, String toAddress, String subject, String message) { + this.fromAddress = fromAddress; + this.toAddress = toAddress; + this.subject = subject; + this.message = message; + } + } + + private List convertToMails(List userInfos, ProductInfo productInfo) throws IOException { + List mailInfos = new LinkedList<>(); + if (userInfos != null) { + Iterator iter = userInfos.iterator(); + while (iter.hasNext()) { + MailInfo mailInfo = configureEMail((HashMap) iter.next(), productInfo); + if (mailInfo != null) { + mailInfos.add(mailInfo); + } + } + } + return mailInfos; + } + + private MailInfo configureEMail(HashMap userInfo, ProductInfo productInfo) throws IOException + { + String toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) { + String name = (String) userInfo.get(NAME_KEY); + String subject = "您关注的产品降价了"; + String message = "尊敬的 "+name+", 您关注的产品 " + productInfo.getProductDesc() + " 降价了,欢迎购买!" ; + return new MailInfo(fromAddress, toAddress, subject, message); + } + return null; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/MailUtil.java b/students/812350401/src/main/java/com/coderising/myood/srp/MailUtil.java new file mode 100644 index 0000000000..25a0f64583 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.myood.srp; + + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + } + + +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/ProductInfo.java b/students/812350401/src/main/java/com/coderising/myood/srp/ProductInfo.java new file mode 100644 index 0000000000..1cca0338ec --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/ProductInfo.java @@ -0,0 +1,65 @@ +package com.coderising.myood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +/** + * Created by thomas_young on 20/6/2017. + */ +public class ProductInfo { + private String productID = null; + private String productDesc = null; + + private static File f = new File("/Users/thomas_young/Documents/code/liuxintraining/coding2017/students/812350401/src/main/java/com/coderising/myood/srp/product_promotion.txt"); + + public ProductInfo() { + try { + readFileSetProperty(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * 读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + * @throws IOException + */ + private void readFileSetProperty() throws IOException + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(f)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/PromotionMail.java b/students/812350401/src/main/java/com/coderising/myood/srp/PromotionMail.java new file mode 100644 index 0000000000..b6ecd6fc41 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/PromotionMail.java @@ -0,0 +1,8 @@ +package com.coderising.myood.srp; + +public class PromotionMail { + public static void main(String[] args) throws Exception { + MailService mailService = new MailService(); + mailService.sendMails(true); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/UserDao.java b/students/812350401/src/main/java/com/coderising/myood/srp/UserDao.java new file mode 100644 index 0000000000..d5f421a952 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/UserDao.java @@ -0,0 +1,26 @@ +package com.coderising.myood.srp; + +import java.util.List; + +/** + * Created by thomas_young on 21/6/2017. + */ +public class UserDao { + private String sendMailQuery = null; + + private void setLoadQuery(String productID) throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + public List loadMailingList(String productID) throws Exception { + setLoadQuery(productID); + return DBUtil.query(this.sendMailQuery); + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/Configuration.java b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/Configuration.java new file mode 100644 index 0000000000..b187686fc0 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/Configuration.java @@ -0,0 +1,26 @@ +package com.coderising.myood.srp.goodSrp; + +import com.coderising.myood.srp.ConfigurationKeys; + +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(com.coderising.myood.srp.ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(com.coderising.myood.srp.ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/ConfigurationKeys.java b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/ConfigurationKeys.java new file mode 100644 index 0000000000..c69fa86cbf --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.myood.srp.goodSrp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/DBUtil.java b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/DBUtil.java new file mode 100644 index 0000000000..4d8403d525 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.myood.srp.goodSrp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com" + i); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/Mail.java b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/Mail.java new file mode 100644 index 0000000000..04472df8bc --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/Mail.java @@ -0,0 +1,32 @@ +package com.coderising.myood.srp.goodSrp; + +import com.coderising.myood.srp.goodSrp.template.MailBodyTemplate; +import com.coderising.myood.srp.goodSrp.template.TextMailBodyTemplate; + +import java.util.List; +import java.util.stream.Collectors; + +public class Mail { + + private User user; + MailBodyTemplate mailBodyTemplate; + public Mail(User u){ + this.user = u; + } + public String getAddress(){ + return user.getEMailAddress(); + } + public String getSubject(){ + return "您关注的产品降价了"; + } + public String getBody(){ + mailBodyTemplate = new TextMailBodyTemplate(user.getName(), buildProductDescList(), getAddress()); + return mailBodyTemplate.render(); + } + private String buildProductDescList() { + List products = user.getSubscribedProducts(); + //.... 实现略... + return products.stream().map(Object::toString) + .collect(Collectors.joining(", ")); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/MailSender.java b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/MailSender.java new file mode 100644 index 0000000000..70d2595e47 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/MailSender.java @@ -0,0 +1,35 @@ +package com.coderising.myood.srp.goodSrp; + +/** + * Created by thomas_young on 24/6/2017. + */ +public class MailSender { + private String fromAddress ; + private String smtpHost; + private String altSmtpHost; + + public MailSender(Configuration config){ + this.fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + this.smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + this.altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + } + + public void sendMail(Mail mail){ + try{ + sendEmail(mail, this.smtpHost); + }catch(Exception e){ + try{ + sendEmail(mail, this.altSmtpHost); + }catch (Exception ex){ + System.out.println("通过备用 SMTP服务器发送邮件失败: " + ex.getMessage()); + } + + } + } + + private void sendEmail(Mail mail, String smtpHost){ + //发送邮件 + System.out.println("开始发送邮件"); + MailUtil.sendEmail(mail, smtpHost, fromAddress); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/MailUtil.java b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/MailUtil.java new file mode 100644 index 0000000000..77a26d8318 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/MailUtil.java @@ -0,0 +1,16 @@ +package com.coderising.myood.srp.goodSrp; + +public class MailUtil { + + public static void sendEmail(Mail mail, String smtpHost, String fromAddress) { + //假装发了一封邮件 + System.out.println("使用smtpHost为"+smtpHost); + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(mail.getAddress()).append("\n"); + buffer.append("Subject:").append(mail.getSubject()).append("\n"); + buffer.append("Content:").append(mail.getBody()).append("\n"); + + System.out.println(buffer.toString()); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/Product.java b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/Product.java new file mode 100644 index 0000000000..9373690bd7 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/Product.java @@ -0,0 +1,34 @@ +package com.coderising.myood.srp.goodSrp; + + + +public class Product { + + private String id; + private String desc; + public String getDescription(){ + return desc; + } + + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + @Override + public String toString() { + return desc; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/ProductService.java b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/ProductService.java new file mode 100644 index 0000000000..26853bc4d3 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/ProductService.java @@ -0,0 +1,38 @@ +package com.coderising.myood.srp.goodSrp; + + +import java.io.*; +import java.util.LinkedList; +import java.util.List; + +public class ProductService { + private static File f = new File("/Users/thomas_young/Documents/code/liuxintraining/coding2017/students/812350401/src/main/java/com/coderising/myood/srp/product_promotion.txt"); + public List getPromotionProducts() { + //从文本文件中读取文件列表 + String line; + List products = new LinkedList<>(); + try (BufferedReader br = new BufferedReader(new FileReader(f))) { + while ((line = br.readLine()) != null) { + Product p =parseGenProduct(line); + products.add(p); + } + } catch (IOException e) { + e.printStackTrace(); + } + return products; + } + + private Product parseGenProduct(String line) { + String[] data = line.split(" "); + String productID = data[0]; + String productDesc = data[1]; + System.out.println("产品ID = " + productID); + System.out.println("产品描述 = " + productDesc + "\n"); + Product p = new Product(); + p.setDesc(productDesc); + p.setId(productID); + return p; + } + + +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/PromotionJob.java b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/PromotionJob.java new file mode 100644 index 0000000000..5b3ce7a1de --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/PromotionJob.java @@ -0,0 +1,29 @@ +package com.coderising.myood.srp.goodSrp; + +import java.util.List; + +public class PromotionJob { + + private ProductService productService = new ProductService() ; //获取production service + private UserService userService = new UserService() ;// 获取UserService + + public void run(){ + + Configuration cfg = new Configuration(); + + List ps = productService.getPromotionProducts(); + + List users = userService.getUsers(ps); + + + MailSender mailSender = new MailSender(cfg); + + for(User user : users){ + mailSender.sendMail(new Mail(user)); + } + } + + public static void main(String[] args) { + new PromotionJob().run(); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/User.java b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/User.java new file mode 100644 index 0000000000..65383587d1 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/User.java @@ -0,0 +1,39 @@ +package com.coderising.myood.srp.goodSrp; + +import java.util.List; + +/** + * Created by thomas_young on 24/6/2017. + */ +public class User { + private String name; + private String emailAddress; + + private List subscribedProducts; + + public String getName(){ + return name; + } + public String getEMailAddress() { + return emailAddress; + } + public List getSubscribedProducts(){ + return this.subscribedProducts; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmailAddress() { + return emailAddress; + } + + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } + + public void setSubscribedProducts(List subscribedProducts) { + this.subscribedProducts = subscribedProducts; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/UserService.java b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/UserService.java new file mode 100644 index 0000000000..152d253ae3 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/UserService.java @@ -0,0 +1,26 @@ +package com.coderising.myood.srp.goodSrp; + +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +/** + * Created by thomas_young on 24/6/2017. + */ +public class UserService { + + public List getUsers(List ps) { + List users = new LinkedList<>(); + String sql = "Select name from subscriptions where send_mail=1"; + System.out.println("loadQuery set\n"); + List userInfoList = DBUtil.query(sql); + for (Object userInfo: userInfoList) { + User user = new User(); + user.setName(((Map)userInfo).get("NAME")); + user.setEmailAddress(((Map)userInfo).get("EMAIL")); + user.setSubscribedProducts(ps); + users.add(user); + } + return users; + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/template/MailBodyTemplate.java b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/template/MailBodyTemplate.java new file mode 100644 index 0000000000..2ff179ac7c --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/template/MailBodyTemplate.java @@ -0,0 +1,5 @@ +package com.coderising.myood.srp.goodSrp.template; + +public interface MailBodyTemplate { + String render(); +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/template/TextMailBodyTemplate.java b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/template/TextMailBodyTemplate.java new file mode 100644 index 0000000000..b43561a04d --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/goodSrp/template/TextMailBodyTemplate.java @@ -0,0 +1,20 @@ +package com.coderising.myood.srp.goodSrp.template; + + +public class TextMailBodyTemplate implements MailBodyTemplate { + String productDescription; + String name; + String toAdress; + public TextMailBodyTemplate(String name, String productDescription, String toAdress){ + this.productDescription = productDescription; + this.name = name; + this.toAdress = toAdress; + } + + @Override + public String render() { + //使用某种模板技术实现Render + return "尊敬的 "+ name +", 您关注的产品 " + productDescription + " 降价了,欢迎购买!" ; + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myood/srp/product_promotion.txt b/students/812350401/src/main/java/com/coderising/myood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/812350401/src/main/java/com/coderising/myood/uml/Dice.java b/students/812350401/src/main/java/com/coderising/myood/uml/Dice.java new file mode 100644 index 0000000000..a48f7114ee --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/uml/Dice.java @@ -0,0 +1,17 @@ +package com.coderising.myood.uml; + +import com.google.common.collect.ImmutableList; + +import java.util.Random; + +/** + * Created by thomas_young on 27/6/2017. + */ +public class Dice { + + private ImmutableList values = ImmutableList.of(1, 2, 3, 4, 5, 6); + + public int roll() { + return values.get(new Random().nextInt(values.size())); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/uml/DiceGame.java b/students/812350401/src/main/java/com/coderising/myood/uml/DiceGame.java new file mode 100644 index 0000000000..386550fd67 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/uml/DiceGame.java @@ -0,0 +1,44 @@ +package com.coderising.myood.uml; + +/** + * Created by thomas_young on 27/6/2017. + */ +public class DiceGame { + private Player player1, player2; + private Dice dice1, dice2; + private static int WIN_POINT = 7; + + public void start() { + assert player1 != null; + assert player2 != null; + assert dice1 != null; + assert dice2 != null; + int player1Point; + int player2Point; + do { + player1Point = player1.roll(dice1, dice2); + player2Point = player2.roll(dice1, dice2); + System.out.print(player1 + " roll " + player1Point + ", "); + System.out.println(player2 + " roll " + player2Point + "."); + if (player1Point == player2Point) { + continue; + } + if (player1Point == WIN_POINT) { + System.out.println(player1 + " win!"); + break; + } + if (player2Point == WIN_POINT) { + System.out.println(player2 + " win!"); + break; + } + } while (true); + } + + public DiceGame(Player aPlayer1, Player aPlayer2, Dice aDice1, Dice aDice2) { + player1 = aPlayer1; + player2 = aPlayer2; + dice1 = aDice1; + dice2 = aDice2; + } + +} diff --git a/students/812350401/src/main/java/com/coderising/myood/uml/GameTest.java b/students/812350401/src/main/java/com/coderising/myood/uml/GameTest.java new file mode 100644 index 0000000000..ee36709326 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/uml/GameTest.java @@ -0,0 +1,15 @@ +package com.coderising.myood.uml; + +/** + * Created by thomas_young on 27/6/2017. + */ +public class GameTest { + public static void main(String[] args) { + Player player1 = new Player("player1"); + Player player2 = new Player("player2"); + Dice dice1 = new Dice(); + Dice dice2 = new Dice(); + DiceGame game = new DiceGame(player1, player2, dice1, dice2); + game.start(); + } +} diff --git a/students/812350401/src/main/java/com/coderising/myood/uml/Player.java b/students/812350401/src/main/java/com/coderising/myood/uml/Player.java new file mode 100644 index 0000000000..2add582970 --- /dev/null +++ b/students/812350401/src/main/java/com/coderising/myood/uml/Player.java @@ -0,0 +1,23 @@ +package com.coderising.myood.uml; + +/** + * Created by thomas_young on 27/6/2017. + */ +public class Player { + private String name; + + public Player(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } + + public int roll(Dice dice1, Dice dice2) { + int first = dice1.roll(); + int second = dice2.roll(); + return first + second; + } +} diff --git "a/students/812350401/src/main/java/com/coderising/myood/uml/\346\212\225\351\252\260\345\255\220\346\227\266\345\272\217\345\233\276.png" "b/students/812350401/src/main/java/com/coderising/myood/uml/\346\212\225\351\252\260\345\255\220\346\227\266\345\272\217\345\233\276.png" new file mode 100644 index 0000000000..578894269d Binary files /dev/null and "b/students/812350401/src/main/java/com/coderising/myood/uml/\346\212\225\351\252\260\345\255\220\346\227\266\345\272\217\345\233\276.png" differ diff --git "a/students/812350401/src/main/java/com/coderising/myood/uml/\346\212\225\351\252\260\345\255\220\347\261\273\345\233\276.png" "b/students/812350401/src/main/java/com/coderising/myood/uml/\346\212\225\351\252\260\345\255\220\347\261\273\345\233\276.png" new file mode 100644 index 0000000000..587726bd61 Binary files /dev/null and "b/students/812350401/src/main/java/com/coderising/myood/uml/\346\212\225\351\252\260\345\255\220\347\261\273\345\233\276.png" differ diff --git "a/students/812350401/src/main/java/com/coderising/myood/uml/\350\264\255\347\211\251\347\275\221\347\253\231\347\224\250\344\276\213\345\233\276.png" "b/students/812350401/src/main/java/com/coderising/myood/uml/\350\264\255\347\211\251\347\275\221\347\253\231\347\224\250\344\276\213\345\233\276.png" new file mode 100644 index 0000000000..46addc0408 Binary files /dev/null and "b/students/812350401/src/main/java/com/coderising/myood/uml/\350\264\255\347\211\251\347\275\221\347\253\231\347\224\250\344\276\213\345\233\276.png" differ diff --git a/students/812350401/src/main/resource/01.txt b/students/812350401/src/main/resource/01.txt new file mode 100644 index 0000000000..5f5521fae2 --- /dev/null +++ b/students/812350401/src/main/resource/01.txt @@ -0,0 +1,2 @@ +abc +def diff --git a/students/812350401/src/main/resource/07.txt b/students/812350401/src/main/resource/07.txt new file mode 100644 index 0000000000..be72da22ea --- /dev/null +++ b/students/812350401/src/main/resource/07.txt @@ -0,0 +1,5 @@ + abc +def + +gh + diff --git a/students/812350401/src/test/com/coderising/mydp/bridge/CircleTest.java b/students/812350401/src/test/com/coderising/mydp/bridge/CircleTest.java new file mode 100644 index 0000000000..f7dc934648 --- /dev/null +++ b/students/812350401/src/test/com/coderising/mydp/bridge/CircleTest.java @@ -0,0 +1,21 @@ +package com.coderising.mydp.bridge; + +import junit.framework.TestCase; + +/** + * Created by thomas_young on 6/8/2017. + */ +public class CircleTest extends TestCase { + public void testDraw() throws Exception { + + } + + public void testSetDrawing() throws Exception { + + } + + public void testMain() throws Exception { + + } + +} \ No newline at end of file diff --git a/students/812350401/src/test/com/coderising/myood/atmSimulation/impl/ATMTest.java b/students/812350401/src/test/com/coderising/myood/atmSimulation/impl/ATMTest.java new file mode 100644 index 0000000000..408d70d68c --- /dev/null +++ b/students/812350401/src/test/com/coderising/myood/atmSimulation/impl/ATMTest.java @@ -0,0 +1,38 @@ +package com.coderising.myood.atmSimulation.impl; + +import com.coderising.myood.atmSimulation.model.*; +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Created by thomas_young on 30/7/2017. + */ +public class ATMTest { + private static ATM atm; + + static { + atm = new ATM(); + CardReader cardReader = new CardReaderImpl(); + SuperKeyPad superKeyPad = new SuperKeyPad(); + KeyBoard keyBoard = new KeyBoardImpl(); + Display display = new DisplayImpl(); + superKeyPad.setDisplay(display); + superKeyPad.setKeyBoard(keyBoard); + CashDispenser cashDispenser = new CashDispenserImpl(); + DepositSlot depositSlot = new DepositSlotImpl(); + Printer printer; + BankProxy bankProxy = new BankProxyImpl(); + NetworkClient networkClient = new NetworkClient(); + bankProxy.setNetworkClient(networkClient); + atm.setBankProxy(bankProxy); + atm.setCardReader(cardReader); + atm.setCashDispenser(cashDispenser); + atm.setDepositSlot(depositSlot); + atm.setSuperKeyPad(superKeyPad); + } + + public static void main(String[] args) { + atm.start(); + } +} \ No newline at end of file diff --git a/students/812350401/src/test/com/coderising/myood/atmSimulation/impl/BankProxyImplTest.java b/students/812350401/src/test/com/coderising/myood/atmSimulation/impl/BankProxyImplTest.java new file mode 100644 index 0000000000..6fdfc3e91e --- /dev/null +++ b/students/812350401/src/test/com/coderising/myood/atmSimulation/impl/BankProxyImplTest.java @@ -0,0 +1,31 @@ +package com.coderising.myood.atmSimulation.impl; + +import com.coderising.myood.atmSimulation.model.BankProxy; +import org.junit.Assert; +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Created by thomas_young on 30/7/2017. + */ +public class BankProxyImplTest { + private static BankProxy bankProxy; + { + bankProxy = new BankProxyImpl(); + NetworkClient networkClient = new NetworkClient(); + bankProxy.setNetworkClient(networkClient); + } + @Test + public void verify() throws Exception { + Assert.assertFalse(bankProxy.verify("yangkai", "12345")); + Assert.assertFalse(bankProxy.verify(null, "12345")); + Assert.assertTrue(bankProxy.verify("yangkai", "123456")); + } + + @Test + public void process() throws Exception { + + } + +} \ No newline at end of file diff --git a/students/812350401/src/test/com/coderising/myood/atmSimulation/impl/SuperKeyPadTest.java b/students/812350401/src/test/com/coderising/myood/atmSimulation/impl/SuperKeyPadTest.java new file mode 100644 index 0000000000..455c721402 --- /dev/null +++ b/students/812350401/src/test/com/coderising/myood/atmSimulation/impl/SuperKeyPadTest.java @@ -0,0 +1,66 @@ +package com.coderising.myood.atmSimulation.impl; + +import com.coderising.myood.atmSimulation.model.Display; +import com.coderising.myood.atmSimulation.model.KeyBoard; +import com.coderising.myood.atmSimulation.model.Transaction; +import org.apache.commons.lang3.StringUtils; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; + +import static org.junit.Assert.*; + +/** + * Created by thomas_young on 30/7/2017. + */ +public class SuperKeyPadTest { + private SuperKeyPad superKeyPad; + { + superKeyPad = new SuperKeyPad(); + Display display = new DisplayImpl(); + KeyBoard keyBoard = new KeyBoardImpl(); + superKeyPad.setDisplay(display); + superKeyPad.setKeyBoard(keyBoard); + } + + @Test + public void testGetPassword() throws Exception { + String password = "123456"; + String output; + InputStream stdin = System.in; + try { + System.setIn(new ByteArrayInputStream(password.getBytes())); + output = superKeyPad.getPassword(); + } finally { + System.setIn(stdin); + } + Assert.assertEquals(password, output); + } + + @Test + public void testDisplayMessage() throws Exception { + superKeyPad.displayMessage("欢迎"); + } + + @Ignore + @Test + public void testGetTransaction() throws Exception { + + String lineSeparator = System.getProperty("line.separator"); + String trxInput = "X" + lineSeparator + "D" + lineSeparator + "xx" + lineSeparator + "190"; + + InputStream stdin = System.in; + Transaction transaction; + try { + System.setIn(new ByteArrayInputStream(trxInput.getBytes())); + transaction = superKeyPad.getTransaction("yangkai", "123456"); + } finally { + System.setIn(stdin); + } + System.out.println(transaction); + } + +} \ No newline at end of file diff --git a/students/812350401/src/test/com/coderising/myood/atmSimulation/model/CardReaderTest.java b/students/812350401/src/test/com/coderising/myood/atmSimulation/model/CardReaderTest.java new file mode 100644 index 0000000000..9c88dfa4d7 --- /dev/null +++ b/students/812350401/src/test/com/coderising/myood/atmSimulation/model/CardReaderTest.java @@ -0,0 +1,33 @@ +package com.coderising.myood.atmSimulation.model; + +import com.coderising.myood.atmSimulation.impl.CardReaderImpl; +import com.coderising.myood.atmSimulation.model.CardReader; +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Created by thomas_young on 30/7/2017. + */ +public class CardReaderTest { + CardReader cardReader = new CardReaderImpl(); + @Test + public void getAccount() throws Exception { + String account; + while(true) { + account = cardReader.getAccount(); + if(account != null) { + System.out.println("读卡成功,卡号是"+account); + break; + } + System.out.println("读卡失败"); + } + cardReader.ejectCard(); + } + + @Test + public void ejectCard() throws Exception { + cardReader.ejectCard(); + } + +} \ No newline at end of file diff --git a/students/812350401/src/test/com/coderising/myood/atmSimulation/model/DisplayTest.java b/students/812350401/src/test/com/coderising/myood/atmSimulation/model/DisplayTest.java new file mode 100644 index 0000000000..5bc7779d86 --- /dev/null +++ b/students/812350401/src/test/com/coderising/myood/atmSimulation/model/DisplayTest.java @@ -0,0 +1,23 @@ +package com.coderising.myood.atmSimulation.model; + +import com.coderising.myood.atmSimulation.impl.DisplayImpl; +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Created by thomas_young on 30/7/2017. + */ +public class DisplayTest { + private static Display display = new DisplayImpl(); + @Test + public void outputPlainText() throws Exception { + display.outputPlainText("欢迎你!"); + } + + @Test + public void outputEncryptedText() throws Exception { + display.outputEncryptedText("345677"); + } + +} \ No newline at end of file diff --git a/students/812350401/src/test/com/coderising/myood/atmSimulation/model/KeyBoardTest.java b/students/812350401/src/test/com/coderising/myood/atmSimulation/model/KeyBoardTest.java new file mode 100644 index 0000000000..7c732d0786 --- /dev/null +++ b/students/812350401/src/test/com/coderising/myood/atmSimulation/model/KeyBoardTest.java @@ -0,0 +1,33 @@ +package com.coderising.myood.atmSimulation.model; + +import com.coderising.myood.atmSimulation.impl.KeyBoardImpl; +import org.junit.Ignore; +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; + +/** + * Created by thomas_young on 30/7/2017. + */ +public class KeyBoardTest { + KeyBoard keyBoard = new KeyBoardImpl(); + + @Test + public void testInput() throws Exception { + String data = "Hello, World!\r\n"; + String input; + InputStream stdin = System.in; + try { + System.setIn(new ByteArrayInputStream(data.getBytes())); + input = keyBoard.input(); + } finally { + System.setIn(stdin); + } + System.out.println("input is----" + input); + + System.setIn(new ByteArrayInputStream("haha\n".getBytes())); + input = keyBoard.input(); + System.out.println(input); + } +} \ No newline at end of file diff --git a/students/812350401/src/test/com/coderising/myood/atmSimulation/model/TransactionTest.java b/students/812350401/src/test/com/coderising/myood/atmSimulation/model/TransactionTest.java new file mode 100644 index 0000000000..c8efb805f7 --- /dev/null +++ b/students/812350401/src/test/com/coderising/myood/atmSimulation/model/TransactionTest.java @@ -0,0 +1,54 @@ +package com.coderising.myood.atmSimulation.model; + +import com.coderising.myood.atmSimulation.impl.*; +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Created by thomas_young on 30/7/2017. + */ +public class TransactionTest { + private static Transaction withdrawTrx; + private static Transaction noMoneyWithdrawTrx; + private static Transaction depositTrx; + private static ATM atm; + + static { + atm = new ATM(); + withdrawTrx = new WithdrawTransaction("withdraw", "1023", 100d); + noMoneyWithdrawTrx = new WithdrawTransaction("withdraw", "1023", 10001d); + depositTrx = new DepositTransaction("deposit", "456", 200d); + CardReader cardReader = new CardReaderImpl(); + SuperKeyPad superKeyPad = new SuperKeyPad(); + CashDispenser cashDispenser = new CashDispenserImpl(); + DepositSlot depositSlot = new DepositSlotImpl(); + Printer printer; + BankProxy bankProxy = new BankProxyImpl(); + atm.setBankProxy(bankProxy); + atm.setCardReader(cardReader); + atm.setCashDispenser(cashDispenser); + atm.setDepositSlot(depositSlot); + atm.setSuperKeyPad(superKeyPad); + } + + @Test + public void preProcess() throws Exception { + assertTrue(withdrawTrx.preProcess(atm)); + assertFalse(noMoneyWithdrawTrx.preProcess(atm)); + depositTrx.preProcess(atm); + assertEquals((Double)(((DepositTransaction)depositTrx).getAmount()-5d), ((DepositTransaction)depositTrx).getActualAmount()); + } + + @Test + public void postProcess() throws Exception { + assertTrue(withdrawTrx.postProcess(atm)); + depositTrx.postProcess(atm); + } + + @Test + public void toNetworkPackage() throws Exception { + + } + +} \ No newline at end of file diff --git a/students/812350401/src/test/com/coderising/myood/payroll/my_payroll/database/EmployeeTableTest.java b/students/812350401/src/test/com/coderising/myood/payroll/my_payroll/database/EmployeeTableTest.java new file mode 100644 index 0000000000..02c5552097 --- /dev/null +++ b/students/812350401/src/test/com/coderising/myood/payroll/my_payroll/database/EmployeeTableTest.java @@ -0,0 +1,71 @@ +package com.coderising.myood.payroll.my_payroll.database; + +import org.junit.Test; +import org.junit.Before; +import org.junit.After; + +/** + * EmployeeTable Tester. + * + * @author + * @version 1.0 + * @since
Sep 16, 2017
+ */ +public class EmployeeTableTest { + + @Before + public void before() throws Exception { + } + + @After + public void after() throws Exception { + } + + @Test + public void testEmployeeTable() { + Table table = new EmployeeTable(); + EmployeeTable.EmployeeBuilder employeeBuilder = new EmployeeTable.EmployeeBuilder(); + employeeBuilder.id(1) + .address("aa") + .insert((EmployeeTable) table); + employeeBuilder + .id(2) + .base_salary(500.5) + .insert((EmployeeTable) table); + employeeBuilder.clear(); + employeeBuilder + .id(3) + .salary(5000) + .emp_type("0") + .insert((EmployeeTable) table); + System.out.println(table); + } + + @Test + public void testDatabase() { + DataBase dataBase = new DataBase("payroll"); + Table table = new EmployeeTable(); + + EmployeeTable.EmployeeBuilder employeeBuilder = new EmployeeTable.EmployeeBuilder(); + employeeBuilder.id(1) + .address("aa") + .insert((EmployeeTable) table); + employeeBuilder + .id(2) + .base_salary(500.5) + .insert((EmployeeTable) table); + employeeBuilder.clear(); + employeeBuilder + .id(3) + .salary(5000) + .emp_type("0") + .insert((EmployeeTable) table); + dataBase.addTable(table); + + System.out.println(dataBase); + + System.out.println(dataBase.drop("Employee")); + System.out.println(dataBase); + } + +} diff --git a/students/812350401/src/test/com/coderising/myood/payroll/my_payroll/domain/AffiliationTest.java b/students/812350401/src/test/com/coderising/myood/payroll/my_payroll/domain/AffiliationTest.java new file mode 100644 index 0000000000..9a5386738b --- /dev/null +++ b/students/812350401/src/test/com/coderising/myood/payroll/my_payroll/domain/AffiliationTest.java @@ -0,0 +1,43 @@ +package com.coderising.myood.payroll.my_payroll.domain; + +import com.coderising.myood.payroll.my_payroll.affiliantion.NonAffiliation; +import com.coderising.myood.payroll.my_payroll.affiliantion.ServiseCharge; +import com.coderising.myood.payroll.my_payroll.affiliantion.UnionAffiliation; +import com.coderising.myood.payroll.my_payroll.util.DateUtil; +import org.junit.Assert; +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Created by thomas_young on 16/9/2017. + */ +public class AffiliationTest { + private static double TOLERANCE = 1e-5; + + @Test + public void calculateDeductions() throws Exception { + Affiliation na = new NonAffiliation(); + Paycheck pc = new Paycheck(1, DateUtil.parseDate("2017-06-01"), DateUtil.parseDate("2017-06-28")); + + double deduction = na.calculateDeductions(pc); + Assert.assertEquals(0d, deduction, TOLERANCE); + + Affiliation ua = new UnionAffiliation(111); + + ServiseCharge sc1 = new ServiseCharge("2017-06-16", 200); + ServiseCharge sc2 = new ServiseCharge("2017-06-28", 300); + ServiseCharge sc3 = new ServiseCharge("2017-07-18", 400); + + deduction = ua.calculateDeductions(pc); + Assert.assertEquals(444d, deduction, TOLERANCE); + + ((UnionAffiliation) ua).addServiceCharge(sc1); + ((UnionAffiliation) ua).addServiceCharge(sc2); + ((UnionAffiliation) ua).addServiceCharge(sc3); + deduction = ua.calculateDeductions(pc); + Assert.assertEquals(944d, deduction, TOLERANCE); + + } + +} \ No newline at end of file diff --git a/students/812350401/src/test/com/coderising/myood/payroll/my_payroll/domain/PaymentClassificationTest.java b/students/812350401/src/test/com/coderising/myood/payroll/my_payroll/domain/PaymentClassificationTest.java new file mode 100644 index 0000000000..43358afd01 --- /dev/null +++ b/students/812350401/src/test/com/coderising/myood/payroll/my_payroll/domain/PaymentClassificationTest.java @@ -0,0 +1,68 @@ +package com.coderising.myood.payroll.my_payroll.domain; + +import com.coderising.myood.payroll.my_payroll.paymentclassification.*; +import com.coderising.myood.payroll.my_payroll.paymentclassification.SalesReceipt; +import com.coderising.myood.payroll.my_payroll.util.DateUtil; +import org.junit.Assert; +import org.junit.Test; + +/** + * Created by thomas_young on 16/9/2017. + */ +public class PaymentClassificationTest { + private static double TOLERANCE = 1e-5; + @Test + public void hourlyCalculatePay1() throws Exception { + HourlyClassification hc = new HourlyClassification(100); + Paycheck pc = new Paycheck(1, DateUtil.parseDate("2017-06-12"), DateUtil.parseDate("2017-07-12")); + TimeCard t1 = new TimeCard("2017-06-11", 4); + TimeCard t2 = new TimeCard("2017-06-15", 10); + hc.addTimeCard(t1); + hc.addTimeCard(t2); + double pay = hc.calculatePay(pc); + Assert.assertEquals(1100d, pay, TOLERANCE); + } + + @Test + public void hourlyCalculatePay2() throws Exception { + PaymentClassification hc = new HourlyClassification(100); + Paycheck pc = new Paycheck(1, DateUtil.parseDate("2017-06-12"), DateUtil.parseDate("2017-07-12")); + com.coderising.myood.payroll.my_payroll.paymentclassification.TimeCard t1 = new com.coderising.myood.payroll.my_payroll.paymentclassification.TimeCard("2017-06-12", 4); + com.coderising.myood.payroll.my_payroll.paymentclassification.TimeCard t2 = new com.coderising.myood.payroll.my_payroll.paymentclassification.TimeCard("2017-06-15", 10); + ((HourlyClassification) hc).addTimeCard(t1); + ((HourlyClassification) hc).addTimeCard(t2); + double pay = hc.calculatePay(pc); + Assert.assertEquals(1500d, pay, TOLERANCE); + } + + @Test + public void salariedCalculatePay() { + PaymentClassification sc = new SalariedClassification(2000d); + double pay = sc.calculatePay(null); + Assert.assertEquals(2000d, pay, TOLERANCE); + } + + @Test + public void commissionCalculatePay() { + PaymentClassification cc = new CommissionClassification(2000d, 0.1); + Paycheck pc = new Paycheck(1, DateUtil.parseDate("2017-06-12"), DateUtil.parseDate("2017-07-12")); + + double pay = cc.calculatePay(pc); + Assert.assertEquals(2000d, pay, TOLERANCE); + + com.coderising.myood.payroll.my_payroll.paymentclassification.SalesReceipt sr1 = new com.coderising.myood.payroll.my_payroll.paymentclassification.SalesReceipt("2017-06-13", 200d); + com.coderising.myood.payroll.my_payroll.paymentclassification.SalesReceipt sr2 = new com.coderising.myood.payroll.my_payroll.paymentclassification.SalesReceipt("2017-06-15", 100d); + ((CommissionClassification) cc).addSalesReceipt(sr1); + ((CommissionClassification) cc).addSalesReceipt(sr2); + pay = cc.calculatePay(pc); + Assert.assertEquals(2030d, pay, TOLERANCE); + + PaymentClassification cc2 = new CommissionClassification(2000d, 0.1); + com.coderising.myood.payroll.my_payroll.paymentclassification.SalesReceipt sr3 = new SalesReceipt("2017-06-11", 200d); + ((CommissionClassification) cc2).addSalesReceipt(sr3); + ((CommissionClassification) cc2).addSalesReceipt(sr1); + pay = cc2.calculatePay(pc); + Assert.assertEquals(2020d, pay, TOLERANCE); + } + +} \ No newline at end of file diff --git a/students/812350401/src/test/com/coderising/myood/payroll/my_payroll/domain/PaymentMethodTest.java b/students/812350401/src/test/com/coderising/myood/payroll/my_payroll/domain/PaymentMethodTest.java new file mode 100644 index 0000000000..d2c62ac11d --- /dev/null +++ b/students/812350401/src/test/com/coderising/myood/payroll/my_payroll/domain/PaymentMethodTest.java @@ -0,0 +1,19 @@ +package com.coderising.myood.payroll.my_payroll.domain; + +import com.coderising.myood.payroll.my_payroll.paymentmethod.BankMethod; +import com.coderising.myood.payroll.my_payroll.util.DateUtil; +import org.junit.Test; + + +/** + * Created by thomas_young on 16/9/2017. + */ +public class PaymentMethodTest { + @Test + public void testBankPay() throws Exception { + PaymentMethod bp = new BankMethod(); + Paycheck pc = new Paycheck(1, DateUtil.parseDate("2017-06-13"), DateUtil.parseDate("2017-06-20")); + bp.pay(pc); + } + +} \ No newline at end of file diff --git a/students/812350401/src/test/com/coderising/myood/payroll/my_payroll/domain/PaymentScheduleTest.java b/students/812350401/src/test/com/coderising/myood/payroll/my_payroll/domain/PaymentScheduleTest.java new file mode 100644 index 0000000000..70a9994e6a --- /dev/null +++ b/students/812350401/src/test/com/coderising/myood/payroll/my_payroll/domain/PaymentScheduleTest.java @@ -0,0 +1,42 @@ +package com.coderising.myood.payroll.my_payroll.domain; + +import com.coderising.myood.payroll.my_payroll.paymentschedule.BiWeeklySchedule; +import com.coderising.myood.payroll.my_payroll.paymentschedule.MonthlySchedule; +import com.coderising.myood.payroll.my_payroll.paymentschedule.WeeklySchedule; +import com.coderising.myood.payroll.my_payroll.util.DateUtil; +import org.junit.Assert; +import org.junit.Test; + +/** + * Created by thomas_young on 16/9/2017. + */ +public class PaymentScheduleTest { + @Test + public void testMonthlySchedule() throws Exception { + PaymentSchedule ms = new MonthlySchedule(); + Assert.assertTrue(ms.isPayDate(DateUtil.parseDate("2017-06-30"))); + Assert.assertTrue(!ms.isPayDate(DateUtil.parseDate("2017-06-29"))); + Assert.assertEquals(DateUtil.parseDate("2017-06-01"), + ms.getPayPeriodStartDate(ms.getPayPeriodStartDate(DateUtil.parseDate("2017-06-15")))); + } + + @Test + public void testBiWeeklySchedule() { + PaymentSchedule bs = new BiWeeklySchedule(); + Assert.assertTrue(bs.isPayDate(DateUtil.parseDate("2017-06-16"))); + Assert.assertTrue(!bs.isPayDate(DateUtil.parseDate("2017-06-09"))); + Assert.assertEquals(DateUtil.parseDate("2017-06-03"), + bs.getPayPeriodStartDate(DateUtil.parseDate("2017-06-16"))); + } + + @Test + public void testWeeklySchedule() { + PaymentSchedule ps = new WeeklySchedule(); + Assert.assertTrue(ps.isPayDate(DateUtil.parseDate("2017-06-16"))); + Assert.assertTrue(ps.isPayDate(DateUtil.parseDate("2017-06-09"))); + Assert.assertTrue(!ps.isPayDate(DateUtil.parseDate("2017-06-17"))); + Assert.assertEquals(DateUtil.parseDate("2017-06-10"), + ps.getPayPeriodStartDate(DateUtil.parseDate("2017-06-16"))); + + } +} \ No newline at end of file diff --git a/students/812350401/src/test/com/coderising/myood/payroll/my_payroll/domain/RepeatedPayTest.java b/students/812350401/src/test/com/coderising/myood/payroll/my_payroll/domain/RepeatedPayTest.java new file mode 100644 index 0000000000..ce03fd3edc --- /dev/null +++ b/students/812350401/src/test/com/coderising/myood/payroll/my_payroll/domain/RepeatedPayTest.java @@ -0,0 +1,58 @@ +package com.coderising.myood.payroll.my_payroll.domain; + +import com.coderising.myood.payroll.my_payroll.PayrollService; +import com.coderising.myood.payroll.my_payroll.database.DataBase; +import com.coderising.myood.payroll.my_payroll.database.EmployeeTable; +import com.coderising.myood.payroll.my_payroll.database.PaycheckTable; +import com.coderising.myood.payroll.my_payroll.util.DateUtil; +import org.junit.Assert; +import org.junit.Test; + +import java.util.Date; + +/** + * Created by thomas_young on 17/9/2017. + */ +public class RepeatedPayTest { + private static DataBase payrollDataBase; + private static EmployeeTable employeeTable; + private static PaycheckTable paycheckTable; + private static PayTransaction payTransaction; + @Test + public void testRepeatedPay() { + payrollDataBase = new DataBase("payroll"); + employeeTable = new EmployeeTable(); + paycheckTable = new PaycheckTable(); + payrollDataBase.addTable(employeeTable); + payrollDataBase.addTable(paycheckTable); + EmployeeTable.EmployeeBuilder employeeBuilder = new EmployeeTable.EmployeeBuilder(); + employeeBuilder + .id(4) + .name("牛逼哥") + .emp_type("1") + .address("Tokyo") + .hourly_rate(500) + .schedule_type("1") + .payment_type("1") + .affiliation_type("1") + .insert(employeeTable); + + Date d = DateUtil.parseDate("2017-08-11"); + payTransaction = new PayTransaction(); + PayrollService payrollService = new PayrollService(); + payrollService.setEmployeeTable(employeeTable); + payrollService.setPaycheckTable(paycheckTable); + payTransaction.setDate(d); + payTransaction.setPayrollService(payrollService); + payTransaction.execute(); + payTransaction.execute(); + Assert.assertEquals(1, paycheckTable.getRows().size()); + + d = DateUtil.parseDate("2017-08-18"); + payTransaction.setDate(d); + payTransaction.execute(); + Assert.assertEquals(2, paycheckTable.getRows().size()); + System.out.println("***************************************"); + System.out.println(paycheckTable); + } +} diff --git a/students/81681981/first_OOP_homework/ood-assignment/pom.xml b/students/81681981/first_OOP_homework/ood-assignment/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/81681981/first_OOP_homework/ood-assignment/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..0af0155e33 --- /dev/null +++ b/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,24 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + User user = new User(); + user.setUserName("User" + i); + user.setMail(i+"aa@bb.com"); + userList.add(user); + } + + return userList; + } +} diff --git a/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/Email.java b/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/Email.java new file mode 100644 index 0000000000..b6d62acbeb --- /dev/null +++ b/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/Email.java @@ -0,0 +1,80 @@ +package com.coderising.ood.srp; + +import java.util.HashMap; +import java.util.Map; +/* + * email + */ + +public class Email { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String subject = null; + protected String message = null; + + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + + public String getSmtpHost() { + return smtpHost; + } + + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + + + public String getAltSmtpHost() { + return altSmtpHost; + } + + + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + + + public String getFromAddress() { + return fromAddress; + } + + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + protected void setSMTPHost() + { + smtpHost = this.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() + { + altSmtpHost = this.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + protected void setFromAddress() + { + fromAddress = this.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + +} diff --git a/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..f0adff0ab8 --- /dev/null +++ b/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,15 @@ +package com.coderising.ood.srp; + + +public class MailUtil { + public static void sendEmail(String toAddress,Message mes,boolean debug) { + Email email = new Email(); + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(email.getFromAddress()).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(mes.getSubject()).append("\n"); + buffer.append("Content:").append(mes.getMessageDesc()).append("\n"); + System.out.println(buffer.toString()); + } +} diff --git a/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/Message.java b/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/Message.java new file mode 100644 index 0000000000..59d916286b --- /dev/null +++ b/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/Message.java @@ -0,0 +1,19 @@ +package com.coderising.ood.srp; + +public class Message { + private String subject; + private String messageDesc; + public String getSubject() { + return subject; + } + public void setSubject(String subject) { + this.subject = subject; + } + public String getMessageDesc() { + return messageDesc; + } + public void setMessageDesc(String messageDesc) { + this.messageDesc = messageDesc; + } + +} diff --git a/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java b/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java new file mode 100644 index 0000000000..236f61d132 --- /dev/null +++ b/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/Product.java @@ -0,0 +1,43 @@ +package com.coderising.ood.srp; + +import java.util.ArrayList; +import java.util.List; + +public class Product { + + protected String productID = null; + protected String productDesc = null; + + protected void setProductID(String productID) + { + this.productID = productID; + + } + + protected String getproductID() + { + return productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + + public String getProductID() { + return productID; + } + + //获得该产品的所有订阅者 + protected List getLoadQuery(String productID){ + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + System.out.println("loadQuery set"); + return DBUtil.query(sendMailQuery); + } +} diff --git a/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..b0641c9789 --- /dev/null +++ b/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,103 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class PromotionMail { + + protected String sendMailQuery = null; + + protected String toAddress = null; + + protected String subject = null; + protected String message = null; + /** + * 1.读产品信息 2.获取发送地址 3.组织内容 4.发送 + * + * */ + // 1.获取产品信息 + protected List readFile(File file) throws IOException // @02C + { + List productlist = new ArrayList(); + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + Product product = new Product(); + product.setProductID(data[0]); + product.setProductDesc(data[1]); + productlist.add(product); + System.out.println("产品ID = " + data[0] + "\n"); + System.out.println("产品描述 = " + data[1] + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + + return productlist; + } + + // 获取产品信息 + public PromotionMail(File file, boolean mailDebug) throws Exception { + + // 读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + List productlist = readFile(file); + if (productlist != null) { + for (int i = 0; i < productlist.size(); i++) { + Product product = (Product) productlist.get(i); + if(product != null){ + this.consistAndSend(product); + } + } + + } + } + + //获取某产品的所有订阅用户,并推送对应内容 + public void consistAndSend(Product product){ + List toAddressList = product.getLoadQuery(product + .getproductID());// 获取该产品的订阅者 + if (toAddressList != null){ + for (int j = 0; j < toAddressList.size(); j++) { + User user = (User) toAddressList.get(j); + Message mes = this.setMessage(user.getUserName(), + product.getProductDesc()); + this.sendEMails(true, mes, user.getMail()); + } + } + } + + + protected Message setMessage(String name, String productDesc){ + Message mes = new Message(); + String subject = "您关注的产品降价了"; + String message = "尊敬的 " + name + ", 您关注的产品 " + productDesc + + " 降价了,欢迎购买!"; + mes.setSubject(subject); + mes.setMessageDesc(message); + return mes; + } + + protected void sendEMails(boolean debug, Message mes, String toAddress){ + System.out.println("开始发送邮件"); + if (null != toAddress && !toAddress.equals("")) { + try{ + MailUtil.sendEmail(toAddress, mes, debug); + + }catch(Exception e){ + + } + } else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/TestMain.java b/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/TestMain.java new file mode 100644 index 0000000000..88b43c18ac --- /dev/null +++ b/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/TestMain.java @@ -0,0 +1,16 @@ +package com.coderising.ood.srp; + +import java.io.File; + +public class TestMain { + + public static void main(String[] args) throws Exception { + + File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + + } +} diff --git a/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/User.java b/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/User.java new file mode 100644 index 0000000000..cb03ec5d2c --- /dev/null +++ b/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/User.java @@ -0,0 +1,21 @@ +package com.coderising.ood.srp; + +import java.util.List; + +public class User { + private String userName; + private String mail; + public String getUserName() { + return userName; + } + public void setUserName(String userName) { + this.userName = userName; + } + public String getMail() { + return mail; + } + public void setMail(String mail) { + this.mail = mail; + } + +} diff --git a/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/81681981/first_OOP_homework/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/81681981/first_OOP_homework/readme.txt b/students/81681981/first_OOP_homework/readme.txt new file mode 100644 index 0000000000..0330532c81 --- /dev/null +++ b/students/81681981/first_OOP_homework/readme.txt @@ -0,0 +1,11 @@ +作业说明 + +类及功能 +1.conifgurationKeys.java 邮件发送服务器配置信息 +2.新增User.java 对应订阅用户信息(用户名,邮箱) +3.修改DBUtil.java 数据库操作类,把键值 修改为User对象 +4.新增Email.java 维护邮件发送的前置信息和邮件标题,邮件内容,smtphost,altSmtpHost,fromAddress,subject,message +5.新增Product.java 维护产品信息及订阅用户 +6.新增Message.java 维护要发送的内容 +7.修改PromotionMail.java 功能:读取产品信息,组织要发送的内容封装为Message对象,获取该产品对应的订阅用户,调用MailUtil.java 发送邮件 +8.MailUtil.java 负责发送 \ No newline at end of file diff --git a/students/82180735/ood/ood-assignment/README.md b/students/82180735/ood/ood-assignment/README.md new file mode 100644 index 0000000000..c425e51701 --- /dev/null +++ b/students/82180735/ood/ood-assignment/README.md @@ -0,0 +1,6 @@ + +[TOC] +## 面向对象相关的作业 + +### 第一周作业 重构一个发送邮件的程序,使之符合SRP + diff --git a/students/82180735/ood/ood-assignment/pom.xml b/students/82180735/ood/ood-assignment/pom.xml new file mode 100644 index 0000000000..b55d53ffe1 --- /dev/null +++ b/students/82180735/ood/ood-assignment/pom.xml @@ -0,0 +1,12 @@ + + + 4.0.0 + + com.yue + ood-assignment + 1.0-SNAPSHOT + + + \ No newline at end of file diff --git a/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..d11d29787e --- /dev/null +++ b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Main.java b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Main.java new file mode 100644 index 0000000000..72dccf53ef --- /dev/null +++ b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/Main.java @@ -0,0 +1,50 @@ +package com.coderising.ood.srp; + +import com.coderising.ood.srp.domain.mail.MailConfigInfo; +import com.coderising.ood.srp.domain.mail.MailInfo; +import com.coderising.ood.srp.domain.product.ProductInfo; +import com.coderising.ood.srp.service.ProductInfoService; +import com.coderising.ood.srp.service.PromotionMailService; +import com.coderising.ood.srp.service.UserService; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * Created by justin on 17/6/19. + */ +public class Main { + + public static void main(String[] args) { + //查询商品信息 + ProductInfoService productInfoService = new ProductInfoService(); + ProductInfo productInfo = productInfoService.selectProduct(); + + //查询用户信息 + UserService userService = new UserService(); + List> userList = userService.querySubscriptions(productInfo.getProductID()); + + //构造邮件配置及发件人信息 + Configuration configuration = new Configuration(); + MailConfigInfo mailConfigInfo = new MailConfigInfo(); + mailConfigInfo.setSmtpHost(configuration.getProperty(ConfigurationKeys.SMTP_SERVER)); + mailConfigInfo.setAltSmtpHost(configuration.getProperty(ConfigurationKeys.ALT_SMTP_SERVER)); + mailConfigInfo.setFromAddress(configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN)); + + //构造邮件内容及收件人信息 + List mailInfos = new ArrayList(userList.size()); + for (Map map : userList) { + MailInfo mailInfo = new MailInfo(); + mailInfo.setMessage("尊敬的 "+map.get("NAME")+", 您关注的产品 " + productInfo.getProductDesc() + " 降价了,欢迎购买!"); + mailInfo.setSubject("您关注的产品降价了"); + mailInfo.setToAddress(map.get("EMAIL")); + + mailInfos.add(mailInfo); + } + + PromotionMailService promotionMailService = new PromotionMailService(); + + promotionMailService.sendEMails(mailConfigInfo,mailInfos,true); + } +} diff --git a/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dao/UserDao.java b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dao/UserDao.java new file mode 100644 index 0000000000..89137e35d8 --- /dev/null +++ b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/dao/UserDao.java @@ -0,0 +1,22 @@ +package com.coderising.ood.srp.dao; + +import com.coderising.ood.srp.util.DBUtil; + +import java.util.List; + +/** + * Created by justin on 17/6/19. + */ +public class UserDao { + + public List querySubscriptions(String productId) { + + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productId +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + return DBUtil.query(sendMailQuery); + } +} diff --git a/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domain/mail/MailConfigInfo.java b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domain/mail/MailConfigInfo.java new file mode 100644 index 0000000000..bcfd9aa857 --- /dev/null +++ b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domain/mail/MailConfigInfo.java @@ -0,0 +1,35 @@ +package com.coderising.ood.srp.domain.mail; + +/** + * Created by justin on 17/6/12. + */ +public class MailConfigInfo { + private String smtpHost; + private String altSmtpHost; + private String fromAddress; + + public String getSmtpHost() { + return smtpHost; + } + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + +} diff --git a/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domain/mail/MailInfo.java b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domain/mail/MailInfo.java new file mode 100644 index 0000000000..07aa58602a --- /dev/null +++ b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domain/mail/MailInfo.java @@ -0,0 +1,35 @@ +package com.coderising.ood.srp.domain.mail; + +/** + * Created by justin on 17/6/12. + */ +public class MailInfo { + private String toAddress; + private String subject; + private String message; + + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domain/product/ProductInfo.java b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domain/product/ProductInfo.java new file mode 100644 index 0000000000..2bc2be9d1e --- /dev/null +++ b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/domain/product/ProductInfo.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp.domain.product; + +/** + * Created by justin on 17/6/12. + */ +public class ProductInfo { + private String productID; + private String productDesc; + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git a/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/service/ProductInfoService.java b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/service/ProductInfoService.java new file mode 100644 index 0000000000..32b1733564 --- /dev/null +++ b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/service/ProductInfoService.java @@ -0,0 +1,44 @@ +package com.coderising.ood.srp.service; + +import com.coderising.ood.srp.domain.product.ProductInfo; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.net.URL; + +/** + * Created by justin on 17/6/19. + */ +public class ProductInfoService { + + public ProductInfo selectProduct() { +// File file = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + URL base = Thread.currentThread().getContextClassLoader().getResource(""); + File file = new File(base.getFile(),"product_promotion.txt"); + BufferedReader br = null; + ProductInfo productInfo = new ProductInfo(); + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + productInfo.setProductID(data[0]); + productInfo.setProductDesc(data[1]); + + System.out.println("产品ID = " + productInfo.getProductID() + "\n"); + System.out.println("产品描述 = " + productInfo.getProductDesc() + "\n"); + + } catch (IOException e) { +// throw new IOException(e.getMessage()); + } finally { + try { + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return productInfo; + } +} diff --git a/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/service/PromotionMailService.java b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/service/PromotionMailService.java new file mode 100644 index 0000000000..248d0b7a64 --- /dev/null +++ b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/service/PromotionMailService.java @@ -0,0 +1,52 @@ +package com.coderising.ood.srp.service; + +import com.coderising.ood.srp.util.MailUtil; +import com.coderising.ood.srp.domain.mail.MailConfigInfo; +import com.coderising.ood.srp.domain.mail.MailInfo; + +import java.util.Iterator; +import java.util.List; + +/** + * Created by justin on 17/6/12. + */ +public class PromotionMailService { + + public void sendEMails(MailConfigInfo mailConfigInfo, List mailInfos, boolean debug) + { + + System.out.println("开始发送邮件"); + + + if (mailInfos != null) { + Iterator iter = mailInfos.iterator(); + while (iter.hasNext()) { + MailInfo mailInfo = (MailInfo) iter.next(); + + try + { + if (mailInfo.getToAddress().length() > 0) + MailUtil.sendEmail(mailInfo.getToAddress(), mailConfigInfo.getFromAddress(), mailInfo.getSubject(), mailInfo.getMessage(), + mailConfigInfo.getSmtpHost(), debug); + } + catch (Exception e) + { + try { + MailUtil.sendEmail(mailInfo.getToAddress(), mailConfigInfo.getFromAddress(), mailInfo.getSubject(), mailInfo.getMessage(), + mailConfigInfo.getAltSmtpHost(), debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + } + + else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/service/UserService.java b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/service/UserService.java new file mode 100644 index 0000000000..bed06d4306 --- /dev/null +++ b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/service/UserService.java @@ -0,0 +1,15 @@ +package com.coderising.ood.srp.service; + +import com.coderising.ood.srp.dao.UserDao; + +import java.util.List; + +/** + * Created by justin on 17/6/19. + */ +public class UserService { + + public List querySubscriptions(String productId) { + return new UserDao().querySubscriptions(productId); + } +} diff --git a/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/DBUtil.java b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/DBUtil.java new file mode 100644 index 0000000000..f18e812954 --- /dev/null +++ b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/DBUtil.java @@ -0,0 +1,26 @@ +package com.coderising.ood.srp.util; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List> query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java new file mode 100644 index 0000000000..bb028c690c --- /dev/null +++ b/students/82180735/ood/ood-assignment/src/main/java/com/coderising/ood/srp/util/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp.util; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/82180735/ood/ood-assignment/src/main/resources/product_promotion.txt b/students/82180735/ood/ood-assignment/src/main/resources/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/82180735/ood/ood-assignment/src/main/resources/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/840145455/readme.md b/students/840145455/readme.md new file mode 100644 index 0000000000..6afb392c20 --- /dev/null +++ b/students/840145455/readme.md @@ -0,0 +1 @@ +愿意自荐代码的,可以每个人一个目录 以自己的QQ号命名 ,把自荐的代码放到里边去 diff --git a/students/861924479/src/com/learning/test/Test.java b/students/861924479/src/com/learning/test/Test.java new file mode 100644 index 0000000000..df9a26ef20 --- /dev/null +++ b/students/861924479/src/com/learning/test/Test.java @@ -0,0 +1,5 @@ +package com.learning.test; + +public class Test { + +} diff --git a/students/862726639/pom.xml b/students/862726639/pom.xml new file mode 100644 index 0000000000..cac49a5328 --- /dev/null +++ b/students/862726639/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.coderising + ood-assignment + 0.0.1-SNAPSHOT + jar + + ood-assignment + http://maven.apache.org + + + UTF-8 + + + + + + junit + junit + 4.12 + + + + + + aliyunmaven + http://maven.aliyun.com/nexus/content/groups/public/ + + + diff --git a/students/862726639/src/main/java/com/coderising/ood/srp/Email.java b/students/862726639/src/main/java/com/coderising/ood/srp/Email.java new file mode 100644 index 0000000000..fd2d231ecb --- /dev/null +++ b/students/862726639/src/main/java/com/coderising/ood/srp/Email.java @@ -0,0 +1,145 @@ +package com.coderising.ood.srp; + +import java.io.IOException; +import org.apache.commons.mail.EmailException; +import org.apache.commons.mail.HtmlEmail; +/** + * 只提交发送邮件的功能,主邮箱,备用邮箱需要赋予 + * @author gaohuan + * + */ +public class Email { + public static final String ENCODEING = "UTF-8"; + + private String host; // 服务器地址 + + private String sender; // 发件人的邮箱 + + private String receiver; // 收件人的邮箱 + + private String name; // 发件人昵称 + + private String username; // 账号 + + private String password; // 密码 + + private String subject; // 主题 + + private String message; // 信息(支持HTML) + + public boolean send2(Email mail) { + if ("".equals(mail.getReceiver())&&null == mail.getReceiver()) { + return false; + } + System.out.println("开始发送邮件"); + // 发送email + HtmlEmail email = new HtmlEmail(); + try { + // 这里是SMTP发送服务器的名字:163的如下:"smtp.163.com" + email.setHostName(mail.getHost()); + // 字符编码集的设置 + email.setCharset("utf-8"); + // 收件人的邮箱 + email.addTo(mail.getReceiver()); + // 发送人的邮箱 + email.setFrom(mail.getSender(), mail.getName()); + // 如果需要认证信息的话,设置认证:用户名-密码。分别为发件人在邮件服务器上的注册名称和密码 + email.setAuthentication(mail.getUsername(), mail.getPassword()); + // 要发送的邮件主题 + email.setSubject(mail.getSubject()); + // 要发送的信息,由于使用了HtmlEmail,可以在邮件内容中使用HTML标签 + email.setMsg(mail.getMessage()); + // 发送 + email.send(); + System.out.println(mail.getSender() + " 发送邮件到 " + mail.getReceiver()); + return true; + } catch (EmailException e) { + e.printStackTrace(); + System.out.println(mail.getSender() + " 发送邮件到 " + mail.getReceiver() + + " 失败"); + return false; + } + } + + + public String getHost() { + return host; + } + + + public void setHost(String host) { + this.host = host; + } + + + public String getSender() { + return sender; + } + + + public void setSender(String sender) { + this.sender = sender; + } + + + public String getReceiver() { + return receiver; + } + + + public void setReceiver(String receiver) { + this.receiver = receiver; + } + + + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + public String getUsername() { + return username; + } + + + public void setUsername(String username) { + this.username = username; + } + + + public String getPassword() { + return password; + } + + + public void setPassword(String password) { + this.password = password; + } + + + public String getSubject() { + return subject; + } + + + public void setSubject(String subject) { + this.subject = subject; + } + + + public String getMessage() { + return message; + } + + + public void setMessage(String message) { + this.message = message; + } + + +} diff --git a/students/862726639/src/main/java/com/coderising/ood/srp/Goods.java b/students/862726639/src/main/java/com/coderising/ood/srp/Goods.java new file mode 100644 index 0000000000..376bc87de2 --- /dev/null +++ b/students/862726639/src/main/java/com/coderising/ood/srp/Goods.java @@ -0,0 +1,79 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +/** + * 这个类的作用只是用于获取资源文件中的降价商品 + * @author gaohuan + * + */ +public class Goods { + private String productID; + private String productDesc; + + /** + * 获得降价 + * @return + * @throws IOException + */ + @SuppressWarnings("finally") + public ArrayList getSaleGoods() throws IOException { + ArrayList goodsList = new ArrayList(); + File file = new File("src\\main\\java\\com\\coderising\\ood\\srp\\product_promotion.txt"); + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + Goods goods = new Goods(data[0], data[1]); + goodsList.add(goods); + System.out.println("产品ID = " + goods.getProductID() + "\n"); + System.out.println("产品描述 = " + goods.getProductDesc() + "\n"); + + } catch (Exception e) { + e.printStackTrace(); + } finally { + br.close(); + return goodsList; + } + } + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + + public Goods() { + super(); + } + + public Goods(String productID, String productDesc) { + super(); + this.productID = productID; + this.productDesc = productDesc; + } + + + + + + + + + + +} diff --git a/students/862726639/src/main/java/com/coderising/ood/srp/Main.java b/students/862726639/src/main/java/com/coderising/ood/srp/Main.java new file mode 100644 index 0000000000..1e347cdd18 --- /dev/null +++ b/students/862726639/src/main/java/com/coderising/ood/srp/Main.java @@ -0,0 +1,35 @@ +package com.coderising.ood.srp; + +import java.io.IOException; +import java.util.ArrayList; + +import org.junit.Test; + +public class Main { + //发送邮件 + @Test + public void test() throws Exception{ + //获得降价商品 + Goods goods = new Goods(); + ArrayList saleGoods = goods.getSaleGoods(); + //获得对应用户 + for (Goods goods2 : saleGoods) { + User user = new User(); + ArrayList userById = user.getUserById(goods2.getProductID()); + for (User user2 : userById) { + //发送邮件 + Email email = new Email(); + email.setHost("smtp.163.com"); // 设置邮件服务器,如果不用163的,自己找找看相关的 + email.setSender("15237140070@163.com"); + email.setReceiver(user2.getEmail()); // 接收人 + email.setUsername("15237140070@163.com"); // 登录账号,一般都是和邮箱名一样吧 + email.setPassword("sudan521"); // 发件人邮箱的登录密码 + email.setSubject("降价了降价了"); + email.setMessage(Message.saleMessage(user2.getName(), goods2.getProductDesc())+""); + email.send2(email); + + } + } + } + +} diff --git a/students/862726639/src/main/java/com/coderising/ood/srp/Message.java b/students/862726639/src/main/java/com/coderising/ood/srp/Message.java new file mode 100644 index 0000000000..af09775311 --- /dev/null +++ b/students/862726639/src/main/java/com/coderising/ood/srp/Message.java @@ -0,0 +1,12 @@ +package com.coderising.ood.srp; + +public class Message { + + public static StringBuilder saleMessage(String userName ,String goodsName){ + StringBuilder buffer = new StringBuilder(); + buffer.append("Subject:").append("您关注的产品降价了").append("\n"); + buffer.append("Content:").append("尊敬的 "+userName+", 您关注的产品 " + goodsName + " 降价了,欢迎购买!").append("\n"); + return buffer; + } + +} diff --git a/students/862726639/src/main/java/com/coderising/ood/srp/User.java b/students/862726639/src/main/java/com/coderising/ood/srp/User.java new file mode 100644 index 0000000000..8821a97490 --- /dev/null +++ b/students/862726639/src/main/java/com/coderising/ood/srp/User.java @@ -0,0 +1,53 @@ +package com.coderising.ood.srp; + +import java.util.ArrayList; +public class User { + private String name; + private String email; + + + /** + * 通过降价商品的id 获取需要返回的用户 + * @param productID + * @return + */ + public ArrayList getUserById(String productID){ + ArrayList userList = new ArrayList(); + userList.add(new User("高欢1","15582372277@163.com")); + userList.add(new User("高欢2")); + userList.add(new User("高欢3")); + return userList; + } + + public User(String name, String email) { + super(); + this.name = name; + this.email = email; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + public User(String name) { + super(); + this.name = name; + } + + public User() { + super(); + // TODO Auto-generated constructor stub + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + +} diff --git a/students/862726639/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/862726639/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/862726639/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/89460886/ood/srp/Configuration.java b/students/89460886/ood/srp/Configuration.java new file mode 100644 index 0000000000..20cb685583 --- /dev/null +++ b/students/89460886/ood/srp/Configuration.java @@ -0,0 +1,25 @@ +package ood.srp; + +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + return configurations.get(key); + } + + +} diff --git a/students/89460886/ood/srp/ConfigurationKeys.java b/students/89460886/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..47cf4153b3 --- /dev/null +++ b/students/89460886/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/89460886/ood/srp/DBUtil.java b/students/89460886/ood/srp/DBUtil.java new file mode 100644 index 0000000000..89dbacc9bf --- /dev/null +++ b/students/89460886/ood/srp/DBUtil.java @@ -0,0 +1,43 @@ +package ood.srp; + +import java.util.ArrayList; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + List userList = new ArrayList<>(); + for (int i = 1; i <= 3; i++) { + User user = new User(); + user.setName("User" + i); + user.setEmail("aa@bb.com"); + userList.add(user); + } + return userList; + } + + public static List queryValidUserList(String sql) { + List userList = query(sql); + List resultList = new ArrayList<>(); + for (int i = 0, len = userList.size(); i < len; i++) { + String email = userList.get(i).getEmail(); + if (email != null && email.length() > 0) { + resultList.add(userList.get(i)); + } + } + return resultList; + } + + public static List queryUserListByProduct(Product product) { + String sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + product.getProductID() + "' " + + "and send_mail=1 "; + return queryValidUserList(sendMailQuery); + } + +} diff --git a/students/89460886/ood/srp/IRequest.java b/students/89460886/ood/srp/IRequest.java new file mode 100644 index 0000000000..5d15088f60 --- /dev/null +++ b/students/89460886/ood/srp/IRequest.java @@ -0,0 +1,16 @@ +package ood.srp; + +import java.util.Map; + +/** + * @author jiaxun + */ +public interface IRequest { + + Map getHeaders(); + + Map getParams(); + + String getUrl(); + +} diff --git a/students/89460886/ood/srp/MailRequest.java b/students/89460886/ood/srp/MailRequest.java new file mode 100644 index 0000000000..62b9c6ed52 --- /dev/null +++ b/students/89460886/ood/srp/MailRequest.java @@ -0,0 +1,57 @@ +package ood.srp; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author jiaxun + */ +public class MailRequest implements IRequest { + + private String toAddress; + private String subject; + private String message; + + @Override + public Map getHeaders() { + return null; + } + + @Override + public Map getParams() { + Map map = new HashMap<>(); + map.put("toAddress", toAddress); + map.put("subject", subject); + map.put("message", message); + return map; + } + + @Override + public String getUrl() { + return null; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } +} diff --git a/students/89460886/ood/srp/Product.java b/students/89460886/ood/srp/Product.java new file mode 100644 index 0000000000..f92235f0a7 --- /dev/null +++ b/students/89460886/ood/srp/Product.java @@ -0,0 +1,26 @@ +package ood.srp; + +/** + * @author jiaxun + */ +public class Product { + + private String productID = null; + private String productDesc = null; + + public String getProductID() { + return productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git a/students/89460886/ood/srp/ProductRepository.java b/students/89460886/ood/srp/ProductRepository.java new file mode 100644 index 0000000000..0c987504ac --- /dev/null +++ b/students/89460886/ood/srp/ProductRepository.java @@ -0,0 +1,38 @@ +package ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +/** + * @author jiaxun + */ +public class ProductRepository { + + public static Product getProductFromFile(File file) throws IOException { + Product product = null; + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String line = br.readLine(); + String[] data = line.split(" "); + + product = new Product(); + product.setProductID(data[0]); + product.setProductDesc(data[1]); + + System.out.println("产品ID = " + product.getProductID() + "\n"); + System.out.println("产品描述 = " + product.getProductDesc() + "\n"); + + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (br != null) { + br.close(); + } + } + return product; + } + +} diff --git a/students/89460886/ood/srp/PromotionMail.java b/students/89460886/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..199a80a7cc --- /dev/null +++ b/students/89460886/ood/srp/PromotionMail.java @@ -0,0 +1,42 @@ +package ood.srp; + +import java.io.File; +import java.util.List; + +public class PromotionMail { + + public static void main(String[] args) throws Exception { + + File file = new File("/Users/jiaxun/OpenSource/Algorithm/src/ood/srp/product_promotion.txt"); + boolean emailDebug = false; + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + Product product = ProductRepository.getProductFromFile(file); + + List userList = DBUtil.queryUserListByProduct(product); + + PromotionMail pe = new PromotionMail(); + + pe.sendEMails(emailDebug, userList, product); + } + + protected void sendEMails(boolean debug, List userList, Product product) { + + System.out.println("开始发送邮件"); + + if (userList != null) { + for (int i = 0, len = userList.size(); i < len; i++) { + MailRequest mailRequest = new MailRequest(); + + mailRequest.setSubject("您关注的产品降价了"); + mailRequest.setMessage("尊敬的 " + userList.get(i).getName() + ", 您关注的产品 " + product.getProductDesc() + " 降价了,欢迎购买!"); + mailRequest.setToAddress(userList.get(i).getEmail()); + + SmtpClient.sharedInstance().sendEmail(mailRequest, debug); + } + } else { + System.out.println("没有邮件发送"); + } + } + +} diff --git a/students/89460886/ood/srp/SmtpClient.java b/students/89460886/ood/srp/SmtpClient.java new file mode 100644 index 0000000000..a0c52b6fc3 --- /dev/null +++ b/students/89460886/ood/srp/SmtpClient.java @@ -0,0 +1,45 @@ +package ood.srp; + +import java.util.Map; + +/** + * @author jiaxun + */ +public class SmtpClient { + + private static volatile SmtpClient instance = null; + + private String smtpHost = null; + private String altSmtpHost = null; + private String fromAddress = null; + + private SmtpClient() { + Configuration config = new Configuration(); + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + public static SmtpClient sharedInstance() { + if (instance == null) { + synchronized (SmtpClient.class) { + if (instance == null) { + return new SmtpClient(); + } + } + } + return instance; + } + + public void sendEmail(IRequest request, boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + Map params = request.getParams(); + // 这里为了演示方便,直接根据请求的 key 获取内容 + buffer.append("To:").append(params.get("toAddress")).append("\n"); + buffer.append("Subject:").append(params.get("subject")).append("\n"); + buffer.append("Content:").append(params.get("message")).append("\n"); + System.out.println(buffer.toString()); + } +} diff --git a/students/89460886/ood/srp/User.java b/students/89460886/ood/srp/User.java new file mode 100644 index 0000000000..71bc2b7702 --- /dev/null +++ b/students/89460886/ood/srp/User.java @@ -0,0 +1,26 @@ +package ood.srp; + +/** + * @author jiaxun + */ +public class User { + + private String name; + private String email; + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/students/89460886/ood/srp/product_promotion.txt b/students/89460886/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/89460886/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/919442958/README.md b/students/919442958/README.md new file mode 100644 index 0000000000..d96760c4ae --- /dev/null +++ b/students/919442958/README.md @@ -0,0 +1 @@ +这是919442958的作业。1234 12 \ No newline at end of file diff --git a/students/932235900/src/com/coderising/ood/srp/PromotaionTest.java b/students/932235900/src/com/coderising/ood/srp/PromotaionTest.java new file mode 100644 index 0000000000..04bc17a433 --- /dev/null +++ b/students/932235900/src/com/coderising/ood/srp/PromotaionTest.java @@ -0,0 +1,34 @@ +package com.coderising.ood.srp; + +import java.util.List; + +import com.coderising.ood.srp.common.Configuration; +import com.coderising.ood.srp.entity.Email; +import com.coderising.ood.srp.entity.Product; +import com.coderising.ood.srp.entity.User; +import com.coderising.ood.srp.service.EmailService; +import com.coderising.ood.srp.service.ProductService; +import com.coderising.ood.srp.service.UserService; + +public class PromotaionTest { + + public static void main(String[] args) { + //1.获得客户集合 + List users = new UserService().getUsers(); + //2.获得促销商品 + List products = new ProductService().getPromotionProducts("src\\com\\coderising\\ood\\srp\\common\\product_promotion.txt"); + //3.配置 + Configuration conf = new Configuration(); + //给每个用户发邮件 + EmailService emailService = new EmailService(); + for(User user:users ){ + + Email email = emailService.generateEmail(user, products, conf ); + + emailService.sendEmail(email); + + + } + + } +} diff --git a/students/932235900/src/com/coderising/ood/srp/common/Configuration.java b/students/932235900/src/com/coderising/ood/srp/common/Configuration.java new file mode 100644 index 0000000000..4565927da1 --- /dev/null +++ b/students/932235900/src/com/coderising/ood/srp/common/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp.common; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/932235900/src/com/coderising/ood/srp/common/ConfigurationKeys.java b/students/932235900/src/com/coderising/ood/srp/common/ConfigurationKeys.java new file mode 100644 index 0000000000..a0064e0e4d --- /dev/null +++ b/students/932235900/src/com/coderising/ood/srp/common/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp.common; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/932235900/src/com/coderising/ood/srp/common/DBUtil.java b/students/932235900/src/com/coderising/ood/srp/common/DBUtil.java new file mode 100644 index 0000000000..6e333a508c --- /dev/null +++ b/students/932235900/src/com/coderising/ood/srp/common/DBUtil.java @@ -0,0 +1,26 @@ +package com.coderising.ood.srp.common; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import com.coderising.ood.srp.entity.User; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + User user = new User(); + user.setUserName("User" + i); + user.setEmailAddress("aa"+i+"@bb.com"); + userList.add(user); + } + return userList; + } +} diff --git a/students/932235900/src/com/coderising/ood/srp/common/product_promotion.txt b/students/932235900/src/com/coderising/ood/srp/common/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/932235900/src/com/coderising/ood/srp/common/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/932235900/src/com/coderising/ood/srp/entity/Email.java b/students/932235900/src/com/coderising/ood/srp/entity/Email.java new file mode 100644 index 0000000000..dd13c4fab1 --- /dev/null +++ b/students/932235900/src/com/coderising/ood/srp/entity/Email.java @@ -0,0 +1,46 @@ +package com.coderising.ood.srp.entity; +/** + * + * @author liubin + *电子邮件实体类 + */ +public class Email { + + private String toAddress; + private String fromAddress; + private String subject; + private String message; + private String smtpHost; + + public String getToAddress() { + return toAddress; + } + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + public String getFromAddress() { + return fromAddress; + } + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + public String getSubject() { + return subject; + } + public void setSubject(String subject) { + this.subject = subject; + } + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + public String getSmtpHost() { + return smtpHost; + } + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + +} diff --git a/students/932235900/src/com/coderising/ood/srp/entity/Product.java b/students/932235900/src/com/coderising/ood/srp/entity/Product.java new file mode 100644 index 0000000000..dffa593397 --- /dev/null +++ b/students/932235900/src/com/coderising/ood/srp/entity/Product.java @@ -0,0 +1,31 @@ +package com.coderising.ood.srp.entity; +/** + * + * @author liubin + * 产品实体类 + * + */ +public class Product { + + private String productId; + private String productDesc; + + public String getProductId() { + return productId; + } + public void setProductId(String productId) { + this.productId = productId; + } + public String getProductDesc() { + return productDesc; + } + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + @Override + public String toString() { + return "Product [产品ID = " + productId + ", 产品描述 = " + productDesc + "]"; + } + + +} diff --git a/students/932235900/src/com/coderising/ood/srp/entity/User.java b/students/932235900/src/com/coderising/ood/srp/entity/User.java new file mode 100644 index 0000000000..bd85ceac8f --- /dev/null +++ b/students/932235900/src/com/coderising/ood/srp/entity/User.java @@ -0,0 +1,29 @@ +package com.coderising.ood.srp.entity; + +public class User { + private String userId; + private String userName; + private String emailAddress; + + public String getUserId() { + return userId; + } + public void setUserId(String userId) { + this.userId = userId; + } + public String getUserName() { + return userName; + } + public void setUserName(String userName) { + this.userName = userName; + } + public String getEmailAddress() { + return emailAddress; + } + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } + + + +} diff --git a/students/932235900/src/com/coderising/ood/srp/service/EmailService.java b/students/932235900/src/com/coderising/ood/srp/service/EmailService.java new file mode 100644 index 0000000000..9455ba57a5 --- /dev/null +++ b/students/932235900/src/com/coderising/ood/srp/service/EmailService.java @@ -0,0 +1,43 @@ +package com.coderising.ood.srp.service; + +import java.util.List; + +import com.coderising.ood.srp.common.Configuration; +import com.coderising.ood.srp.common.ConfigurationKeys; +import com.coderising.ood.srp.entity.Email; +import com.coderising.ood.srp.entity.Product; +import com.coderising.ood.srp.entity.User; + +public class EmailService { + + public Email generateEmail(User user,List products,Configuration configuration){ + Email email = new Email(); + email.setFromAddress(configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN)); + email.setToAddress(user.getEmailAddress()); + email.setSubject("您关注的产品降价了"); + StringBuffer message=new StringBuffer("尊敬的 "+user.getUserName()+", 您关注的产品:"); + for(Product product:products){ + message.append(product.getProductDesc()+" "); + } + message.append("降价了,欢迎购买!"); + email.setMessage(message.toString()); + return email; + } + /** + * 发送一封Email + * @param email + */ + public void sendEmail(Email email){ + if(email != null ){ + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(email.getFromAddress()).append("\n"); + buffer.append("To:").append(email.getToAddress()).append("\n"); + buffer.append("Subject:").append(email.getSubject()).append("\n"); + buffer.append("Content:").append(email.getMessage()).append("\n"); + System.out.println(buffer.toString()); + }else{ + System.out.println("email 为空,发送邮件失败!"); + } + } +} diff --git a/students/932235900/src/com/coderising/ood/srp/service/ProductService.java b/students/932235900/src/com/coderising/ood/srp/service/ProductService.java new file mode 100644 index 0000000000..1762527fa6 --- /dev/null +++ b/students/932235900/src/com/coderising/ood/srp/service/ProductService.java @@ -0,0 +1,59 @@ +package com.coderising.ood.srp.service; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import com.coderising.ood.srp.entity.Product; + +public class ProductService { + + /** + * 从给定的路径文件获取打折商品信息 + * @param path + * @return + */ + public List getPromotionProducts(String path){ + List products = new ArrayList(); + if(path != null && !"".equals(path)){ + File file = new File(path); + try { + products = readFile(file); + } catch (IOException e) { + System.out.println("获取打折商品信息出错:"+ e.getMessage()); + } + } + return products; + } + + private List readFile(File file) throws IOException // @02C + { + List products = new ArrayList(); + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = null; + while((temp = br.readLine()) != null){ + + String[] data = temp.split(" "); + + Product product = new Product(); + product.setProductId(data[0]); + product.setProductDesc(data[1]); + System.out.println(product); + + products.add(product); + } + return products; + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + if(br != null){ + br.close(); + } + } + } +} diff --git a/students/932235900/src/com/coderising/ood/srp/service/UserService.java b/students/932235900/src/com/coderising/ood/srp/service/UserService.java new file mode 100644 index 0000000000..d8bc1b67d6 --- /dev/null +++ b/students/932235900/src/com/coderising/ood/srp/service/UserService.java @@ -0,0 +1,17 @@ +package com.coderising.ood.srp.service; + +import java.util.List; + +import com.coderising.ood.srp.common.DBUtil; +import com.coderising.ood.srp.entity.User; + +public class UserService { + /** + * 获取客户列表 + */ + public List getUsers(){ + String sendMailQuery = "Select name from subscriptions " + + "where send_mail=1 "; + return DBUtil.query(sendMailQuery); + } +} diff --git "a/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/SRP\346\265\201\347\250\213.png" "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/SRP\346\265\201\347\250\213.png" new file mode 100644 index 0000000000..638b75e7eb Binary files /dev/null and "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/SRP\346\265\201\347\250\213.png" differ diff --git "a/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/PromotionMail.java" "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/PromotionMail.java" new file mode 100644 index 0000000000..7e1c102f25 --- /dev/null +++ "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/PromotionMail.java" @@ -0,0 +1,67 @@ +package com.coderising.ood.srp_restructure_1; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import com.coderising.ood.srp_restructure_1.pojo.Configuration; +import com.coderising.ood.srp_restructure_1.pojo.ConfigurationKeys; +import com.coderising.ood.srp_restructure_1.pojo.Mail; +import com.coderising.ood.srp_restructure_1.pojo.MailServiceConfiguration; +import com.coderising.ood.srp_restructure_1.pojo.Product; +import com.coderising.ood.srp_restructure_1.pojo.User; +import com.coderising.ood.srp_restructure_1.service.ProductService; +import com.coderising.ood.srp_restructure_1.service.UserService; +import com.coderising.ood.srp_restructure_1.util.DBUtil; +import com.coderising.ood.srp_restructure_1.util.MailUtil; + +public class PromotionMail { + + UserService userService = new UserService(); + ProductService productService = new ProductService(); + + public static void main(String[] args) throws Exception { + File file = new File("src/main/java/com/coderising/ood/srp_restructure_1/product_promotion.txt"); + boolean emailDebug = false; + PromotionMail pe = new PromotionMail(file, emailDebug); + } + + public PromotionMail(File file, boolean mailDebug) throws Exception { + MailServiceConfiguration configuration = new MailServiceConfiguration() + .setAltSMTPHost(ConfigurationKeys.SMTP_SERVER).setSMTPHost(ConfigurationKeys.ALT_SMTP_SERVER) + .setFromAddress(ConfigurationKeys.SMTP_SERVER); + List plist = productService.getProductDescList(file); + sendEMails(mailDebug, configuration, plist); + } + + protected void sendEMails(boolean debug, MailServiceConfiguration configuration, List plist) + throws IOException { + System.out.println("开始发送邮件"); + if (plist != null) { + Iterator piterator = plist.iterator(); + while (piterator.hasNext()) { + Product product = piterator.next(); + List ulist = userService.getSendMailUser(product); + if (ulist != null) { + Iterator uiterator = ulist.iterator(); + while (uiterator.hasNext()) { + User user = uiterator.next(); + Mail mail = new Mail("您关注的产品降价了", + "尊敬的 " + user.getName() + ", 您关注的产品 " + plist.get(0).getProductDesc() + " 降价了,欢迎购买!", + user.getEmail()); + MailUtil.sendEmail(debug, configuration, mail); + } + } else { + System.out.println("没有邮件发送"); + } + } + } else { + System.out.println("没有降价商品"); + } + } +} diff --git "a/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/pojo/Configuration.java" "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/pojo/Configuration.java" new file mode 100644 index 0000000000..56182957fa --- /dev/null +++ "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/pojo/Configuration.java" @@ -0,0 +1,26 @@ +package com.coderising.ood.srp_restructure_1.pojo; + +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static { + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git "a/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/pojo/ConfigurationKeys.java" "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/pojo/ConfigurationKeys.java" new file mode 100644 index 0000000000..6a5cdb35fc --- /dev/null +++ "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/pojo/ConfigurationKeys.java" @@ -0,0 +1,9 @@ +package com.coderising.ood.srp_restructure_1.pojo; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git "a/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/pojo/Mail.java" "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/pojo/Mail.java" new file mode 100644 index 0000000000..560809a8cb --- /dev/null +++ "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/pojo/Mail.java" @@ -0,0 +1,38 @@ +package com.coderising.ood.srp_restructure_1.pojo; + +public class Mail { + + private String subject; + private String message; + private String toAddress; + + public Mail(String subject, String message, String toAddress) { + this.subject = subject; + this.message = message; + this.toAddress = toAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } +} diff --git "a/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/pojo/MailServiceConfiguration.java" "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/pojo/MailServiceConfiguration.java" new file mode 100644 index 0000000000..cbdaaec27b --- /dev/null +++ "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/pojo/MailServiceConfiguration.java" @@ -0,0 +1,35 @@ +package com.coderising.ood.srp_restructure_1.pojo; + +public class MailServiceConfiguration { + + private String SMTPHost; + private String AltSMTPHost; + private String FromAddress; + + public String getSMTPHost() { + return SMTPHost; + } + + public MailServiceConfiguration setSMTPHost(String sMTPHost) { + SMTPHost = sMTPHost; + return this; + } + + public String getAltSMTPHost() { + return AltSMTPHost; + } + + public MailServiceConfiguration setAltSMTPHost(String altSMTPHost) { + AltSMTPHost = altSMTPHost; + return this; + } + + public String getFromAddress() { + return FromAddress; + } + + public MailServiceConfiguration setFromAddress(String fromAddress) { + FromAddress = fromAddress; + return this; + } +} diff --git "a/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/pojo/Product.java" "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/pojo/Product.java" new file mode 100644 index 0000000000..38de6f12e0 --- /dev/null +++ "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/pojo/Product.java" @@ -0,0 +1,23 @@ +package com.coderising.ood.srp_restructure_1.pojo; + +public class Product { + + private String productID; + private String productDesc; + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } +} diff --git "a/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/pojo/User.java" "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/pojo/User.java" new file mode 100644 index 0000000000..ebe5d134f3 --- /dev/null +++ "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/pojo/User.java" @@ -0,0 +1,23 @@ +package com.coderising.ood.srp_restructure_1.pojo; + +public class User { + + private String name; + private String email; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git "a/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/product_promotion.txt" "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/product_promotion.txt" new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/product_promotion.txt" @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git "a/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/service/ProductService.java" "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/service/ProductService.java" new file mode 100644 index 0000000000..d1353bc72b --- /dev/null +++ "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/service/ProductService.java" @@ -0,0 +1,39 @@ +package com.coderising.ood.srp_restructure_1.service; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import com.coderising.ood.srp_restructure_1.pojo.Product; + +public class ProductService { + + public List getProductDescList(File file) throws IOException { + List plist = new ArrayList(); + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + Product p = new Product(); + p.setProductID(data[0]); + p.setProductDesc(data[1]); + + System.out.println("产品ID = " + p.getProductID() + "\n"); + System.out.println("产品描述 = " + p.getProductDesc() + "\n"); + + plist.add(p); + return plist; + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + + } + +} diff --git "a/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/service/UserService.java" "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/service/UserService.java" new file mode 100644 index 0000000000..799f713ccf --- /dev/null +++ "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/service/UserService.java" @@ -0,0 +1,18 @@ +package com.coderising.ood.srp_restructure_1.service; + +import java.util.ArrayList; +import java.util.List; + +import com.coderising.ood.srp_restructure_1.pojo.Product; +import com.coderising.ood.srp_restructure_1.pojo.User; +import com.coderising.ood.srp_restructure_1.util.DBUtil; + +public class UserService { + + public List getSendMailUser(Product product) { + String sql = "Select name from subscriptions " + "where product_id= '" + product.getProductID() + "' " + + "and send_mail=1 "; + return DBUtil.query(sql); + } + +} diff --git "a/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/util/DBUtil.java" "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/util/DBUtil.java" new file mode 100644 index 0000000000..086893ec60 --- /dev/null +++ "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/util/DBUtil.java" @@ -0,0 +1,36 @@ +package com.coderising.ood.srp_restructure_1.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import com.coderising.ood.srp_restructure_1.pojo.User; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * + * @param sql + * @return + */ + public static List query(String sql) { + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + /* + * HashMap userInfo = new HashMap(); userInfo.put("NAME", "User" + + * i); userInfo.put("EMAIL", "aa@bb.com"); userList.add(userInfo); + */ + /* + * 因为在重构的时候使用了bean,所以为了方便直接改为返回beanlist + */ + User user = new User(); + user.setName("User" + i); + user.setEmail("aa@bb.com"); + userList.add(user); + } + + return userList; + } +} diff --git "a/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/util/MailUtil.java" "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/util/MailUtil.java" new file mode 100644 index 0000000000..ca44417827 --- /dev/null +++ "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/srp_restructure_1/util/MailUtil.java" @@ -0,0 +1,34 @@ +package com.coderising.ood.srp_restructure_1.util; + +import com.coderising.ood.srp_restructure_1.pojo.Mail; +import com.coderising.ood.srp_restructure_1.pojo.MailServiceConfiguration; + +public class MailUtil { + + private static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + // 假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + } + + public static void sendEmail(boolean debug, MailServiceConfiguration configuration, Mail mail) { + try { + if (mail.getToAddress().length() > 0) + sendEmail(mail.getToAddress(), configuration.getFromAddress(), mail.getSubject(), mail.getMessage(), + configuration.getSMTPHost(), debug); + } catch (Exception e) { + try { + sendEmail(mail.getToAddress(), configuration.getFromAddress(), mail.getSubject(), mail.getMessage(), + configuration.getAltSMTPHost(), debug); + + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } +} \ No newline at end of file diff --git "a/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/\345\216\237\345\247\213\346\265\201\347\250\213.png" "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/\345\216\237\345\247\213\346\265\201\347\250\213.png" new file mode 100644 index 0000000000..c2d8aceb83 Binary files /dev/null and "b/students/949603184/homework01-\351\207\215\346\236\204\351\202\256\344\273\266\345\217\221\351\200\201/\345\216\237\345\247\213\346\265\201\347\250\213.png" differ diff --git "a/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/LoggerUtil/Logger.java" "b/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/LoggerUtil/Logger.java" new file mode 100644 index 0000000000..63733b92e0 --- /dev/null +++ "b/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/LoggerUtil/Logger.java" @@ -0,0 +1,25 @@ +package com.coderising.ood.ocp.LoggerUtil; + +import com.coderising.ood.ocp.Log.BaseLog; +import com.coderising.ood.ocp.Log.PrintLog; +import com.coderising.ood.ocp.MsgUtil.BaseMsgTool; +import com.coderising.ood.ocp.MsgUtil.HandleMsgWithNone; + +public class Logger { + + private BaseMsgTool tool; + private BaseLog log; + + public Logger(BaseMsgTool tool, BaseLog log) { + this.tool = tool; + this.log = log; + } + + public void log(String msg) { + log.sendLog(tool.handleMsg(msg)); + } + + public static void main(String[] args) { + new Logger(new HandleMsgWithNone(), new PrintLog()).log("Hello world"); + } +} diff --git "a/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/MsgUtil/BaseMsgTool.java" "b/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/MsgUtil/BaseMsgTool.java" new file mode 100644 index 0000000000..412c02ba4b --- /dev/null +++ "b/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/MsgUtil/BaseMsgTool.java" @@ -0,0 +1,5 @@ +package com.coderising.ood.ocp.MsgUtil; + +public abstract class BaseMsgTool implements IMsgHandle{ + +} diff --git "a/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/MsgUtil/HandleMsgWithDate.java" "b/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/MsgUtil/HandleMsgWithDate.java" new file mode 100644 index 0000000000..e3f6798d11 --- /dev/null +++ "b/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/MsgUtil/HandleMsgWithDate.java" @@ -0,0 +1,9 @@ +package com.coderising.ood.ocp.MsgUtil; + +import com.coderising.ood.ocp.Util.DateUtil; + +public class HandleMsgWithDate extends BaseMsgTool { + public String handleMsg(String msg) { + return DateUtil.getCurrentDateAsString() + ": " + msg; + } +} diff --git "a/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/MsgUtil/HandleMsgWithNone.java" "b/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/MsgUtil/HandleMsgWithNone.java" new file mode 100644 index 0000000000..ae1b936637 --- /dev/null +++ "b/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/MsgUtil/HandleMsgWithNone.java" @@ -0,0 +1,7 @@ +package com.coderising.ood.ocp.MsgUtil; + +public class HandleMsgWithNone extends BaseMsgTool { + public String handleMsg(String msg) { + return msg; + } +} diff --git "a/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/MsgUtil/IMsgHandle.java" "b/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/MsgUtil/IMsgHandle.java" new file mode 100644 index 0000000000..e72a6672ea --- /dev/null +++ "b/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/MsgUtil/IMsgHandle.java" @@ -0,0 +1,7 @@ +package com.coderising.ood.ocp.MsgUtil; + +public interface IMsgHandle { + + String handleMsg(String msg); + +} diff --git "a/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/Util/DateUtil.java" "b/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/Util/DateUtil.java" new file mode 100644 index 0000000000..26e947e622 --- /dev/null +++ "b/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/Util/DateUtil.java" @@ -0,0 +1,7 @@ +package com.coderising.ood.ocp.Util; + +public class DateUtil { + public static String getCurrentDateAsString() { + return null; + } +} diff --git "a/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/Util/MailUtil.java" "b/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/Util/MailUtil.java" new file mode 100644 index 0000000000..d857e8ef56 --- /dev/null +++ "b/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/Util/MailUtil.java" @@ -0,0 +1,7 @@ +package com.coderising.ood.ocp.Util; + +public class MailUtil { + public static void send(String logMsg) { + + } +} diff --git "a/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/Util/SMSUtil.java" "b/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/Util/SMSUtil.java" new file mode 100644 index 0000000000..1affb5938d --- /dev/null +++ "b/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/Util/SMSUtil.java" @@ -0,0 +1,7 @@ +package com.coderising.ood.ocp.Util; + +public class SMSUtil { + public static void send(String logMsg) { + + } +} diff --git "a/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/\350\247\243\351\242\230\346\200\235\350\267\257.txt" "b/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/\350\247\243\351\242\230\346\200\235\350\267\257.txt" new file mode 100644 index 0000000000..bd6d6a03ba --- /dev/null +++ "b/students/949603184/homework02-\351\207\215\346\236\204\346\227\245\345\277\227\346\211\223\345\215\260/ocp_restructure_1/\350\247\243\351\242\230\346\200\235\350\267\257.txt" @@ -0,0 +1 @@ +http://lanyuanxiaoyao.com/2017/06/19/ocp-homework/ \ No newline at end of file diff --git "a/students/949603184/homework06-XML\347\273\223\347\202\271\347\224\237\346\210\220\345\231\250/DoubleLevelNesting/TagBuilder.java" "b/students/949603184/homework06-XML\347\273\223\347\202\271\347\224\237\346\210\220\345\231\250/DoubleLevelNesting/TagBuilder.java" new file mode 100644 index 0000000000..be8b594844 --- /dev/null +++ "b/students/949603184/homework06-XML\347\273\223\347\202\271\347\224\237\346\210\220\345\231\250/DoubleLevelNesting/TagBuilder.java" @@ -0,0 +1,71 @@ +package DoubleLevelNesting; + +import java.util.ArrayList; + +/** + * Tag构造器 + * + * @author LanyuanXiaoyao + * @create 2017-07-18 + */ +public class TagBuilder { + + private TagNode root; + private TagBuilder rootBuilder; + + public TagBuilder(String rootName) { + this.root = new TagNode(rootName); + this.root.setChildren(new ArrayList<>()); + this.root.setAttributes(new ArrayList<>()); + } + + public TagBuilder(String rootName, TagBuilder tagBuilder) { + this.root = new TagNode(rootName); + this.root.setChildren(new ArrayList<>()); + this.root.setAttributes(new ArrayList<>()); + this.rootBuilder = tagBuilder; + } + + public TagBuilder addChild(String childName) { + TagBuilder childBuilder = new TagBuilder(childName, this); + if (rootBuilder == null) + root.getChildren().add(childBuilder.build()); + else + rootBuilder.build().getChildren().add(childBuilder.build()); + return childBuilder; + } + + public TagBuilder setAttribute(String name, String value) { + TagNode.Attribute attribute = new TagNode.Attribute(name, value); + root.getAttributes().add(attribute); + return this; + } + + public TagBuilder end() { + return rootBuilder; + } + + public void toXML() { + if (rootBuilder == null) + System.out.println(root.toXML()); + else + rootBuilder.toXML(); + } + + public TagNode build() { + return root; + } + + public static void main(String[] args) { + new TagBuilder("root") + .setAttribute("attr3", "value") + .setAttribute("attr4", "value") + .addChild("child") + .setAttribute("attr1", "value") + .setAttribute("attr2", "value") + .addChild("child2") + .setAttribute("attr5", "value") + .setAttribute("attr6", "value") + .toXML(); + } +} diff --git "a/students/949603184/homework06-XML\347\273\223\347\202\271\347\224\237\346\210\220\345\231\250/DoubleLevelNesting/TagNode.java" "b/students/949603184/homework06-XML\347\273\223\347\202\271\347\224\237\346\210\220\345\231\250/DoubleLevelNesting/TagNode.java" new file mode 100644 index 0000000000..45fc5ac9b6 --- /dev/null +++ "b/students/949603184/homework06-XML\347\273\223\347\202\271\347\224\237\346\210\220\345\231\250/DoubleLevelNesting/TagNode.java" @@ -0,0 +1,94 @@ +package DoubleLevelNesting; + +import java.util.ArrayList; +import java.util.List; + +/** + * Tag节点 + * + * @author LanyuanXiaoyao + * @create 2017-07-18 + */ +public class TagNode { + private String tagName; + private String tagValue; + private List children = new ArrayList<>(); + private List attributes = new ArrayList<>(); + + public TagNode(String tagName) { + this.tagName = tagName; + } + + public String getTagName() { + return tagName; + } + + public void setTagName(String tagName) { + this.tagName = tagName; + } + + public String getTagValue() { + return tagValue; + } + + public void setTagValue(String tagValue) { + this.tagValue = tagValue; + } + + public List getChildren() { + return children; + } + + public void setChildren(List children) { + this.children = children; + } + + public List getAttributes() { + return attributes; + } + + public void setAttributes(List attributes) { + this.attributes = attributes; + } + + public static class Attribute { + public Attribute(String name, String value) { + this.name = name; + this.value = value; + } + + String name; + String value; + } + + public String toXML() { + return toXML(this); + } + + private String toXML(TagNode node) { + StringBuilder buffer = new StringBuilder(); + buffer.append("<").append(node.tagName); + if (node.attributes.size() > 0) { + for (int i = 0; i < node.attributes.size(); i++) { + Attribute attr = node.attributes.get(i); + buffer.append(" ").append(toXML(attr)); + } + } + if (node.children.size() == 0) { + buffer.append("/>"); + return buffer.toString(); + } + System.out.println(node.children.size()); + buffer.append(">"); + for (TagNode childNode : node.children) { + buffer.append(toXML(childNode)); + } + buffer.append(""); + + return buffer.toString(); + } + + private String toXML(Attribute attr) { + return attr.name + "=\"" + attr.value + "\""; + } +} diff --git "a/students/949603184/homework06-XML\347\273\223\347\202\271\347\224\237\346\210\220\345\231\250/MultiLevelNesting/TagBuilder.java" "b/students/949603184/homework06-XML\347\273\223\347\202\271\347\224\237\346\210\220\345\231\250/MultiLevelNesting/TagBuilder.java" new file mode 100644 index 0000000000..64b3a3d51a --- /dev/null +++ "b/students/949603184/homework06-XML\347\273\223\347\202\271\347\224\237\346\210\220\345\231\250/MultiLevelNesting/TagBuilder.java" @@ -0,0 +1,73 @@ +package MultiLevelNesting; + +import java.util.ArrayList; + +/** + * Tag构造器 + * + * @author LanyuanXiaoyao + * @create 2017-07-18 + */ +public class TagBuilder { + + private TagNode root; + private TagBuilder rootBuilder; + + public TagBuilder(String rootName) { + this.root = new TagNode(rootName); + this.root.setChildren(new ArrayList<>()); + this.root.setAttributes(new ArrayList<>()); + } + + public TagBuilder(String rootName, TagBuilder tagBuilder) { + this.root = new TagNode(rootName); + this.root.setChildren(new ArrayList<>()); + this.root.setAttributes(new ArrayList<>()); + this.rootBuilder = tagBuilder; + } + + public TagBuilder addChild(String childName) { + TagBuilder childBuilder = new TagBuilder(childName, this); + root.getChildren().add(childBuilder.toTagTreeNode()); + return childBuilder; + } + + public TagBuilder setAttribute(String name, String value) { + TagNode.Attribute attribute = new TagNode.Attribute(name, value); + root.getAttributes().add(attribute); + return this; + } + + public TagBuilder and() { + return rootBuilder; + } + + public void toXML() { + if (rootBuilder == null) + System.out.println(root.toXML()); + else + rootBuilder.toXML(); + } + + public TagNode toTagTreeNode() { + return root; + } + + public static void main(String[] args) { + new TagBuilder("root") + .setAttribute("attr0","0") + .addChild("child") + .setAttribute("attr1","1") + .setAttribute("attr1","1") + .setAttribute("attr1","1") + .addChild("child2") + .setAttribute("attr2","2") + .setAttribute("attr2","2") + .setAttribute("attr2","2") + .and() + .and() + .addChild("child3") + .setAttribute("attr3","3") + .toXML(); + } +} diff --git "a/students/949603184/homework06-XML\347\273\223\347\202\271\347\224\237\346\210\220\345\231\250/MultiLevelNesting/TagNode.java" "b/students/949603184/homework06-XML\347\273\223\347\202\271\347\224\237\346\210\220\345\231\250/MultiLevelNesting/TagNode.java" new file mode 100644 index 0000000000..421ca50850 --- /dev/null +++ "b/students/949603184/homework06-XML\347\273\223\347\202\271\347\224\237\346\210\220\345\231\250/MultiLevelNesting/TagNode.java" @@ -0,0 +1,93 @@ +package MultiLevelNesting; + +import java.util.ArrayList; +import java.util.List; + +/** + * Tag节点 + * + * @author LanyuanXiaoyao + * @create 2017-07-18 + */ +public class TagNode { + private String tagName; + private String tagValue; + private List children = new ArrayList<>(); + private List attributes = new ArrayList<>(); + + public TagNode(String tagName) { + this.tagName = tagName; + } + + public String getTagName() { + return tagName; + } + + public void setTagName(String tagName) { + this.tagName = tagName; + } + + public String getTagValue() { + return tagValue; + } + + public void setTagValue(String tagValue) { + this.tagValue = tagValue; + } + + public List getChildren() { + return children; + } + + public void setChildren(List children) { + this.children = children; + } + + public List getAttributes() { + return attributes; + } + + public void setAttributes(List attributes) { + this.attributes = attributes; + } + + public static class Attribute { + public Attribute(String name, String value) { + this.name = name; + this.value = value; + } + + String name; + String value; + } + + public String toXML() { + return toXML(this); + } + + private String toXML(TagNode node) { + StringBuilder buffer = new StringBuilder(); + buffer.append("<").append(node.tagName); + if (node.attributes.size() > 0) { + for (int i = 0; i < node.attributes.size(); i++) { + Attribute attr = node.attributes.get(i); + buffer.append(" ").append(toXML(attr)); + } + } + if (node.children.size() == 0) { + buffer.append("/>"); + return buffer.toString(); + } + buffer.append(">"); + for (TagNode childNode : node.children) { + buffer.append(toXML(childNode)); + } + buffer.append(""); + + return buffer.toString(); + } + + private String toXML(Attribute attr) { + return attr.name + "=\"" + attr.value + "\""; + } +} diff --git "a/students/949603184/homework06-XML\347\273\223\347\202\271\347\224\237\346\210\220\345\231\250/\345\210\206\345\210\253\345\256\236\347\216\260\344\272\206\344\270\244\345\261\202\345\265\214\345\245\227\345\222\214\345\244\232\345\261\202\345\265\214\345\245\227" "b/students/949603184/homework06-XML\347\273\223\347\202\271\347\224\237\346\210\220\345\231\250/\345\210\206\345\210\253\345\256\236\347\216\260\344\272\206\344\270\244\345\261\202\345\265\214\345\245\227\345\222\214\345\244\232\345\261\202\345\265\214\345\245\227" new file mode 100644 index 0000000000..e69de29bb2 diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/DateUtil.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/DateUtil.java new file mode 100644 index 0000000000..8defe31480 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/DateUtil.java @@ -0,0 +1,10 @@ +package com.github.wluqing.coding2017.basic.ood.ocp; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return null; + } + +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/Logger.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/Logger.java new file mode 100644 index 0000000000..34907a0ed9 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/Logger.java @@ -0,0 +1,38 @@ +package com.github.wluqing.coding2017.basic.ood.ocp; + +public class Logger { + + public final int RAW_LOG = 1; + public final int RAW_LOG_WITH_DATE = 2; + public final int EMAIL_LOG = 1; + public final int SMS_LOG = 2; + public final int PRINT_LOG = 3; + + int type = 0; + int method = 0; + + public Logger(int logType, int logMethod){ + this.type = logType; + this.method = logMethod; + } + public void log(String msg){ + + String logMsg = msg; + + if(this.type == RAW_LOG){ + logMsg = msg; + } else if(this.type == RAW_LOG_WITH_DATE){ + String txtDate = DateUtil.getCurrentDateAsString(); + logMsg = txtDate + ": " + msg; + } + + if(this.method == EMAIL_LOG){ + MailUtil.send(logMsg); + } else if(this.method == SMS_LOG){ + SMSUtil.send(logMsg); + } else if(this.method == PRINT_LOG){ + System.out.println(logMsg); + } + } +} + diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/MailUtil.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/MailUtil.java new file mode 100644 index 0000000000..d2b51e3abd --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/MailUtil.java @@ -0,0 +1,10 @@ +package com.github.wluqing.coding2017.basic.ood.ocp; + +public class MailUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/SMSUtil.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/SMSUtil.java new file mode 100644 index 0000000000..b499c47efb --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/SMSUtil.java @@ -0,0 +1,10 @@ +package com.github.wluqing.coding2017.basic.ood.ocp; + +public class SMSUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/good/Formatter.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/good/Formatter.java new file mode 100644 index 0000000000..642fbb35d6 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/good/Formatter.java @@ -0,0 +1,7 @@ +package com.github.wluqing.coding2017.basic.ood.ocp.good; + +public interface Formatter { + + String format(String msg); + +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/good/FormatterFactory.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/good/FormatterFactory.java new file mode 100644 index 0000000000..e0542f7be6 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/good/FormatterFactory.java @@ -0,0 +1,13 @@ +package com.github.wluqing.coding2017.basic.ood.ocp.good; + +public class FormatterFactory { + public static Formatter createFormatter(int type){ + if(type == 1){ + return new RawFormatter(); + } + if (type == 2){ + return new HtmlFormatter(); + } + return null; + } +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/good/HtmlFormatter.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/good/HtmlFormatter.java new file mode 100644 index 0000000000..d901191524 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/good/HtmlFormatter.java @@ -0,0 +1,11 @@ +package com.github.wluqing.coding2017.basic.ood.ocp.good; + +public class HtmlFormatter implements Formatter { + + @Override + public String format(String msg) { + + return null; + } + +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/good/Logger.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/good/Logger.java new file mode 100644 index 0000000000..8b0dce72b6 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/good/Logger.java @@ -0,0 +1,18 @@ +package com.github.wluqing.coding2017.basic.ood.ocp.good; + +public class Logger { + + private Formatter formatter; + private Sender sender; + + public Logger(Formatter formatter,Sender sender){ + this.formatter = formatter; + this.sender = sender; + } + public void log(String msg){ + sender.send(formatter.format(msg)) ; + } + + +} + diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/good/RawFormatter.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/good/RawFormatter.java new file mode 100644 index 0000000000..ecc8daff9e --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/good/RawFormatter.java @@ -0,0 +1,11 @@ +package com.github.wluqing.coding2017.basic.ood.ocp.good; + +public class RawFormatter implements Formatter { + + @Override + public String format(String msg) { + + return null; + } + +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/good/Sender.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/good/Sender.java new file mode 100644 index 0000000000..407ac9f2c2 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/ocp/good/Sender.java @@ -0,0 +1,7 @@ +package com.github.wluqing.coding2017.basic.ood.ocp.good; + +public interface Sender { + + void send(String msg); + +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/Affiliation.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/Affiliation.java new file mode 100644 index 0000000000..587ce68f29 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/Affiliation.java @@ -0,0 +1,5 @@ +package com.github.wluqing.coding2017.basic.ood.payroll; + +public interface Affiliation { + public double calculateDeductions(Paycheck pc); +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/Employee.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/Employee.java new file mode 100644 index 0000000000..8c7ee3a469 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/Employee.java @@ -0,0 +1,42 @@ +package com.github.wluqing.coding2017.basic.ood.payroll; + +import java.util.Date; + +public class Employee { + String id; + String name; + String address; + Affiliation affiliation; + + + PaymentClassification classification; + PaymentSchedule schedule; + PaymentMethod paymentMethod; + + public Employee(String name, String address){ + this.name = name; + this.address = address; + } + public boolean isPayDay(Date d) { + return false; + } + + public Date getPayPeriodStartDate(Date d) { + return null; + } + + public void payDay(Paycheck pc){ + + } + + public void setClassification(PaymentClassification classification) { + this.classification = classification; + } + public void setSchedule(PaymentSchedule schedule) { + this.schedule = schedule; + } + public void setPaymentMethod(PaymentMethod paymentMethod) { + this.paymentMethod = paymentMethod; + } +} + diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/Paycheck.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/Paycheck.java new file mode 100644 index 0000000000..c6ed31d5e3 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/Paycheck.java @@ -0,0 +1,35 @@ +package com.github.wluqing.coding2017.basic.ood.payroll; + +import java.util.Date; +import java.util.Map; + +public class Paycheck { + private Date payPeriodStart; + private Date payPeriodEnd; + private double grossPay; + private double netPay; + private double deductions; + + public Paycheck(Date payPeriodStart, Date payPeriodEnd){ + this.payPeriodStart = payPeriodStart; + this.payPeriodEnd = payPeriodEnd; + } + public void setGrossPay(double grossPay) { + this.grossPay = grossPay; + + } + public void setDeductions(double deductions) { + this.deductions = deductions; + } + public void setNetPay(double netPay){ + this.netPay = netPay; + } + public Date getPayPeriodEndDate() { + + return this.payPeriodEnd; + } + public Date getPayPeriodStartDate() { + + return this.payPeriodStart; + } +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/PaymentClassification.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/PaymentClassification.java new file mode 100644 index 0000000000..af249d9557 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/PaymentClassification.java @@ -0,0 +1,5 @@ +package com.github.wluqing.coding2017.basic.ood.payroll; + +public interface PaymentClassification { + public double calculatePay(Paycheck pc); +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/PaymentMethod.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/PaymentMethod.java new file mode 100644 index 0000000000..9b25d28fed --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/PaymentMethod.java @@ -0,0 +1,5 @@ +package com.github.wluqing.coding2017.basic.ood.payroll; + +public interface PaymentMethod { + public void pay(Paycheck pc); +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/PaymentSchedule.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/PaymentSchedule.java new file mode 100644 index 0000000000..63791efbb8 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/PaymentSchedule.java @@ -0,0 +1,8 @@ +package com.github.wluqing.coding2017.basic.ood.payroll; + +import java.util.Date; + +public interface PaymentSchedule { + public boolean isPayDate(Date date); + public Date getPayPeriodStartDate( Date payPeriodEndDate); +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/SalesReceipt.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/SalesReceipt.java new file mode 100644 index 0000000000..79c0d8882b --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/SalesReceipt.java @@ -0,0 +1,14 @@ +package com.github.wluqing.coding2017.basic.ood.payroll; + +import java.util.Date; + +public class SalesReceipt { + private Date saleDate; + private double amount; + public Date getSaleDate() { + return saleDate; + } + public double getAmount() { + return amount; + } +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/TimeCard.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/TimeCard.java new file mode 100644 index 0000000000..7860212a4d --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/payroll/TimeCard.java @@ -0,0 +1,15 @@ +package com.github.wluqing.coding2017.basic.ood.payroll; + +import java.util.Date; + +public class TimeCard { + private Date date; + private int hours; + + public Date getDate() { + return date; + } + public int getHours() { + return hours; + } +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/Configuration.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/Configuration.java new file mode 100644 index 0000000000..d431224c09 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.github.wluqing.coding2017.basic.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/ConfigurationKeys.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..87749f5066 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.github.wluqing.coding2017.basic.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/DBUtil.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/DBUtil.java new file mode 100644 index 0000000000..d4df5ad069 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.github.wluqing.coding2017.basic.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/MailUtil.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/MailUtil.java new file mode 100644 index 0000000000..82c1a3279a --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package com.github.wluqing.coding2017.basic.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/PromotionMail.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..0dba90c8ec --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/PromotionMail.java @@ -0,0 +1,199 @@ +package com.github.wluqing.coding2017.basic.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery = null; + + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected String productID = null; + protected String productDesc = null; + + private static Configuration config; + + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + + + config = new Configuration(); + + setSMTPHost(); + setAltSMTPHost(); + + + setFromAddress(); + + + setLoadQuery(); + + sendEMails(mailDebug, loadMailingList()); + + + } + + + + + protected void setProductID(String productID) + { + this.productID = productID; + + } + + protected String getproductID() + { + return productID; + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected void setSMTPHost() + { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() + { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + protected void setFromAddress() + { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setMessage(HashMap userInfo) throws IOException + { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + + + + } + + + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + private void setProductDesc(String desc) { + this.productDesc = desc; + } + + + protected void configureEMail(HashMap userInfo) throws IOException + { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try + { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } + + else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good/template/MailBodyTemplate.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good/template/MailBodyTemplate.java new file mode 100644 index 0000000000..87ef5a8c8b --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good/template/MailBodyTemplate.java @@ -0,0 +1,5 @@ +package com.github.wluqing.coding2017.basic.ood.srp.good.template; + +public interface MailBodyTemplate { + public String render(); +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good/template/TextMailBodyTemplate.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good/template/TextMailBodyTemplate.java new file mode 100644 index 0000000000..e515229473 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good/template/TextMailBodyTemplate.java @@ -0,0 +1,19 @@ +package com.github.wluqing.coding2017.basic.ood.srp.good.template; + +import java.util.Map; + +public class TextMailBodyTemplate implements MailBodyTemplate { + + private MapparamMap ; + + public TextMailBodyTemplate(Map map){ + paramMap = map; + } + + @Override + public String render() { + //使用某种模板技术实现Render + return null; + } + +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/Configuration.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/Configuration.java new file mode 100644 index 0000000000..71a78aae1e --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/Configuration.java @@ -0,0 +1,23 @@ +package com.github.wluqing.coding2017.basic.ood.srp.good1; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/ConfigurationKeys.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/ConfigurationKeys.java new file mode 100644 index 0000000000..928978a1b8 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.github.wluqing.coding2017.basic.ood.srp.good1; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/Mail.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/Mail.java new file mode 100644 index 0000000000..3d10b3d64a --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/Mail.java @@ -0,0 +1,27 @@ +package com.github.wluqing.coding2017.basic.ood.srp.good1; + +import java.util.List; + +public class Mail { + + private User user; + + public Mail(User u){ + this.user = u; + } + public String getAddress(){ + return user.getEMailAddress(); + } + public String getSubject(){ + return "您关注的产品降价了"; + } + public String getBody(){ + + return "尊敬的 "+user.getName()+", 您关注的产品 " + this.buildProductDescList() + " 降价了,欢迎购买!" ; + } + private String buildProductDescList() { + List products = user.getSubscribedProducts(); + //.... 实现略... + return null; + } +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/MailSender.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/MailSender.java new file mode 100644 index 0000000000..02487cbbd9 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/MailSender.java @@ -0,0 +1,35 @@ +package com.github.wluqing.coding2017.basic.ood.srp.good1; + +public class MailSender { + + private String fromAddress ; + private String smtpHost; + private String altSmtpHost; + + public MailSender(Configuration config){ + this.fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + this.smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + this.altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + } + + public void sendMail(Mail mail){ + try{ + sendEmail(mail,this.smtpHost); + }catch(Exception e){ + try{ + sendEmail(mail,this.altSmtpHost); + }catch (Exception ex){ + System.out.println("通过备用 SMTP服务器发送邮件失败: " + ex.getMessage()); + } + + } + } + + private void sendEmail(Mail mail, String smtpHost){ + + String toAddress = mail.getAddress(); + String subject = mail.getSubject(); + String msg = mail.getBody(); + //发送邮件 + } +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/Product.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/Product.java new file mode 100644 index 0000000000..1f19b2fe65 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/Product.java @@ -0,0 +1,14 @@ +package com.github.wluqing.coding2017.basic.ood.srp.good1; + + + +public class Product { + + private String id; + private String desc; + public String getDescription(){ + return desc; + } + + +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/ProductService.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/ProductService.java new file mode 100644 index 0000000000..0b3e061f51 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/ProductService.java @@ -0,0 +1,9 @@ +package com.github.wluqing.coding2017.basic.ood.srp.good1; + + +public class ProductService { + public Product getPromotionProduct(){ + //从文本文件中读取文件列表 + return null; + } +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/PromotionJob.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/PromotionJob.java new file mode 100644 index 0000000000..4dbe9fdd29 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/PromotionJob.java @@ -0,0 +1,24 @@ +package com.github.wluqing.coding2017.basic.ood.srp.good1; + +import java.util.List; + +public class PromotionJob { + + private ProductService productService = null ; //获取production service + private UserService userService = null ;// 获取UserService + + public void run(){ + + Configuration cfg = new Configuration(); + + Product p = productService.getPromotionProduct(); + + List users = userService.getUsers(p); + + MailSender mailSender = new MailSender(cfg); + + for(User user : users){ + mailSender.sendMail(new Mail(user)); + } + } +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/User.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/User.java new file mode 100644 index 0000000000..b5193a4755 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/User.java @@ -0,0 +1,24 @@ +package com.github.wluqing.coding2017.basic.ood.srp.good1; + +import java.util.List; + + + +public class User { + + private String name; + private String emailAddress; + + private List subscribedProducts; + + public String getName(){ + return name; + } + public String getEMailAddress() { + return emailAddress; + } + public List getSubscribedProducts(){ + return this.subscribedProducts; + } + +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/UserService.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/UserService.java new file mode 100644 index 0000000000..aaa6a58a0d --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good1/UserService.java @@ -0,0 +1,11 @@ +package com.github.wluqing.coding2017.basic.ood.srp.good1; + +import java.util.List; + +public class UserService { + + public List getUsers(Product product){ + //调用DAO相关的类从数据库中读取订阅产品的用户列表 + return null; + } +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good2/ProductService.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good2/ProductService.java new file mode 100644 index 0000000000..c5439cac5e --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good2/ProductService.java @@ -0,0 +1,12 @@ +package com.github.wluqing.coding2017.basic.ood.srp.good2; + +import java.util.List; + +import com.github.wluqing.coding2017.basic.ood.srp.good1.Product; + +public class ProductService { + public List getPromotionProducts(){ + //从文本文件中读取文件列表 + return null; + } +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good2/UserService.java b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good2/UserService.java new file mode 100644 index 0000000000..7813fb663c --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/good2/UserService.java @@ -0,0 +1,13 @@ +package com.github.wluqing.coding2017.basic.ood.srp.good2; + +import java.util.List; + +import com.github.wluqing.coding2017.basic.ood.srp.good1.Product; +import com.github.wluqing.coding2017.basic.ood.srp.good1.User; + +public class UserService { + public List getUsers(List products){ + //调用DAO相关的类从数据库中读取订阅产品的用户列表 + return null; + } +} diff --git a/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/product_promotion.txt b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/962040254/src/com/github/wluqing/coding2017/basic/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/977996067/pom.xml b/students/977996067/pom.xml new file mode 100644 index 0000000000..2c2630e332 --- /dev/null +++ b/students/977996067/pom.xml @@ -0,0 +1,24 @@ + + + 4.0.0 + + cc.javaone.coding2017 + ood-assignment + 1.0-SNAPSHOT + + + junit + junit + 4.12 + + + org.projectlombok + lombok + 1.16.18 + + + + + \ No newline at end of file diff --git a/students/977996067/src/main/java/com/coderising/dp/week1/TagBuilder.java b/students/977996067/src/main/java/com/coderising/dp/week1/TagBuilder.java new file mode 100644 index 0000000000..a31514a6fe --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week1/TagBuilder.java @@ -0,0 +1,63 @@ +package com.coderising.dp.week1; + +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +public class TagBuilder { + + private TagNode rootTag; + + private AtomicReference tempParentNode = new AtomicReference<>(); + + private AtomicReference currentNode = new AtomicReference<>(); + + public TagBuilder(String rootTagName) { + this.rootTag = new TagNode(); + rootTag.setTagName(rootTagName); + tempParentNode.set(rootTag); + currentNode.set(rootTag); + } + + public TagBuilder addChild(String childTagName) { + TagNode node = currentNode.get(); + tempParentNode.set(node); + currentNode.set(doAddChildren(node, childTagName)); + return this; + } + + private TagNode doAddChildren(TagNode node, String childTagName) { + List children = node.getChildren(); + TagNode childTag = new TagNode(); + childTag.setTagName(childTagName); + children.add(childTag); + return childTag; + } + + public TagBuilder addSibling(String childTagName) { + TagNode tagNode = tempParentNode.get(); + TagNode childTag = doAddChildren(tagNode, childTagName); + currentNode.set(childTag); + return this; + } + + public TagBuilder setAttribute(String key, String value) { + TagNode tagNode = currentNode.get(); + List attributes = tagNode.getAttributes(); + + TagNode.Attribute attribute = new TagNode.Attribute(); + attribute.setName(key); + attribute.setValue(value); + attributes.add(attribute); + return this; + } + + public String toXML() { + return rootTag.toString(); + } +} + + +// ~ HomeWork2 +// ======================================================================================================== + +// 单例的类: java.lang.Runtime \ No newline at end of file diff --git a/students/977996067/src/main/java/com/coderising/dp/week1/TagNode.java b/students/977996067/src/main/java/com/coderising/dp/week1/TagNode.java new file mode 100644 index 0000000000..6fa56abfdf --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week1/TagNode.java @@ -0,0 +1,91 @@ +package com.coderising.dp.week1; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +public class TagNode { + private String tagName; + private String tagValue; + private List children = new ArrayList<>(); + private List attributes = new ArrayList<>(); + + public String getTagName() { + return tagName; + } + + public void setTagName(String tagName) { + this.tagName = tagName; + } + + public String getTagValue() { + return tagValue; + } + + public void setTagValue(String tagValue) { + this.tagValue = tagValue; + } + + public List getChildren() { + return children; + } + + public void setChildren(List children) { + this.children = children; + } + + public List getAttributes() { + return attributes; + } + + public void setAttributes(List attributes) { + this.attributes = attributes; + } + + public static class Attribute { + String name; + String value; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + } + + @Override + public String toString() { + String lineBreaker = System.getProperty("line.separator"); + StringBuilder sb = new StringBuilder(); + sb.append("<").append(this.tagName); + if (!isEmpty(this.attributes)) { + attributes.forEach(attribute -> sb.append(" ") + .append(attribute.getName()) + .append("=\"") + .append(attribute.getValue()) + .append("\"")); + } + sb.append(">"); + if (!isEmpty(this.children)) { + sb.append(lineBreaker); + children.forEach(child -> sb.append(child.toString())); + } + sb.append(lineBreaker).append("").append(lineBreaker); + return sb.toString(); + + } + + private boolean isEmpty(Collection c) { + return c == null || c.size() == 0; + } +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week2/bridge/Circle.java b/students/977996067/src/main/java/com/coderising/dp/week2/bridge/Circle.java new file mode 100644 index 0000000000..c90c1b3889 --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week2/bridge/Circle.java @@ -0,0 +1,15 @@ +package com.coderising.dp.week2.bridge; + +public class Circle extends Shape { + + public Circle(Drawing drawing) { + super(drawing); + } + + @Override + public void draw() { + getDrawing().drawLine(); + getDrawing().drawCircle(); + System.out.println("I am drawing a circle ..."); + } +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week2/bridge/DrawClient.java b/students/977996067/src/main/java/com/coderising/dp/week2/bridge/DrawClient.java new file mode 100644 index 0000000000..c59cd73066 --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week2/bridge/DrawClient.java @@ -0,0 +1,9 @@ +package com.coderising.dp.week2.bridge; + +public class DrawClient { + + public static void main(String[] args) { + Drawing drawing = new DrawingGL1(); + new Rectangle(drawing).draw(); + } +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week2/bridge/Drawing.java b/students/977996067/src/main/java/com/coderising/dp/week2/bridge/Drawing.java new file mode 100644 index 0000000000..afa394c29f --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week2/bridge/Drawing.java @@ -0,0 +1,8 @@ +package com.coderising.dp.week2.bridge; + +public interface Drawing { + + void drawLine(); + + void drawCircle(); +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week2/bridge/DrawingGL1.java b/students/977996067/src/main/java/com/coderising/dp/week2/bridge/DrawingGL1.java new file mode 100644 index 0000000000..1b3f6c09c4 --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week2/bridge/DrawingGL1.java @@ -0,0 +1,14 @@ +package com.coderising.dp.week2.bridge; + +public class DrawingGL1 implements Drawing { + + @Override + public void drawLine() { + System.out.println("I am drawing line 1 ..."); + } + + @Override + public void drawCircle() { + System.out.println("I am drawing circle 1 ..."); + } +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week2/bridge/DrawingGL2.java b/students/977996067/src/main/java/com/coderising/dp/week2/bridge/DrawingGL2.java new file mode 100644 index 0000000000..23031c0122 --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week2/bridge/DrawingGL2.java @@ -0,0 +1,14 @@ +package com.coderising.dp.week2.bridge; + +public class DrawingGL2 implements Drawing { + + @Override + public void drawLine() { + System.out.println("I am drawing line 2 ..."); + } + + @Override + public void drawCircle() { + System.out.println("I am drawing circle 2 ..."); + } +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week2/bridge/Rectangle.java b/students/977996067/src/main/java/com/coderising/dp/week2/bridge/Rectangle.java new file mode 100644 index 0000000000..9ebfaa12d5 --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week2/bridge/Rectangle.java @@ -0,0 +1,15 @@ +package com.coderising.dp.week2.bridge; + +public class Rectangle extends Shape { + + public Rectangle(Drawing drawing) { + super(drawing); + } + + @Override + public void draw() { + getDrawing().drawLine(); + getDrawing().drawCircle(); + System.out.println("I am drawing a rectangle ..."); + } +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week2/bridge/Shape.java b/students/977996067/src/main/java/com/coderising/dp/week2/bridge/Shape.java new file mode 100644 index 0000000000..28d2d90430 --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week2/bridge/Shape.java @@ -0,0 +1,16 @@ +package com.coderising.dp.week2.bridge; + +public abstract class Shape { + + private Drawing drawing; + + public Shape(Drawing drawing) { + this.drawing = drawing; + } + + public Drawing getDrawing() { + return drawing; + } + + protected abstract void draw(); +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week2/composition/Line.java b/students/977996067/src/main/java/com/coderising/dp/week2/composition/Line.java new file mode 100644 index 0000000000..d0d15396fa --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week2/composition/Line.java @@ -0,0 +1,9 @@ +package com.coderising.dp.week2.composition; + +public class Line implements Shape { + + @Override + public void draw() { + System.out.println("I am drawing a line ..."); + } +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week2/composition/Picture.java b/students/977996067/src/main/java/com/coderising/dp/week2/composition/Picture.java new file mode 100644 index 0000000000..8dd13fc673 --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week2/composition/Picture.java @@ -0,0 +1,18 @@ +package com.coderising.dp.week2.composition; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +public class Picture implements Shape { + + private List shapes = new CopyOnWriteArrayList<>(); + + @Override + public void draw() { + shapes.forEach(Shape::draw); + } + + public void addShape(Shape shape) { + shapes.add(shape); + } +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week2/composition/Rectangle.java b/students/977996067/src/main/java/com/coderising/dp/week2/composition/Rectangle.java new file mode 100644 index 0000000000..00fb136dcb --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week2/composition/Rectangle.java @@ -0,0 +1,9 @@ +package com.coderising.dp.week2.composition; + +public class Rectangle implements Shape { + + @Override + public void draw() { + System.out.println("I am drawing a rectangle ..."); + } +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week2/composition/Shape.java b/students/977996067/src/main/java/com/coderising/dp/week2/composition/Shape.java new file mode 100644 index 0000000000..5ccbf9fa9c --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week2/composition/Shape.java @@ -0,0 +1,6 @@ +package com.coderising.dp.week2.composition; + +public interface Shape { + + void draw(); +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week2/composition/ShapeClient.java b/students/977996067/src/main/java/com/coderising/dp/week2/composition/ShapeClient.java new file mode 100644 index 0000000000..e8a0c2e7f3 --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week2/composition/ShapeClient.java @@ -0,0 +1,17 @@ +package com.coderising.dp.week2.composition; + +public class ShapeClient { + + public static void main(String[] args) { + Picture subPicture = new Picture(); + Line line = new Line(); + subPicture.addShape(new Text()); + subPicture.addShape(line); + subPicture.addShape(new Square()); + Picture parentPicture = new Picture(); + parentPicture.addShape(subPicture); + parentPicture.addShape(line); + parentPicture.addShape(new Rectangle()); + parentPicture.draw(); + } +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week2/composition/Square.java b/students/977996067/src/main/java/com/coderising/dp/week2/composition/Square.java new file mode 100644 index 0000000000..7d21e6ead1 --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week2/composition/Square.java @@ -0,0 +1,9 @@ +package com.coderising.dp.week2.composition; + +public class Square implements Shape { + + @Override + public void draw() { + System.out.println("I am drawing a square ..."); + } +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week2/composition/Text.java b/students/977996067/src/main/java/com/coderising/dp/week2/composition/Text.java new file mode 100644 index 0000000000..7c255262f6 --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week2/composition/Text.java @@ -0,0 +1,9 @@ +package com.coderising.dp.week2.composition; + +public class Text implements Shape { + + @Override + public void draw() { + System.out.println("I am drawing a text..."); + } +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week2/decorator/Email.java b/students/977996067/src/main/java/com/coderising/dp/week2/decorator/Email.java new file mode 100644 index 0000000000..f530f207ea --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week2/decorator/Email.java @@ -0,0 +1,6 @@ +package com.coderising.dp.week2.decorator; + +public interface Email { + + String getContent(); +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week2/decorator/EmailDecorator.java b/students/977996067/src/main/java/com/coderising/dp/week2/decorator/EmailDecorator.java new file mode 100644 index 0000000000..8faae4222d --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week2/decorator/EmailDecorator.java @@ -0,0 +1,51 @@ +package com.coderising.dp.week2.decorator; + +import java.nio.charset.Charset; +import java.util.Base64; + +public class EmailDecorator implements Email { + + private Email email; + + private String rawContent; + + private String handledContent; + + private EmailType emailType; + + public EmailDecorator(Email email) { + this(email, EmailType.PRIVATE); + } + + public EmailDecorator(Email email, EmailType emailType) { + this.email = email; + handle(email.getContent(), emailType); + } + + @Override + public String getContent() { + if (isModified()) { + handle(this.email.getContent(), this.emailType); + } + return this.handledContent; + } + + private void handle(String rawString, EmailType emailType) { + this.rawContent = rawString; + this.emailType = emailType; + String decodeString = decode(rawString); + this.handledContent = emailType == EmailType.PRIVATE ? decodeString : (decodeString + "本邮件仅为个人观点,并不代表公司立场"); + + } + + private String decode(String rawString) { + return new String(Base64.getEncoder().encode(rawString.getBytes()), Charset.defaultCharset()); + } + + private boolean isModified() { + if (this.rawContent == null) { + throw new RuntimeException(); + } + return email != null && rawContent.equals(email.getContent()); + } +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week2/decorator/EmailImpl.java b/students/977996067/src/main/java/com/coderising/dp/week2/decorator/EmailImpl.java new file mode 100644 index 0000000000..fd1a0eb48b --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week2/decorator/EmailImpl.java @@ -0,0 +1,15 @@ +package com.coderising.dp.week2.decorator; + +public class EmailImpl implements Email { + + private String content; + + public EmailImpl(String content) { + this.content = content; + } + + @Override + public String getContent() { + return this.content; + } +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week2/decorator/EmailType.java b/students/977996067/src/main/java/com/coderising/dp/week2/decorator/EmailType.java new file mode 100644 index 0000000000..97ed1febea --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week2/decorator/EmailType.java @@ -0,0 +1,6 @@ +package com.coderising.dp.week2.decorator; + +public enum EmailType { + PRIVATE, + PUBLIC +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week3/command/Command.java b/students/977996067/src/main/java/com/coderising/dp/week3/command/Command.java new file mode 100644 index 0000000000..9baa019670 --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week3/command/Command.java @@ -0,0 +1,16 @@ +package com.coderising.dp.week3.command; + +public abstract class Command { + + private Cook cook; + + protected Command(Cook cook) { + this.cook = cook; + } + + public Cook getCook() { + return cook; + } + + protected abstract void cookFood(); +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week3/command/Cook.java b/students/977996067/src/main/java/com/coderising/dp/week3/command/Cook.java new file mode 100644 index 0000000000..40adb8012a --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week3/command/Cook.java @@ -0,0 +1,12 @@ +package com.coderising.dp.week3.command; + +public class Cook { + + void cookSteak() { + System.out.println("Steak is OK"); + } + + void cookPork() { + System.out.println("Pork is OK"); + } +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week3/command/OrderPorkCommand.java b/students/977996067/src/main/java/com/coderising/dp/week3/command/OrderPorkCommand.java new file mode 100644 index 0000000000..aa2b93ad5a --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week3/command/OrderPorkCommand.java @@ -0,0 +1,14 @@ +package com.coderising.dp.week3.command; + +public class OrderPorkCommand extends Command { + + public OrderPorkCommand(Cook cook) { + super(cook); + } + + @Override + protected void cookFood() { + getCook().cookPork(); + } + +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week3/command/OrderSteakCommand.java b/students/977996067/src/main/java/com/coderising/dp/week3/command/OrderSteakCommand.java new file mode 100644 index 0000000000..91a4bc3118 --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week3/command/OrderSteakCommand.java @@ -0,0 +1,13 @@ +package com.coderising.dp.week3.command; + +public class OrderSteakCommand extends Command { + + public OrderSteakCommand(Cook cook) { + super(cook); + } + + @Override + protected void cookFood() { + getCook().cookSteak(); + } +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week3/command/Waiter.java b/students/977996067/src/main/java/com/coderising/dp/week3/command/Waiter.java new file mode 100644 index 0000000000..770ebedf9d --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week3/command/Waiter.java @@ -0,0 +1,19 @@ +package com.coderising.dp.week3.command; + +import java.util.ArrayDeque; +import java.util.Queue; + +public class Waiter { + + private Queue commandQueue = new ArrayDeque<>(); + + public synchronized void addOrder(Command command) { + commandQueue.add(command); + } + + public void sendOrders() { + while (!commandQueue.isEmpty()) { + commandQueue.poll().cookFood(); + } + } +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week3/responsibility/AbstractLogger.java b/students/977996067/src/main/java/com/coderising/dp/week3/responsibility/AbstractLogger.java new file mode 100644 index 0000000000..a1684f1dc5 --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week3/responsibility/AbstractLogger.java @@ -0,0 +1,28 @@ +package com.coderising.dp.week3.responsibility; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +public abstract class AbstractLogger implements Logger { + + private List loggers = new CopyOnWriteArrayList<>(); + + public AbstractLogger setNext(AbstractLogger nextLogger) { + if (!loggers.contains(this)) + loggers.add(this); + loggers.add(nextLogger); + return this; + } + + @Override + public void message(String message, int level) { + loggers + .stream() + .filter(logger -> logger.getLevel() <= level) + .forEach(logger -> logger.doMessage(message)); + } + + protected abstract int getLevel(); + + protected abstract void doMessage(String message); +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week3/responsibility/EmailLogger.java b/students/977996067/src/main/java/com/coderising/dp/week3/responsibility/EmailLogger.java new file mode 100644 index 0000000000..e6c4e4a7a6 --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week3/responsibility/EmailLogger.java @@ -0,0 +1,20 @@ +package com.coderising.dp.week3.responsibility; + +public class EmailLogger extends AbstractLogger { + + private int level; + + public EmailLogger(int level) { + this.level = level; + } + + @Override + public int getLevel() { + return level; + } + + @Override + protected void doMessage(String message) { + System.out.println("email to log : " + message); + } +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week3/responsibility/FileLogger.java b/students/977996067/src/main/java/com/coderising/dp/week3/responsibility/FileLogger.java new file mode 100644 index 0000000000..966b8a7bd7 --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week3/responsibility/FileLogger.java @@ -0,0 +1,20 @@ +package com.coderising.dp.week3.responsibility; + +public class FileLogger extends AbstractLogger { + + private int level; + + public FileLogger(int level) { + this.level = level; + } + + @Override + protected int getLevel() { + return level; + } + + @Override + protected void doMessage(String message) { + System.out.println("log to file : " + message); + } +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week3/responsibility/Logger.java b/students/977996067/src/main/java/com/coderising/dp/week3/responsibility/Logger.java new file mode 100644 index 0000000000..fd88a5481b --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week3/responsibility/Logger.java @@ -0,0 +1,10 @@ +package com.coderising.dp.week3.responsibility; + +public interface Logger { + + int DEBUG = 1; + int NOTICE = 2; + int ERR = 3; + + void message(String message, int level); +} diff --git a/students/977996067/src/main/java/com/coderising/dp/week3/responsibility/StdoutLogger.java b/students/977996067/src/main/java/com/coderising/dp/week3/responsibility/StdoutLogger.java new file mode 100644 index 0000000000..9d72e78616 --- /dev/null +++ b/students/977996067/src/main/java/com/coderising/dp/week3/responsibility/StdoutLogger.java @@ -0,0 +1,21 @@ +package com.coderising.dp.week3.responsibility; + +public class StdoutLogger extends AbstractLogger { + + private int level; + + public StdoutLogger(int level) { + this.level = level; + } + + @Override + protected int getLevel() { + return level; + } + + @Override + protected void doMessage(String message) { + System.out.println("stdout : " + message); + } + +} diff --git a/students/977996067/src/test/java/com/coderising/dp/week1/TagNodeTest.java b/students/977996067/src/test/java/com/coderising/dp/week1/TagNodeTest.java new file mode 100644 index 0000000000..554ae1fda4 --- /dev/null +++ b/students/977996067/src/test/java/com/coderising/dp/week1/TagNodeTest.java @@ -0,0 +1,20 @@ +package com.coderising.dp.week1; + +import org.junit.Test; + +public class TagNodeTest { + + @Test + public void testBuilder() { + + TagBuilder builder = new TagBuilder("order"); + + + String xml = builder.addChild("line-items") + .addChild("line-item").setAttribute("pid", "p3333").setAttribute("qty", "3") + .addSibling("line-item").setAttribute("pid", "p9876").setAttribute("qty", "10") + .toXML(); + + System.out.println(xml); + } +} \ No newline at end of file diff --git a/students/977996067/src/test/java/com/coderising/dp/week3/ChainTest.java b/students/977996067/src/test/java/com/coderising/dp/week3/ChainTest.java new file mode 100644 index 0000000000..0121489823 --- /dev/null +++ b/students/977996067/src/test/java/com/coderising/dp/week3/ChainTest.java @@ -0,0 +1,21 @@ +package com.coderising.dp.week3; + +import com.coderising.dp.week3.responsibility.EmailLogger; +import com.coderising.dp.week3.responsibility.FileLogger; +import com.coderising.dp.week3.responsibility.Logger; +import com.coderising.dp.week3.responsibility.StdoutLogger; +import org.junit.Test; + +public class ChainTest { + + @Test + public void testLoggerChain() { + Logger logger = new StdoutLogger(Logger.DEBUG) + .setNext(new EmailLogger(Logger.NOTICE)) + .setNext(new FileLogger(Logger.ERR)); + + logger.message("计入计算函数", Logger.DEBUG); + logger.message("第一步已完成", Logger.NOTICE); + logger.message("出现了一个致命的bug", Logger.ERR); + } +} diff --git a/students/977996067/src/test/java/com/coderising/dp/week3/CommandTest.java b/students/977996067/src/test/java/com/coderising/dp/week3/CommandTest.java new file mode 100644 index 0000000000..26d75e46bb --- /dev/null +++ b/students/977996067/src/test/java/com/coderising/dp/week3/CommandTest.java @@ -0,0 +1,18 @@ +package com.coderising.dp.week3; + +import com.coderising.dp.week3.command.*; +import org.junit.Test; + +public class CommandTest { + + @Test + public void testCook() { + Cook cook = new Cook(); + Waiter waiter = new Waiter(); + Command c1 = new OrderPorkCommand(cook); + Command c2 = new OrderSteakCommand(cook); + waiter.addOrder(c1); + waiter.addOrder(c2); + waiter.sendOrders(); + } +} diff --git a/students/986547781/README.md b/students/986547781/README.md new file mode 100644 index 0000000000..f568850ceb --- /dev/null +++ b/students/986547781/README.md @@ -0,0 +1,2 @@ +##第一次尝试 +##解决编码问题 \ No newline at end of file diff --git a/students/992331664/data-structure/data-structure/build.gradle b/students/992331664/data-structure/data-structure/build.gradle new file mode 100644 index 0000000000..e8037fb1c4 --- /dev/null +++ b/students/992331664/data-structure/data-structure/build.gradle @@ -0,0 +1,12 @@ +apply plugin: 'java' + +repositories { + jcenter() +} + +dependencies { + compile 'org.slf4j:slf4j-api:1.7.21' + compile 'org.apache.poi:poi:3.16' + compile 'org.apache.poi:poi-ooxml:3.16' + testCompile 'junit:junit:4.12' +} diff --git a/students/992331664/data-structure/data-structure/gradle/wrapper/gradle-wrapper.properties b/students/992331664/data-structure/data-structure/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..d4aaec595d --- /dev/null +++ b/students/992331664/data-structure/data-structure/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Jun 13 11:30:56 CST 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-3.0-bin.zip diff --git a/students/992331664/data-structure/data-structure/gradlew b/students/992331664/data-structure/data-structure/gradlew new file mode 100644 index 0000000000..9aa616c273 --- /dev/null +++ b/students/992331664/data-structure/data-structure/gradlew @@ -0,0 +1,169 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [[ "$(uname)" == "Darwin" ]] && [[ "$HOME" == "$PWD" ]]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/students/992331664/data-structure/data-structure/gradlew.bat b/students/992331664/data-structure/data-structure/gradlew.bat new file mode 100644 index 0000000000..f9553162f1 --- /dev/null +++ b/students/992331664/data-structure/data-structure/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/students/992331664/data-structure/data-structure/settings.gradle b/students/992331664/data-structure/data-structure/settings.gradle new file mode 100644 index 0000000000..e5c7e27790 --- /dev/null +++ b/students/992331664/data-structure/data-structure/settings.gradle @@ -0,0 +1,19 @@ +/* + * This settings file was auto generated by the Gradle buildInit task + * by 'gant' at '17-6-13 上午11:30' with Gradle 3.0 + * + * The settings file is used to specify which projects to include in your build. + * In a single project build this file can be empty or even removed. + * + * Detailed information about configuring a multi-project build in Gradle can be found + * in the user guide at https://docs.gradle.org/3.0/userguide/multi_project_builds.html + */ + +/* +// To declare projects as part of a multi-project build use the 'include' method +include 'shared' +include 'api' +include 'services:webservice' +*/ + +rootProject.name = 'data-structure' diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/DownloadThread.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/DownloadThread.java new file mode 100644 index 0000000000..900a3ad358 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/DownloadThread.java @@ -0,0 +1,20 @@ +package com.coderising.download; + +import com.coderising.download.api.Connection; + +public class DownloadThread extends Thread{ + + Connection conn; + int startPos; + int endPos; + + public DownloadThread( Connection conn, int startPos, int endPos){ + + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + } + public void run(){ + + } +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/FileDownloader.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/FileDownloader.java new file mode 100644 index 0000000000..c3c8a3f27d --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/FileDownloader.java @@ -0,0 +1,73 @@ +package com.coderising.download; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionException; +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; + + +public class FileDownloader { + + String url; + + DownloadListener listener; + + ConnectionManager cm; + + + public FileDownloader(String _url) { + this.url = _url; + + } + + public void execute(){ + // 在这里实现你的代码, 注意: 需要用多线程实现下载 + // 这个类依赖于其他几个接口, 你需要写这几个接口的实现代码 + // (1) ConnectionManager , 可以打开一个连接,通过Connection可以读取其中的一段(用startPos, endPos来指定) + // (2) DownloadListener, 由于是多线程下载, 调用这个类的客户端不知道什么时候结束,所以你需要实现当所有 + // 线程都执行完以后, 调用listener的notifiedFinished方法, 这样客户端就能收到通知。 + // 具体的实现思路: + // 1. 需要调用ConnectionManager的open方法打开连接, 然后通过Connection.getContentLength方法获得文件的长度 + // 2. 至少启动3个线程下载, 注意每个线程需要先调用ConnectionManager的open方法 + // 然后调用read方法, read方法中有读取文件的开始位置和结束位置的参数, 返回值是byte[]数组 + // 3. 把byte数组写入到文件中 + // 4. 所有的线程都下载完成以后, 需要调用listener的notifiedFinished方法 + + // 下面的代码是示例代码, 也就是说只有一个线程, 你需要改造成多线程的。 + Connection conn = null; + try { + + conn = cm.open(this.url); + + int length = conn.getContentLength(); + + new DownloadThread(conn,0,length-1).start(); + + } catch (ConnectionException e) { + e.printStackTrace(); + }finally{ + if(conn != null){ + conn.close(); + } + } + + + + + } + + public void setListener(DownloadListener listener) { + this.listener = listener; + } + + + + public void setConnectionManager(ConnectionManager ucm){ + this.cm = ucm; + } + + public DownloadListener getListener(){ + return this.listener; + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/FileDownloaderTest.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/FileDownloaderTest.java new file mode 100644 index 0000000000..4ff7f46ae0 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/FileDownloaderTest.java @@ -0,0 +1,59 @@ +package com.coderising.download; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.coderising.download.api.ConnectionManager; +import com.coderising.download.api.DownloadListener; +import com.coderising.download.impl.ConnectionManagerImpl; + +public class FileDownloaderTest { + boolean downloadFinished = false; + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testDownload() { + + String url = "http://localhost:8080/test.jpg"; + + FileDownloader downloader = new FileDownloader(url); + + + ConnectionManager cm = new ConnectionManagerImpl(); + downloader.setConnectionManager(cm); + + downloader.setListener(new DownloadListener() { + @Override + public void notifyFinished() { + downloadFinished = true; + } + + }); + + + downloader.execute(); + + // 等待多线程下载程序执行完毕 + while (!downloadFinished) { + try { + System.out.println("还没有下载完成,休眠五秒"); + //休眠5秒 + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + System.out.println("下载完成!"); + + + + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/api/Connection.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/api/Connection.java new file mode 100644 index 0000000000..0957eaf7f4 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/api/Connection.java @@ -0,0 +1,23 @@ +package com.coderising.download.api; + +import java.io.IOException; + +public interface Connection { + /** + * 给定开始和结束位置, 读取数据, 返回值是字节数组 + * @param startPos 开始位置, 从0开始 + * @param endPos 结束位置 + * @return + */ + public byte[] read(int startPos,int endPos) throws IOException; + /** + * 得到数据内容的长度 + * @return + */ + public int getContentLength(); + + /** + * 关闭连接 + */ + public void close(); +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/api/ConnectionException.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/api/ConnectionException.java new file mode 100644 index 0000000000..1551a80b3d --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/api/ConnectionException.java @@ -0,0 +1,5 @@ +package com.coderising.download.api; + +public class ConnectionException extends Exception { + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/api/ConnectionManager.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/api/ConnectionManager.java new file mode 100644 index 0000000000..ce045393b1 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/api/ConnectionManager.java @@ -0,0 +1,10 @@ +package com.coderising.download.api; + +public interface ConnectionManager { + /** + * 给定一个url , 打开一个连接 + * @param url + * @return + */ + public Connection open(String url) throws ConnectionException; +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/api/DownloadListener.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/api/DownloadListener.java new file mode 100644 index 0000000000..bf9807b307 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/api/DownloadListener.java @@ -0,0 +1,5 @@ +package com.coderising.download.api; + +public interface DownloadListener { + public void notifyFinished(); +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/impl/ConnectionImpl.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..36a9d2ce15 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/impl/ConnectionImpl.java @@ -0,0 +1,27 @@ +package com.coderising.download.impl; + +import java.io.IOException; + +import com.coderising.download.api.Connection; + +public class ConnectionImpl implements Connection{ + + @Override + public byte[] read(int startPos, int endPos) throws IOException { + + return null; + } + + @Override + public int getContentLength() { + + return 0; + } + + @Override + public void close() { + + + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/impl/ConnectionManagerImpl.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..172371dd55 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,15 @@ +package com.coderising.download.impl; + +import com.coderising.download.api.Connection; +import com.coderising.download.api.ConnectionException; +import com.coderising.download.api.ConnectionManager; + +public class ConnectionManagerImpl implements ConnectionManager { + + @Override + public Connection open(String url) throws ConnectionException { + + return null; + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/litestruts/LoginAction.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/litestruts/LoginAction.java new file mode 100644 index 0000000000..dcdbe226ed --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/litestruts/LoginAction.java @@ -0,0 +1,39 @@ +package com.coderising.litestruts; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * @author liuxin + * + */ +public class LoginAction{ + private String name ; + private String password; + private String message; + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String execute(){ + if("test".equals(name) && "1234".equals(password)){ + this.message = "login successful"; + return "success"; + } + this.message = "login failed,please check your user/pwd"; + return "fail"; + } + + public void setName(String name){ + this.name = name; + } + public void setPassword(String password){ + this.password = password; + } + public String getMessage(){ + return this.message; + } +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/litestruts/Struts.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/litestruts/Struts.java new file mode 100644 index 0000000000..85e2e22de3 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/litestruts/Struts.java @@ -0,0 +1,34 @@ +package com.coderising.litestruts; + +import java.util.Map; + + + +public class Struts { + + public static View runAction(String actionName, Map parameters) { + + /* + + 0. 读取配置文件struts.xml + + 1. 根据actionName找到相对应的class , 例如LoginAction, 通过反射实例化(创建对象) + 据parameters中的数据,调用对象的setter方法, 例如parameters中的数据是 + ("name"="test" , "password"="1234") , + 那就应该调用 setName和setPassword方法 + + 2. 通过反射调用对象的exectue 方法, 并获得返回值,例如"success" + + 3. 通过反射找到对象的所有getter方法(例如 getMessage), + 通过反射来调用, 把值和属性形成一个HashMap , 例如 {"message": "登录成功"} , + 放到View对象的parameters + + 4. 根据struts.xml中的 配置,以及execute的返回值, 确定哪一个jsp, + 放到View对象的jsp字段中。 + + */ + + return null; + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/litestruts/StrutsTest.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/litestruts/StrutsTest.java new file mode 100644 index 0000000000..b8c81faf3c --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/litestruts/StrutsTest.java @@ -0,0 +1,43 @@ +package com.coderising.litestruts; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + + + + + +public class StrutsTest { + + @Test + public void testLoginActionSuccess() { + + String actionName = "login"; + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/homepage.jsp", view.getJsp()); + Assert.assertEquals("login successful", view.getParameters().get("message")); + } + + @Test + public void testLoginActionFailed() { + String actionName = "login"; + Map params = new HashMap(); + params.put("name","test"); + params.put("password","123456"); //密码和预设的不一致 + + View view = Struts.runAction(actionName,params); + + Assert.assertEquals("/jsp/showLogin.jsp", view.getJsp()); + Assert.assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); + } +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/litestruts/View.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/litestruts/View.java new file mode 100644 index 0000000000..07df2a5dab --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/litestruts/View.java @@ -0,0 +1,23 @@ +package com.coderising.litestruts; + +import java.util.Map; + +public class View { + private String jsp; + private Map parameters; + + public String getJsp() { + return jsp; + } + public View setJsp(String jsp) { + this.jsp = jsp; + return this; + } + public Map getParameters() { + return parameters; + } + public View setParameters(Map parameters) { + this.parameters = parameters; + return this; + } +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/litestruts/struts.xml b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/litestruts/struts.xml new file mode 100644 index 0000000000..e5d9aebba8 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/bad/Course.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/bad/Course.java new file mode 100644 index 0000000000..436d092f58 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/bad/Course.java @@ -0,0 +1,24 @@ +package com.coderising.ood.course.bad; + +import java.util.List; + +public class Course { + private String id; + private String desc; + private int duration ; + + List prerequisites; + + public List getPrerequisites() { + return prerequisites; + } + + + public boolean equals(Object o){ + if(o == null || !(o instanceof Course)){ + return false; + } + Course c = (Course)o; + return (c != null) && c.id.equals(id); + } +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/bad/CourseOffering.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/bad/CourseOffering.java new file mode 100644 index 0000000000..ab8c764584 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/bad/CourseOffering.java @@ -0,0 +1,26 @@ +package com.coderising.ood.course.bad; + +import java.util.ArrayList; +import java.util.List; + + +public class CourseOffering { + private Course course; + private String location; + private String teacher; + private int maxStudents; + + List students = new ArrayList(); + + public int getMaxStudents() { + return maxStudents; + } + + public List getStudents() { + return students; + } + + public Course getCourse() { + return course; + } +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/bad/CourseService.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/bad/CourseService.java new file mode 100644 index 0000000000..8c34bad0c3 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/bad/CourseService.java @@ -0,0 +1,16 @@ +package com.coderising.ood.course.bad; + + + +public class CourseService { + + public void chooseCourse(Student student, CourseOffering sc){ + //如果学生上过该科目的先修科目,并且该课程还未满, 则学生可以加入该课程 + if(student.getCoursesAlreadyTaken().containsAll( + sc.getCourse().getPrerequisites()) + && sc.getMaxStudents() > sc.getStudents().size()){ + sc.getStudents().add(student); + } + + } +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/bad/Student.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/bad/Student.java new file mode 100644 index 0000000000..a651923ef5 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/bad/Student.java @@ -0,0 +1,14 @@ +package com.coderising.ood.course.bad; + +import java.util.ArrayList; +import java.util.List; + +public class Student { + private String id; + private String name; + private List coursesAlreadyTaken = new ArrayList(); + + public List getCoursesAlreadyTaken() { + return coursesAlreadyTaken; + } +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/good/Course.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/good/Course.java new file mode 100644 index 0000000000..aefc9692bb --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/good/Course.java @@ -0,0 +1,18 @@ +package com.coderising.ood.course.good; + +import java.util.List; + +public class Course { + private String id; + private String desc; + private int duration ; + + List prerequisites; + + public List getPrerequisites() { + return prerequisites; + } + +} + + diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/good/CourseOffering.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/good/CourseOffering.java new file mode 100644 index 0000000000..8660ec8109 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/good/CourseOffering.java @@ -0,0 +1,34 @@ +package com.coderising.ood.course.good; + +import java.util.ArrayList; +import java.util.List; + +public class CourseOffering { + private Course course; + private String location; + private String teacher; + private int maxStudents; + + List students = new ArrayList(); + + public List getStudents() { + return students; + } + public int getMaxStudents() { + return maxStudents; + } + public Course getCourse() { + return course; + } + + + // 第二步: 把主要逻辑移动到CourseOffering 中 + public void addStudent(Student student){ + + if(student.canAttend(course) + && this.maxStudents > students.size()){ + students.add(student); + } + } + // 第三步: 重构CourseService +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/good/CourseService.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/good/CourseService.java new file mode 100644 index 0000000000..22ba4a5450 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/good/CourseService.java @@ -0,0 +1,14 @@ +package com.coderising.ood.course.good; + + + +public class CourseService { + + public void chooseCourse(Student student, CourseOffering sc){ + //第一步:重构: canAttend , 但是还有问题 + if(student.canAttend(sc.getCourse()) + && sc.getMaxStudents() > sc.getStudents().size()){ + sc.getStudents().add(student); + } + } +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/good/Student.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/good/Student.java new file mode 100644 index 0000000000..2c7e128b2a --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/course/good/Student.java @@ -0,0 +1,21 @@ +package com.coderising.ood.course.good; + +import java.util.ArrayList; +import java.util.List; + +public class Student { + private String id; + private String name; + private List coursesAlreadyTaken = new ArrayList(); + + public List getCoursesAlreadyTaken() { + return coursesAlreadyTaken; + } + + public boolean canAttend(Course course){ + return this.coursesAlreadyTaken.containsAll( + course.getPrerequisites()); + } +} + + diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/ocp/DateUtil.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/ocp/DateUtil.java new file mode 100644 index 0000000000..b6cf28c096 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/ocp/DateUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class DateUtil { + + public static String getCurrentDateAsString() { + + return null; + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/ocp/Logger.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/ocp/Logger.java new file mode 100644 index 0000000000..0357c4d912 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/ocp/Logger.java @@ -0,0 +1,38 @@ +package com.coderising.ood.ocp; + +public class Logger { + + public final int RAW_LOG = 1; + public final int RAW_LOG_WITH_DATE = 2; + public final int EMAIL_LOG = 1; + public final int SMS_LOG = 2; + public final int PRINT_LOG = 3; + + int type = 0; + int method = 0; + + public Logger(int logType, int logMethod){ + this.type = logType; + this.method = logMethod; + } + public void log(String msg){ + + String logMsg = msg; + + if(this.type == RAW_LOG){ + logMsg = msg; + } else if(this.type == RAW_LOG_WITH_DATE){ + String txtDate = DateUtil.getCurrentDateAsString(); + logMsg = txtDate + ": " + msg; + } + + if(this.method == EMAIL_LOG){ + MailUtil.send(logMsg); + } else if(this.method == SMS_LOG){ + SMSUtil.send(logMsg); + } else if(this.method == PRINT_LOG){ + System.out.println(logMsg); + } + } +} + diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/ocp/MailUtil.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/ocp/MailUtil.java new file mode 100644 index 0000000000..ec54b839c5 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/ocp/MailUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class MailUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/ocp/SMSUtil.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/ocp/SMSUtil.java new file mode 100644 index 0000000000..13cf802418 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/ocp/SMSUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class SMSUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/srp/Configuration.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/srp/DBUtil.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..82e9261d18 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,25 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/srp/MailUtil.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..9f9e749af7 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..781587a846 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,199 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +public class PromotionMail { + + + protected String sendMailQuery = null; + + + protected String smtpHost = null; + protected String altSmtpHost = null; + protected String fromAddress = null; + protected String toAddress = null; + protected String subject = null; + protected String message = null; + + protected String productID = null; + protected String productDesc = null; + + private static Configuration config; + + + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + File f = new File("C:\\coderising\\workspace_ds\\ood-example\\src\\product_promotion.txt"); + boolean emailDebug = false; + + PromotionMail pe = new PromotionMail(f, emailDebug); + + } + + + public PromotionMail(File file, boolean mailDebug) throws Exception { + + //读取配置文件, 文件中只有一行用空格隔开, 例如 P8756 iPhone8 + readFile(file); + + + config = new Configuration(); + + setSMTPHost(); + setAltSMTPHost(); + + + setFromAddress(); + + + setLoadQuery(); + + sendEMails(mailDebug, loadMailingList()); + + + } + + + + + protected void setProductID(String productID) + { + this.productID = productID; + + } + + protected String getproductID() + { + return productID; + } + + protected void setLoadQuery() throws Exception { + + sendMailQuery = "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + + System.out.println("loadQuery set"); + } + + + protected void setSMTPHost() + { + smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + } + + + protected void setAltSMTPHost() + { + altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + + } + + + protected void setFromAddress() + { + fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + protected void setMessage(HashMap userInfo) throws IOException + { + + String name = (String) userInfo.get(NAME_KEY); + + subject = "您关注的产品降价了"; + message = "尊敬的 "+name+", 您关注的产品 " + productDesc + " 降价了,欢迎购买!" ; + + + + } + + + protected void readFile(File file) throws IOException // @02C + { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" "); + + setProductID(data[0]); + setProductDesc(data[1]); + + System.out.println("产品ID = " + productID + "\n"); + System.out.println("产品描述 = " + productDesc + "\n"); + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + private void setProductDesc(String desc) { + this.productDesc = desc; + } + + + protected void configureEMail(HashMap userInfo) throws IOException + { + toAddress = (String) userInfo.get(EMAIL_KEY); + if (toAddress.length() > 0) + setMessage(userInfo); + } + + protected List loadMailingList() throws Exception { + return DBUtil.query(this.sendMailQuery); + } + + + protected void sendEMails(boolean debug, List mailingList) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + configureEMail((HashMap) iter.next()); + try + { + if (toAddress.length() > 0) + MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug); + } + catch (Exception e) + { + + try { + MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + + } + + else { + System.out.println("没有邮件发送"); + + } + + } +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..a98917f829 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo R15 +P4955 Vivo X20 \ No newline at end of file diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/Iterator.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/Iterator.java new file mode 100644 index 0000000000..06ef6311b2 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/Iterator.java @@ -0,0 +1,7 @@ +package com.coding.basic; + +public interface Iterator { + public boolean hasNext(); + public Object next(); + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/List.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/List.java new file mode 100644 index 0000000000..10d13b5832 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/List.java @@ -0,0 +1,9 @@ +package com.coding.basic; + +public interface List { + public void add(Object o); + public void add(int index, Object o); + public Object get(int index); + public Object remove(int index); + public int size(); +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/array/ArrayList.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/array/ArrayList.java new file mode 100644 index 0000000000..4576c016af --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/array/ArrayList.java @@ -0,0 +1,35 @@ +package com.coding.basic.array; + +import com.coding.basic.Iterator; +import com.coding.basic.List; + +public class ArrayList implements List { + + private int size = 0; + + private Object[] elementData = new Object[100]; + + public void add(Object o){ + + } + public void add(int index, Object o){ + + } + + public Object get(int index){ + return null; + } + + public Object remove(int index){ + return null; + } + + public int size(){ + return -1; + } + + public Iterator iterator(){ + return null; + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/array/ArrayUtil.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/array/ArrayUtil.java new file mode 100644 index 0000000000..c17e6def49 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/array/ArrayUtil.java @@ -0,0 +1,159 @@ +package com.coding.basic.array; + +import java.util.Arrays; + +import javax.management.RuntimeErrorException; + +public class ArrayUtil { + + /** + * 给定一个整形数组a , 对该数组的值进行置换 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] 如果 a = + * [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] + * + * @param origin + * @return + */ + public void reverseArray(int[] origin) { + if (origin != null && origin.length > 1) { + for (int i = 0; i < origin.length / 2; i++) { + int temp = origin[i]; + origin[i] = origin[origin.length - 1 - i]; + origin[origin.length - 1 - i] = temp; + } + } + } + + /** + * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} + * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: {1,3,4,5,6,6,5,4,7,6,7,5} + * + * @param oldArray + * @return + */ + + public int[] removeZero(int[] oldArray) { + // JDK 1.8 + // int[] newArray = Arrays.stream(oldArray).filter(item->item + // !=0).toArray(); + + int[] newArray = new int[oldArray.length]; + + int zeroCount = 0; + for (int i = 0; i < oldArray.length; i++) { + if (oldArray[i] == 0) { + zeroCount++; + } else { + newArray[i - zeroCount] = oldArray[i]; + } + } + if (zeroCount == 0) { + return Arrays.copyOf(oldArray, oldArray.length); + } else { + return Arrays.copyOf(newArray, oldArray.length - zeroCount); + } + } + + /** + * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 例如 a1 = + * [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 + * + * @param array1 + * @param array2 + * @return + */ + + public int[] merge(int[] array1, int[] array2) { + return null; + } + + /** + * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size + * 注意,老数组的元素在新数组中需要保持 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 + * [2,3,6,0,0,0] + * + * @param oldArray + * @param size + * @return + */ + public int[] grow(int[] oldArray, int size) { + if (oldArray.length + size < 0) { + throw new RuntimeErrorException(null, "size + oldArray.length 不能小于0"); + } + int[] newArray = new int[oldArray.length + size]; + + if (size < 0) { + for (int i = 0; i < newArray.length; i++) { + newArray[i] = oldArray[i]; + } + } else { + for (int i = 0; i < oldArray.length; i++) { + newArray[i] = oldArray[i]; + } + } + return newArray; + } + + /** + * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 例如, max = 15 , + * 则返回的数组应该为 [1,1,2,3,5,8,13] max = 1, 则返回空数组 [] + * + * @param max + * @return + */ + public int[] fibonacci(int max) { + if (max <= 1) { + return new int[0]; + } + int a = 1; + int count = 1; + for (int i = 1; i <= max; i += a) { + a += i; + count+=2; + } + + int[] result = new int[count]; + + a = 1; + count = 0; + result[count++] = 1; + + for (int i = 1; i <= max; i += a) { + a += i; + result[count++] = i; + result[count++] = a; + } + return result; + } + + /** + * 返回小于给定最大值max的所有素数数组 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * + * @param max + * @return + */ + public int[] getPrimes(int max) { + return null; + } + + /** + * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 + * + * @param max + * @return + */ + public int[] getPerfectNumbers(int max) { + return null; + } + + /** + * 用seperator 把数组 array给连接起来 例如array= [3,8,9], seperator = "-" 则返回值为"3-8-9" + * + * @param array + * @param s + * @return + */ + public String join(int[] array, String seperator) { + return null; + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/linklist/LRUPageFrame.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/linklist/LRUPageFrame.java new file mode 100644 index 0000000000..994a241a3d --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/linklist/LRUPageFrame.java @@ -0,0 +1,57 @@ +package com.coding.basic.linklist; + + +public class LRUPageFrame { + + private static class Node { + + Node prev; + Node next; + int pageNum; + + Node() { + } + } + + private int capacity; + + private int currentSize; + private Node first;// 链表头 + private Node last;// 链表尾 + + + public LRUPageFrame(int capacity) { + this.currentSize = 0; + this.capacity = capacity; + + } + + /** + * 获取缓存中对象 + * + * @param key + * @return + */ + public void access(int pageNum) { + + + } + + + public String toString(){ + StringBuilder buffer = new StringBuilder(); + Node node = first; + while(node != null){ + buffer.append(node.pageNum); + + node = node.next; + if(node != null){ + buffer.append(","); + } + } + return buffer.toString(); + } + + + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/linklist/LRUPageFrameTest.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/linklist/LRUPageFrameTest.java new file mode 100644 index 0000000000..7fd72fc2b4 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/linklist/LRUPageFrameTest.java @@ -0,0 +1,34 @@ +package com.coding.basic.linklist; + +import org.junit.Assert; + +import org.junit.Test; + + +public class LRUPageFrameTest { + + @Test + public void testAccess() { + LRUPageFrame frame = new LRUPageFrame(3); + frame.access(7); + frame.access(0); + frame.access(1); + Assert.assertEquals("1,0,7", frame.toString()); + frame.access(2); + Assert.assertEquals("2,1,0", frame.toString()); + frame.access(0); + Assert.assertEquals("0,2,1", frame.toString()); + frame.access(0); + Assert.assertEquals("0,2,1", frame.toString()); + frame.access(3); + Assert.assertEquals("3,0,2", frame.toString()); + frame.access(0); + Assert.assertEquals("0,3,2", frame.toString()); + frame.access(4); + Assert.assertEquals("4,0,3", frame.toString()); + frame.access(5); + Assert.assertEquals("5,4,0", frame.toString()); + + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/linklist/LinkedList.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/linklist/LinkedList.java new file mode 100644 index 0000000000..f4c7556a2e --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/linklist/LinkedList.java @@ -0,0 +1,125 @@ +package com.coding.basic.linklist; + +import com.coding.basic.Iterator; +import com.coding.basic.List; + +public class LinkedList implements List { + + private Node head; + + public void add(Object o){ + + } + public void add(int index , Object o){ + + } + public Object get(int index){ + return null; + } + public Object remove(int index){ + return null; + } + + public int size(){ + return -1; + } + + public void addFirst(Object o){ + + } + public void addLast(Object o){ + + } + public Object removeFirst(){ + return null; + } + public Object removeLast(){ + return null; + } + public Iterator iterator(){ + return null; + } + + + private static class Node{ + Object data; + Node next; + + } + + /** + * 把该链表逆置 + * 例如链表为 3->7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + + */ + public void removeFirstHalf(){ + + } + + /** + * 从第i个元素开始, 删除length 个元素 , 注意i从0开始 + * @param i + * @param length + */ + public void remove(int i, int length){ + + } + /** + * 假定当前链表和listB均包含已升序排列的整数 + * 从当前链表中取出那些listB所指定的元素 + * 例如当前链表 = 11->101->201->301->401->501->601->701 + * listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + * @param list + */ + public int[] getElements(LinkedList list){ + return null; + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 从当前链表中中删除在listB中出现的元素 + + * @param list + */ + + public void subtract(LinkedList list){ + + } + + /** + * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) + */ + public void removeDuplicateValues(){ + + } + + /** + * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 + * 试写一高效的算法,删除表中所有值大于min且小于max的元素(若表中存在这样的元素) + * @param min + * @param max + */ + public void removeRange(int min, int max){ + + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * @param list + */ + public LinkedList intersection( LinkedList list){ + return null; + } +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/queue/CircleQueue.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/queue/CircleQueue.java new file mode 100644 index 0000000000..2e0550c67e --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/queue/CircleQueue.java @@ -0,0 +1,39 @@ +package com.coding.basic.queue; + +/** + * 用数组实现循环队列 + * @author liuxin + * + * @param + */ +public class CircleQueue { + + private final static int DEFAULT_SIZE = 10; + + //用数组来保存循环队列的元素 + private Object[] elementData = new Object[DEFAULT_SIZE] ; + + //队头 + private int front = 0; + //队尾 + private int rear = 0; + + public boolean isEmpty() { + return false; + + } + + public int size() { + return -1; + } + + + + public void enQueue(E data) { + + } + + public E deQueue() { + return null; + } +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/queue/Josephus.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/queue/Josephus.java new file mode 100644 index 0000000000..6a3ea639b9 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/queue/Josephus.java @@ -0,0 +1,18 @@ +package com.coding.basic.queue; + +import java.util.List; + +/** + * 用Queue来实现Josephus问题 + * 在这个古老的问题当中, N个深陷绝境的人一致同意用这种方式减少生存人数: N个人围成一圈(位置记为0到N-1), 并且从第一个人报数, 报到M的人会被杀死, 直到最后一个人留下来 + * 该方法返回一个List, 包含了被杀死人的次序 + * @author liuxin + * + */ +public class Josephus { + + public static List execute(int n, int m){ + return null; + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/queue/JosephusTest.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/queue/JosephusTest.java new file mode 100644 index 0000000000..7d90318b51 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/queue/JosephusTest.java @@ -0,0 +1,27 @@ +package com.coding.basic.queue; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class JosephusTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testExecute() { + + Assert.assertEquals("[1, 3, 5, 0, 4, 2, 6]", Josephus.execute(7, 2).toString()); + + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/queue/Queue.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/queue/Queue.java new file mode 100644 index 0000000000..c4c4b7325e --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/queue/Queue.java @@ -0,0 +1,61 @@ +package com.coding.basic.queue; + +import java.util.NoSuchElementException; + +public class Queue { + private Node first; + private Node last; + private int size; + + + private static class Node { + private E item; + private Node next; + } + + + public Queue() { + first = null; + last = null; + size = 0; + } + + + public boolean isEmpty() { + return first == null; + } + + public int size() { + return size; + } + + + + public void enQueue(E data) { + Node oldlast = last; + last = new Node(); + last.item = data; + last.next = null; + if (isEmpty()) { + first = last; + } + else{ + oldlast.next = last; + } + size++; + } + + public E deQueue() { + if (isEmpty()) { + throw new NoSuchElementException("Queue underflow"); + } + E item = first.item; + first = first.next; + size--; + if (isEmpty()) { + last = null; + } + return item; + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/queue/QueueWithTwoStacks.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/queue/QueueWithTwoStacks.java new file mode 100644 index 0000000000..cef19a8b59 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/queue/QueueWithTwoStacks.java @@ -0,0 +1,47 @@ +package com.coding.basic.queue; + +import java.util.Stack; + +/** + * 用两个栈来实现一个队列 + * @author liuxin + * + * @param + */ +public class QueueWithTwoStacks { + private Stack stack1; + private Stack stack2; + + + public QueueWithTwoStacks() { + stack1 = new Stack(); + stack2 = new Stack(); + } + + + + + public boolean isEmpty() { + return false; + } + + + + public int size() { + return -1; + } + + + + public void enQueue(E item) { + + } + + public E deQueue() { + return null; + } + + + + } + diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/QuickMinStack.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/QuickMinStack.java new file mode 100644 index 0000000000..f391d92b8f --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/QuickMinStack.java @@ -0,0 +1,19 @@ +package com.coding.basic.stack; + +/** + * 设计一个栈,支持栈的push和pop操作,以及第三种操作findMin, 它返回改数据结构中的最小元素 + * finMin操作最坏的情形下时间复杂度应该是O(1) , 简单来讲,操作一次就可以得到最小值 + * @author liuxin + * + */ +public class QuickMinStack { + public void push(int data){ + + } + public int pop(){ + return -1; + } + public int findMin(){ + return -1; + } +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/Stack.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/Stack.java new file mode 100644 index 0000000000..fedb243604 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/Stack.java @@ -0,0 +1,24 @@ +package com.coding.basic.stack; + +import com.coding.basic.array.ArrayList; + +public class Stack { + private ArrayList elementData = new ArrayList(); + + public void push(Object o){ + } + + public Object pop(){ + return null; + } + + public Object peek(){ + return null; + } + public boolean isEmpty(){ + return false; + } + public int size(){ + return -1; + } +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/StackUtil.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/StackUtil.java new file mode 100644 index 0000000000..b0ec38161d --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/StackUtil.java @@ -0,0 +1,48 @@ +package com.coding.basic.stack; +import java.util.Stack; +public class StackUtil { + + + + /** + * 假设栈中的元素是Integer, 从栈顶到栈底是 : 5,4,3,2,1 调用该方法后, 元素次序变为: 1,2,3,4,5 + * 注意:只能使用Stack的基本操作,即push,pop,peek,isEmpty, 可以使用另外一个栈来辅助 + */ + public static void reverse(Stack s) { + + + + } + + /** + * 删除栈中的某个元素 注意:只能使用Stack的基本操作,即push,pop,peek,isEmpty, 可以使用另外一个栈来辅助 + * + * @param o + */ + public static void remove(Stack s,Object o) { + + } + + /** + * 从栈顶取得len个元素, 原来的栈中元素保持不变 + * 注意:只能使用Stack的基本操作,即push,pop,peek,isEmpty, 可以使用另外一个栈来辅助 + * @param len + * @return + */ + public static Object[] getTop(Stack s,int len) { + return null; + } + /** + * 字符串s 可能包含这些字符: ( ) [ ] { }, a,b,c... x,yz + * 使用堆栈检查字符串s中的括号是不是成对出现的。 + * 例如s = "([e{d}f])" , 则该字符串中的括号是成对出现, 该方法返回true + * 如果 s = "([b{x]y})", 则该字符串中的括号不是成对出现的, 该方法返回false; + * @param s + * @return + */ + public static boolean isValidPairs(String s){ + return false; + } + + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/StackUtilTest.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/StackUtilTest.java new file mode 100644 index 0000000000..76f2cb7668 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/StackUtilTest.java @@ -0,0 +1,65 @@ +package com.coding.basic.stack; + +import java.util.Stack; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +public class StackUtilTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void testReverse() { + Stack s = new Stack(); + s.push(1); + s.push(2); + s.push(3); + s.push(4); + s.push(5); + Assert.assertEquals("[1, 2, 3, 4, 5]", s.toString()); + StackUtil.reverse(s); + Assert.assertEquals("[5, 4, 3, 2, 1]", s.toString()); + } + + @Test + public void testRemove() { + Stack s = new Stack(); + s.push(1); + s.push(2); + s.push(3); + StackUtil.remove(s, 2); + Assert.assertEquals("[1, 3]", s.toString()); + } + + @Test + public void testGetTop() { + Stack s = new Stack(); + s.push(1); + s.push(2); + s.push(3); + s.push(4); + s.push(5); + { + Object[] values = StackUtil.getTop(s, 3); + Assert.assertEquals(5, values[0]); + Assert.assertEquals(4, values[1]); + Assert.assertEquals(3, values[2]); + } + } + + @Test + public void testIsValidPairs() { + Assert.assertTrue(StackUtil.isValidPairs("([e{d}f])")); + Assert.assertFalse(StackUtil.isValidPairs("([b{x]y})")); + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/StackWithTwoQueues.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/StackWithTwoQueues.java new file mode 100644 index 0000000000..d0ab4387d2 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/StackWithTwoQueues.java @@ -0,0 +1,16 @@ +package com.coding.basic.stack; + + +public class StackWithTwoQueues { + + + public void push(int data) { + + } + + public int pop() { + return -1; + } + + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/TwoStackInOneArray.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/TwoStackInOneArray.java new file mode 100644 index 0000000000..e86d056a24 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/TwoStackInOneArray.java @@ -0,0 +1,57 @@ +package com.coding.basic.stack; + +/** + * 用一个数组实现两个栈 + * 将数组的起始位置看作是第一个栈的栈底,将数组的尾部看作第二个栈的栈底,压栈时,栈顶指针分别向中间移动,直到两栈顶指针相遇,则扩容。 + * @author liuxin + * + */ +public class TwoStackInOneArray { + Object[] data = new Object[10]; + + /** + * 向第一个栈中压入元素 + * @param o + */ + public void push1(Object o){ + + } + /** + * 从第一个栈中弹出元素 + * @return + */ + public Object pop1(){ + return null; + } + + /** + * 获取第一个栈的栈顶元素 + * @return + */ + + public Object peek1(){ + return null; + } + /* + * 向第二个栈压入元素 + */ + public void push2(Object o){ + + } + /** + * 从第二个栈弹出元素 + * @return + */ + public Object pop2(){ + return null; + } + /** + * 获取第二个栈的栈顶元素 + * @return + */ + + public Object peek2(){ + return null; + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/InfixExpr.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/InfixExpr.java new file mode 100644 index 0000000000..ef85ff007f --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/InfixExpr.java @@ -0,0 +1,15 @@ +package com.coding.basic.stack.expr; + +public class InfixExpr { + String expr = null; + + public InfixExpr(String expr) { + this.expr = expr; + } + + public float evaluate() { + return 0.0f; + } + + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/InfixExprTest.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/InfixExprTest.java new file mode 100644 index 0000000000..20e34e8852 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/InfixExprTest.java @@ -0,0 +1,52 @@ +package com.coding.basic.stack.expr; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + +public class InfixExprTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testEvaluate() { + //InfixExpr expr = new InfixExpr("300*20+12*5-20/4"); + { + InfixExpr expr = new InfixExpr("2+3*4+5"); + Assert.assertEquals(19.0, expr.evaluate(), 0.001f); + } + { + InfixExpr expr = new InfixExpr("3*20+12*5-40/2"); + Assert.assertEquals(100.0, expr.evaluate(), 0.001f); + } + + { + InfixExpr expr = new InfixExpr("3*20/2"); + Assert.assertEquals(30, expr.evaluate(), 0.001f); + } + + { + InfixExpr expr = new InfixExpr("20/2*3"); + Assert.assertEquals(30, expr.evaluate(), 0.001f); + } + + { + InfixExpr expr = new InfixExpr("10-30+50"); + Assert.assertEquals(30, expr.evaluate(), 0.001f); + } + { + InfixExpr expr = new InfixExpr("10-2*3+50"); + Assert.assertEquals(54, expr.evaluate(), 0.001f); + } + + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/InfixToPostfix.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/InfixToPostfix.java new file mode 100644 index 0000000000..96a2194a67 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/InfixToPostfix.java @@ -0,0 +1,14 @@ +package com.coding.basic.stack.expr; + +import java.util.List; + +public class InfixToPostfix { + + public static List convert(String expr) { + + return null; + } + + + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/PostfixExpr.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/PostfixExpr.java new file mode 100644 index 0000000000..dcbb18be4b --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/PostfixExpr.java @@ -0,0 +1,18 @@ +package com.coding.basic.stack.expr; + +import java.util.List; +import java.util.Stack; + +public class PostfixExpr { +String expr = null; + + public PostfixExpr(String expr) { + this.expr = expr; + } + + public float evaluate() { + return 0.0f; + } + + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/PostfixExprTest.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/PostfixExprTest.java new file mode 100644 index 0000000000..c0435a2db5 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/PostfixExprTest.java @@ -0,0 +1,41 @@ +package com.coding.basic.stack.expr; + + + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class PostfixExprTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testEvaluate() { + { + PostfixExpr expr = new PostfixExpr("6 5 2 3 + 8 * + 3 + *"); + Assert.assertEquals(288, expr.evaluate(),0.0f); + } + { + //9+(3-1)*3+10/2 + PostfixExpr expr = new PostfixExpr("9 3 1-3*+ 10 2/+"); + Assert.assertEquals(20, expr.evaluate(),0.0f); + } + + { + //10-2*3+50 + PostfixExpr expr = new PostfixExpr("10 2 3 * - 50 +"); + Assert.assertEquals(54, expr.evaluate(),0.0f); + } + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/PrefixExpr.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/PrefixExpr.java new file mode 100644 index 0000000000..956927e2df --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/PrefixExpr.java @@ -0,0 +1,18 @@ +package com.coding.basic.stack.expr; + +import java.util.List; +import java.util.Stack; + +public class PrefixExpr { + String expr = null; + + public PrefixExpr(String expr) { + this.expr = expr; + } + + public float evaluate() { + return 0.0f; + } + + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/PrefixExprTest.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/PrefixExprTest.java new file mode 100644 index 0000000000..5cec210e75 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/PrefixExprTest.java @@ -0,0 +1,45 @@ +package com.coding.basic.stack.expr; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + +public class PrefixExprTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testEvaluate() { + { + // 2*3+4*5 + PrefixExpr expr = new PrefixExpr("+ * 2 3* 4 5"); + Assert.assertEquals(26, expr.evaluate(),0.001f); + } + { + // 4*2 + 6+9*2/3 -8 + PrefixExpr expr = new PrefixExpr("-++6/*2 9 3 * 4 2 8"); + Assert.assertEquals(12, expr.evaluate(),0.001f); + } + { + //(3+4)*5-6 + PrefixExpr expr = new PrefixExpr("- * + 3 4 5 6"); + Assert.assertEquals(29, expr.evaluate(),0.001f); + } + { + //1+((2+3)*4)-5 + PrefixExpr expr = new PrefixExpr("- + 1 * + 2 3 4 5"); + Assert.assertEquals(16, expr.evaluate(),0.001f); + } + + + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/Token.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/Token.java new file mode 100644 index 0000000000..8579743fe9 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/Token.java @@ -0,0 +1,50 @@ +package com.coding.basic.stack.expr; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +class Token { + public static final List OPERATORS = Arrays.asList("+", "-", "*", "/"); + private static final Map priorities = new HashMap<>(); + static { + priorities.put("+", 1); + priorities.put("-", 1); + priorities.put("*", 2); + priorities.put("/", 2); + } + static final int OPERATOR = 1; + static final int NUMBER = 2; + String value; + int type; + public Token(int type, String value){ + this.type = type; + this.value = value; + } + + public boolean isNumber() { + return type == NUMBER; + } + + public boolean isOperator() { + return type == OPERATOR; + } + + public int getIntValue() { + return Integer.valueOf(value).intValue(); + } + public String toString(){ + return value; + } + + public boolean hasHigherPriority(Token t){ + if(!this.isOperator() && !t.isOperator()){ + throw new RuntimeException("numbers can't compare priority"); + } + return priorities.get(this.value) - priorities.get(t.value) > 0; + } + + + +} \ No newline at end of file diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/TokenParser.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/TokenParser.java new file mode 100644 index 0000000000..d3b0f167e1 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/TokenParser.java @@ -0,0 +1,57 @@ +package com.coding.basic.stack.expr; + +import java.util.ArrayList; +import java.util.List; + +public class TokenParser { + + + public List parse(String expr) { + List tokens = new ArrayList<>(); + + int i = 0; + + while (i < expr.length()) { + + char c = expr.charAt(i); + + if (isOperator(c)) { + + Token t = new Token(Token.OPERATOR, String.valueOf(c)); + tokens.add(t); + i++; + + } else if (Character.isDigit(c)) { + + int nextOperatorIndex = indexOfNextOperator(i, expr); + String value = expr.substring(i, nextOperatorIndex); + Token t = new Token(Token.NUMBER, value); + tokens.add(t); + i = nextOperatorIndex; + + } else{ + System.out.println("char :["+c+"] is not number or operator,ignore"); + i++; + } + + } + return tokens; + } + + private int indexOfNextOperator(int i, String expr) { + + while (Character.isDigit(expr.charAt(i))) { + i++; + if (i == expr.length()) { + break; + } + } + return i; + + } + + private boolean isOperator(char c) { + String sc = String.valueOf(c); + return Token.OPERATORS.contains(sc); + } +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/TokenParserTest.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/TokenParserTest.java new file mode 100644 index 0000000000..399d3e857e --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/stack/expr/TokenParserTest.java @@ -0,0 +1,41 @@ +package com.coding.basic.stack.expr; + +import static org.junit.Assert.*; + +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class TokenParserTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void test() { + + TokenParser parser = new TokenParser(); + List tokens = parser.parse("300*20+12*5-20/4"); + + Assert.assertEquals(300, tokens.get(0).getIntValue()); + Assert.assertEquals("*", tokens.get(1).toString()); + Assert.assertEquals(20, tokens.get(2).getIntValue()); + Assert.assertEquals("+", tokens.get(3).toString()); + Assert.assertEquals(12, tokens.get(4).getIntValue()); + Assert.assertEquals("*", tokens.get(5).toString()); + Assert.assertEquals(5, tokens.get(6).getIntValue()); + Assert.assertEquals("-", tokens.get(7).toString()); + Assert.assertEquals(20, tokens.get(8).getIntValue()); + Assert.assertEquals("/", tokens.get(9).toString()); + Assert.assertEquals(4, tokens.get(10).getIntValue()); + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/tree/BinarySearchTree.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/tree/BinarySearchTree.java new file mode 100644 index 0000000000..4536ee7a2b --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/tree/BinarySearchTree.java @@ -0,0 +1,55 @@ +package com.coding.basic.tree; + +import java.util.ArrayList; +import java.util.List; + +import com.coding.basic.queue.Queue; + +public class BinarySearchTree { + + BinaryTreeNode root; + public BinarySearchTree(BinaryTreeNode root){ + this.root = root; + } + public BinaryTreeNode getRoot(){ + return root; + } + public T findMin(){ + return null; + } + public T findMax(){ + return null; + } + public int height() { + return -1; + } + public int size() { + return -1; + } + public void remove(T e){ + + } + public List levelVisit(){ + + return null; + } + public boolean isValid(){ + return false; + } + public T getLowestCommonAncestor(T n1, T n2){ + return null; + + } + /** + * 返回所有满足下列条件的节点的值: n1 <= n <= n2 , n 为 + * 该二叉查找树中的某一节点 + * @param n1 + * @param n2 + * @return + */ + public List getNodesBetween(T n1, T n2){ + return null; + } + +} + diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/tree/BinarySearchTreeTest.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/tree/BinarySearchTreeTest.java new file mode 100644 index 0000000000..4a53dbe2f1 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/tree/BinarySearchTreeTest.java @@ -0,0 +1,109 @@ +package com.coding.basic.tree; + +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class BinarySearchTreeTest { + + BinarySearchTree tree = null; + + @Before + public void setUp() throws Exception { + BinaryTreeNode root = new BinaryTreeNode(6); + root.left = new BinaryTreeNode(2); + root.right = new BinaryTreeNode(8); + root.left.left = new BinaryTreeNode(1); + root.left.right = new BinaryTreeNode(4); + root.left.right.left = new BinaryTreeNode(3); + root.left.right.right = new BinaryTreeNode(5); + tree = new BinarySearchTree(root); + } + + @After + public void tearDown() throws Exception { + tree = null; + } + + @Test + public void testFindMin() { + Assert.assertEquals(1, tree.findMin().intValue()); + + } + + @Test + public void testFindMax() { + Assert.assertEquals(8, tree.findMax().intValue()); + } + + @Test + public void testHeight() { + Assert.assertEquals(4, tree.height()); + } + + @Test + public void testSize() { + Assert.assertEquals(7, tree.size()); + } + + @Test + public void testRemoveLeaf() { + tree.remove(3); + BinaryTreeNode root= tree.getRoot(); + Assert.assertEquals(4, root.left.right.data.intValue()); + + } + @Test + public void testRemoveMiddleNode1() { + tree.remove(4); + BinaryTreeNode root= tree.getRoot(); + Assert.assertEquals(5, root.left.right.data.intValue()); + Assert.assertEquals(3, root.left.right.left.data.intValue()); + } + @Test + public void testRemoveMiddleNode2() { + tree.remove(2); + BinaryTreeNode root= tree.getRoot(); + Assert.assertEquals(3, root.left.data.intValue()); + Assert.assertEquals(4, root.left.right.data.intValue()); + } + + @Test + public void testLevelVisit() { + List values = tree.levelVisit(); + Assert.assertEquals("[6, 2, 8, 1, 4, 3, 5]", values.toString()); + + } + @Test + public void testLCA(){ + Assert.assertEquals(2,tree.getLowestCommonAncestor(1, 5).intValue()); + Assert.assertEquals(2,tree.getLowestCommonAncestor(1, 4).intValue()); + Assert.assertEquals(6,tree.getLowestCommonAncestor(3, 8).intValue()); + } + @Test + public void testIsValid() { + + Assert.assertTrue(tree.isValid()); + + BinaryTreeNode root = new BinaryTreeNode(6); + root.left = new BinaryTreeNode(2); + root.right = new BinaryTreeNode(8); + root.left.left = new BinaryTreeNode(4); + root.left.right = new BinaryTreeNode(1); + root.left.right.left = new BinaryTreeNode(3); + tree = new BinarySearchTree(root); + + Assert.assertFalse(tree.isValid()); + } + @Test + public void testGetNodesBetween(){ + List numbers = this.tree.getNodesBetween(3, 8); + System.out.println(numbers.toString()); + + } +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/tree/BinaryTreeNode.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/tree/BinaryTreeNode.java new file mode 100644 index 0000000000..c1421cd398 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/tree/BinaryTreeNode.java @@ -0,0 +1,35 @@ +package com.coding.basic.tree; + +public class BinaryTreeNode { + + public T data; + public BinaryTreeNode left; + public BinaryTreeNode right; + + public BinaryTreeNode(T data){ + this.data=data; + } + public T getData() { + return data; + } + public void setData(T data) { + this.data = data; + } + public BinaryTreeNode getLeft() { + return left; + } + public void setLeft(BinaryTreeNode left) { + this.left = left; + } + public BinaryTreeNode getRight() { + return right; + } + public void setRight(BinaryTreeNode right) { + this.right = right; + } + + public BinaryTreeNode insert(Object o){ + return null; + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/tree/BinaryTreeUtil.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/tree/BinaryTreeUtil.java new file mode 100644 index 0000000000..b033cbe1d5 --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/tree/BinaryTreeUtil.java @@ -0,0 +1,66 @@ +package com.coding.basic.tree; + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +public class BinaryTreeUtil { + /** + * 用递归的方式实现对二叉树的前序遍历, 需要通过BinaryTreeUtilTest测试 + * + * @param root + * @return + */ + public static List preOrderVisit(BinaryTreeNode root) { + List result = new ArrayList(); + + return result; + } + + /** + * 用递归的方式实现对二叉树的中遍历 + * + * @param root + * @return + */ + public static List inOrderVisit(BinaryTreeNode root) { + List result = new ArrayList(); + + return result; + } + + /** + * 用递归的方式实现对二叉树的后遍历 + * + * @param root + * @return + */ + public static List postOrderVisit(BinaryTreeNode root) { + List result = new ArrayList(); + + return result; + } + /** + * 用非递归的方式实现对二叉树的前序遍历 + * @param root + * @return + */ + public static List preOrderWithoutRecursion(BinaryTreeNode root) { + + List result = new ArrayList(); + + return result; + } + /** + * 用非递归的方式实现对二叉树的中序遍历 + * @param root + * @return + */ + public static List inOrderWithoutRecursion(BinaryTreeNode root) { + + List result = new ArrayList(); + + return result; + } + +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/tree/BinaryTreeUtilTest.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/tree/BinaryTreeUtilTest.java new file mode 100644 index 0000000000..41857e137d --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/tree/BinaryTreeUtilTest.java @@ -0,0 +1,75 @@ +package com.coding.basic.tree; + +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class BinaryTreeUtilTest { + + BinaryTreeNode root = null; + @Before + public void setUp() throws Exception { + root = new BinaryTreeNode(1); + root.setLeft(new BinaryTreeNode(2)); + root.setRight(new BinaryTreeNode(5)); + root.getLeft().setLeft(new BinaryTreeNode(3)); + root.getLeft().setRight(new BinaryTreeNode(4)); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testPreOrderVisit() { + + List result = BinaryTreeUtil.preOrderVisit(root); + Assert.assertEquals("[1, 2, 3, 4, 5]", result.toString()); + + + } + @Test + public void testInOrderVisit() { + + + List result = BinaryTreeUtil.inOrderVisit(root); + Assert.assertEquals("[3, 2, 4, 1, 5]", result.toString()); + + } + + @Test + public void testPostOrderVisit() { + + + List result = BinaryTreeUtil.postOrderVisit(root); + Assert.assertEquals("[3, 4, 2, 5, 1]", result.toString()); + + } + + + @Test + public void testInOrderVisitWithoutRecursion() { + BinaryTreeNode node = root.getLeft().getRight(); + node.setLeft(new BinaryTreeNode(6)); + node.setRight(new BinaryTreeNode(7)); + + List result = BinaryTreeUtil.inOrderWithoutRecursion(root); + Assert.assertEquals("[3, 2, 6, 4, 7, 1, 5]", result.toString()); + + } + @Test + public void testPreOrderVisitWithoutRecursion() { + BinaryTreeNode node = root.getLeft().getRight(); + node.setLeft(new BinaryTreeNode(6)); + node.setRight(new BinaryTreeNode(7)); + + List result = BinaryTreeUtil.preOrderWithoutRecursion(root); + Assert.assertEquals("[1, 2, 3, 4, 6, 7, 5]", result.toString()); + + } +} diff --git a/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/tree/FileList.java b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/tree/FileList.java new file mode 100644 index 0000000000..6e65192e4a --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/main/java/com/coding/basic/tree/FileList.java @@ -0,0 +1,10 @@ +package com.coding.basic.tree; + +import java.io.File; + +public class FileList { + public void list(File f) { + } + + +} diff --git a/students/992331664/data-structure/data-structure/src/test/java/com/coding/basic/array/ArrayUtilTest.java b/students/992331664/data-structure/data-structure/src/test/java/com/coding/basic/array/ArrayUtilTest.java new file mode 100644 index 0000000000..255267ce2c --- /dev/null +++ b/students/992331664/data-structure/data-structure/src/test/java/com/coding/basic/array/ArrayUtilTest.java @@ -0,0 +1,52 @@ +package com.coding.basic.array; + +import java.util.Arrays; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class ArrayUtilTest { + + ArrayUtil arrayUtil; + + int[] resultArray ; + + @Before + public void before(){ + arrayUtil = new ArrayUtil(); + } + + @After + public void printArray(){ + System.out.println(Arrays.toString(resultArray)); + } + + @Test + public void testReverseArray(){ + int[] arr = {12,344,5,6,0,4,65,4,}; + arrayUtil.reverseArray(arr); + resultArray = arr; + } + + @Test + public void testRemoveZero(){ + int[] arr = {}; + resultArray = arrayUtil.removeZero(arr); + } + + @Test + public void testMerge(){ + } + + @Test + public void testGrow(){ + int[] arr = {1,6,4,2,0}; + resultArray = arrayUtil.grow(arr, 2); + } + + @Test + public void testFibonacci(){ + resultArray = arrayUtil.fibonacci(15); + } +} diff --git a/students/992331664/ood/ood/build.gradle b/students/992331664/ood/ood/build.gradle new file mode 100644 index 0000000000..588e5e86aa --- /dev/null +++ b/students/992331664/ood/ood/build.gradle @@ -0,0 +1,30 @@ +/* + * This build file was auto generated by running the Gradle 'init' task + * by 'gant' at '17-6-13 上午11:30' with Gradle 3.0 + * + * This generated file contains a sample Java project to get you started. + * For more details take a look at the Java Quickstart chapter in the Gradle + * user guide available at https://docs.gradle.org/3.0/userguide/tutorial_java_projects.html + */ + +// Apply the java plugin to add support for Java +apply plugin: 'java' + +// In this section you declare where to find the dependencies of your project +repositories { + // Use 'jcenter' for resolving your dependencies. + // You can declare any Maven/Ivy/file repository here. + jcenter() +} + +// In this section you declare the dependencies for your production and test code +dependencies { + // The production code uses the SLF4J logging API at compile time + compile 'org.slf4j:slf4j-api:1.7.21' + + // Declare the dependency for your favourite test framework you want to use in your tests. + // TestNG is also supported by the Gradle Test task. Just change the + // testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add + // 'test.useTestNG()' to your build script. + testCompile 'junit:junit:4.12' +} diff --git a/students/992331664/ood/ood/gradle/wrapper/gradle-wrapper.properties b/students/992331664/ood/ood/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..5a2cbbeeab --- /dev/null +++ b/students/992331664/ood/ood/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Jun 13 11:30:26 CST 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-3.0-bin.zip diff --git a/students/992331664/ood/ood/gradlew b/students/992331664/ood/ood/gradlew new file mode 100644 index 0000000000..9aa616c273 --- /dev/null +++ b/students/992331664/ood/ood/gradlew @@ -0,0 +1,169 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [[ "$(uname)" == "Darwin" ]] && [[ "$HOME" == "$PWD" ]]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/students/992331664/ood/ood/gradlew.bat b/students/992331664/ood/ood/gradlew.bat new file mode 100644 index 0000000000..f9553162f1 --- /dev/null +++ b/students/992331664/ood/ood/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/students/992331664/ood/ood/settings.gradle b/students/992331664/ood/ood/settings.gradle new file mode 100644 index 0000000000..f98d8fb6d8 --- /dev/null +++ b/students/992331664/ood/ood/settings.gradle @@ -0,0 +1,19 @@ +/* + * This settings file was auto generated by the Gradle buildInit task + * by 'gant' at '17-6-13 上午11:30' with Gradle 3.0 + * + * The settings file is used to specify which projects to include in your build. + * In a single project build this file can be empty or even removed. + * + * Detailed information about configuring a multi-project build in Gradle can be found + * in the user guide at https://docs.gradle.org/3.0/userguide/multi_project_builds.html + */ + +/* +// To declare projects as part of a multi-project build use the 'include' method +include 'shared' +include 'api' +include 'services:webservice' +*/ + +rootProject.name = 'ood' diff --git a/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/PromotionMail.java b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..9df4e1c77a --- /dev/null +++ b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,91 @@ +package com.coderising.ood.srp; + +import java.io.File; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import com.coderising.ood.srp.config.Configuration; +import com.coderising.ood.srp.config.ConnectionConfig; +import com.coderising.ood.srp.model.MailInfo; +import com.coderising.ood.srp.model.Product; +import com.coderising.ood.srp.model.Subscriptions; +import com.coderising.ood.srp.service.ProductService; +import com.coderising.ood.srp.service.SubscriptionsService; +import com.coderising.ood.srp.util.MailUtil; + +public class PromotionMail { + + protected SubscriptionsService subscriptionsService; + + protected ProductService productService; + + public PromotionMail(SubscriptionsService subscriptionsService, ProductService productService) { + this.subscriptionsService = subscriptionsService; + this.productService = productService; + } + + /** + * 发送促销邮件 + * + * @param file + * 促销产品文件 + * @param mailDebug + * @throws Exception + */ + public void sendPromotionMail(File file, boolean mailDebug) throws Exception { + + // 得到促销的产品 + List products = productService.doFindPromotionalProducts(file); + + // 得到促销产品的订阅信息 + List subscriptions = subscriptionsService.doFindByProducts(products); + + // 得到订阅人的邮箱和名称,邮箱内容 + List mails = getMails(subscriptions); + + // 发送邮箱 + sendEMails(new ConnectionConfig(new Configuration()), mails, mailDebug); + } + + // 得到发送的邮箱对象 + protected List getMails(List subscriptions) { + + List mails = new ArrayList(); + String subject = "您关注的产品降价了"; + + for (Subscriptions sub : subscriptions) { + String productDesc = sub.getProduct().getProductDesc(); + String message = "尊敬的 " + sub.getName() + ", 您关注的产品 " + productDesc + " 降价了,欢迎购买!"; + mails.add(new MailInfo(subject, message, sub.getEmail())); + } + return mails; + } + + // 发送邮件 + protected void sendEMails(ConnectionConfig config, List mails, boolean debug) { + if (mails == null) { + System.out.println("没有邮件需要发送"); + return; + } + System.out.println("开始发送邮件"); + Iterator iter = mails.iterator(); + while (iter.hasNext()) { + MailInfo mail = iter.next(); + if (mail.getToAddress().length() <= 0) { + continue; + } + try { + MailUtil.sendEmail(mail.getToAddress(), config.getFromAddress(), mail.getSubject(), mail.getMessage(),config.getSmtpHost(), debug); + } catch (Exception e) { + try { + MailUtil.sendEmail(mail.getToAddress(), config.getFromAddress(), mail.getSubject(),mail.getMessage(), config.getAltSmtpHost(), debug); + + } catch (Exception e2) { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + System.out.println("发送邮件结束"); + } +} diff --git a/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/config/Configuration.java b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/config/Configuration.java new file mode 100644 index 0000000000..bbed122807 --- /dev/null +++ b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/config/Configuration.java @@ -0,0 +1,22 @@ +package com.coderising.ood.srp.config; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + return configurations.get(key); + } + +} diff --git a/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/config/ConfigurationKeys.java b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/config/ConfigurationKeys.java new file mode 100644 index 0000000000..cadb23ed24 --- /dev/null +++ b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/config/ConfigurationKeys.java @@ -0,0 +1,10 @@ +package com.coderising.ood.srp.config; + + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/config/ConnectionConfig.java b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/config/ConnectionConfig.java new file mode 100644 index 0000000000..531efe251d --- /dev/null +++ b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/config/ConnectionConfig.java @@ -0,0 +1,41 @@ +package com.coderising.ood.srp.config; + +/** + * 邮箱连接配置类 + * + */ +public class ConnectionConfig { + private String smtpHost; + private String altSmtpHost; + private String fromAddress; + + public ConnectionConfig(Configuration config) { + this.smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER); + this.altSmtpHost = config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + this.fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + } + + public String getSmtpHost() { + return smtpHost; + } + + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } + + public String getAltSmtpHost() { + return altSmtpHost; + } + + public void setAltSmtpHost(String altSmtpHost) { + this.altSmtpHost = altSmtpHost; + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } +} diff --git a/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/model/MailInfo.java b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/model/MailInfo.java new file mode 100644 index 0000000000..2744e2fd1f --- /dev/null +++ b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/model/MailInfo.java @@ -0,0 +1,52 @@ +package com.coderising.ood.srp.model; + +/** + * 邮箱信息 + * + */ +public class MailInfo { + private String subject; + private String message; + private String toAddress; + + public MailInfo() { + super(); + } + + public MailInfo(String subject, String message, String toAddress) { + super(); + this.subject = subject; + this.message = message; + this.toAddress = toAddress; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + @Override + public String toString() { + return "Mail [subject=" + subject + ", message=" + message + ", toAddress=" + toAddress + "]"; + } + +} diff --git a/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/model/Product.java b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/model/Product.java new file mode 100644 index 0000000000..fcfc5f7cf4 --- /dev/null +++ b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/model/Product.java @@ -0,0 +1,36 @@ +package com.coderising.ood.srp.model; + +/** + * 产品信息 + */ +public class Product { + + private String productID; + + private String productDesc; + + public Product() { + } + + public String getProductID() { + return productID; + } + + public void setProductID(String productID) { + this.productID = productID; + } + + public String getProductDesc() { + return productDesc; + } + + public void setProductDesc(String productDesc) { + this.productDesc = productDesc; + } + + @Override + public String toString() { + return "Product [productID=" + productID + ", productDesc=" + productDesc + "]"; + } + +} diff --git a/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/model/Subscriptions.java b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/model/Subscriptions.java new file mode 100644 index 0000000000..8a25fe19ed --- /dev/null +++ b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/model/Subscriptions.java @@ -0,0 +1,53 @@ +package com.coderising.ood.srp.model; + +/** + * 订阅信息,主要有订阅产品,订阅用户 + * + */ +public class Subscriptions { + + // name 和 email 应该存放在用户信息中,如叫订阅用户, + private String name; + private String email; + private String productId; + private Product product; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getProductId() { + return productId; + } + + public void setProductId(String productId) { + this.productId = productId; + } + + public Product getProduct() { + return product; + } + + public void setProduct(Product product) { + this.product = product; + } + + @Override + public String toString() { + return "Subscriptions [name=" + name + ", email=" + email + ", productId=" + productId + ", product=" + product + + "]"; + } + +} diff --git a/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/product_promotion.txt b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..b7a974adb3 --- /dev/null +++ b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file diff --git a/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/service/ProductService.java b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/service/ProductService.java new file mode 100644 index 0000000000..aae01818f9 --- /dev/null +++ b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/service/ProductService.java @@ -0,0 +1,17 @@ +package com.coderising.ood.srp.service; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +import com.coderising.ood.srp.model.Product; + +public interface ProductService { + + /** + * 查询促销产品 + * @return 促销产品 + * @throws IOException + */ + List doFindPromotionalProducts(File file) throws IOException; +} diff --git a/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/service/SubscriptionsService.java b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/service/SubscriptionsService.java new file mode 100644 index 0000000000..c31c25c084 --- /dev/null +++ b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/service/SubscriptionsService.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp.service; + +import java.util.List; + +import com.coderising.ood.srp.model.Product; +import com.coderising.ood.srp.model.Subscriptions; + +public interface SubscriptionsService { + + /** + * 查询产品的订阅人 + * + * @param products + * 产品 + * @return 订阅信息 + */ + List doFindByProducts(List products); +} diff --git a/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/service/impl/ProductServiceImpl.java b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/service/impl/ProductServiceImpl.java new file mode 100644 index 0000000000..66fe9b6d90 --- /dev/null +++ b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/service/impl/ProductServiceImpl.java @@ -0,0 +1,40 @@ +package com.coderising.ood.srp.service.impl; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import com.coderising.ood.srp.model.Product; +import com.coderising.ood.srp.service.ProductService; + +public class ProductServiceImpl implements ProductService { + + @Override + public List doFindPromotionalProducts(File file) throws IOException { + + List products = new ArrayList(); + + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + while (br.read() != -1) { + Product product = new Product(); + String temp = br.readLine(); + String[] data = temp.split(" "); + product.setProductID(data[0]); + product.setProductDesc(data[1]); + products.add(product); + } + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + return products; + } + +} diff --git a/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/service/impl/SubscriptionsServiceImpl.java b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/service/impl/SubscriptionsServiceImpl.java new file mode 100644 index 0000000000..164621e2ea --- /dev/null +++ b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/service/impl/SubscriptionsServiceImpl.java @@ -0,0 +1,40 @@ +package com.coderising.ood.srp.service.impl; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.stream.Collectors; + +import com.coderising.ood.srp.model.Product; +import com.coderising.ood.srp.model.Subscriptions; +import com.coderising.ood.srp.service.SubscriptionsService; +import com.coderising.ood.srp.util.DBUtil; + +public class SubscriptionsServiceImpl implements SubscriptionsService { + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + @SuppressWarnings({ "unused", "rawtypes" }) + @Override + public List doFindByProducts(List products) { + + List productIds = products.stream().map(Product::getProductID).collect(Collectors.toList()); + String sendMailQuery = "Select name from subscriptions where product_id in( productIds ) and send_mail = 1 "; + List list = DBUtil.query(sendMailQuery); + + // 这里只是模拟数据 + List subscriptions = new ArrayList(); + for (int i = 0; i < list.size(); i++) { + HashMap userInfo = (HashMap) list.get(i); + Subscriptions ss = new Subscriptions(); + ss.setName((String) userInfo.get(NAME_KEY)); + ss.setEmail((String) userInfo.get(EMAIL_KEY)); + ss.setProduct(products.get(i)); + subscriptions.add(ss); + } + + return subscriptions; + } + +} diff --git a/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/util/DBUtil.java b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/util/DBUtil.java new file mode 100644 index 0000000000..33bb5cfd43 --- /dev/null +++ b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/util/DBUtil.java @@ -0,0 +1,28 @@ +package com.coderising.ood.srp.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + + /** + * 应该从数据库读, 但是简化为直接生成。 + * + * @param sql + * @return + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + public static List query(String sql) { + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } +} diff --git a/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/util/MailUtil.java b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/util/MailUtil.java new file mode 100644 index 0000000000..bb028c690c --- /dev/null +++ b/students/992331664/ood/ood/src/main/java/com/coderising/ood/srp/util/MailUtil.java @@ -0,0 +1,18 @@ +package com.coderising.ood.srp.util; + +public class MailUtil { + + public static void sendEmail(String toAddress, String fromAddress, String subject, String message, String smtpHost, + boolean debug) { + //假装发了一封邮件 + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer.toString()); + + } + + +} diff --git a/students/992331664/ood/ood/src/test/java/com/coderising/ood/srp/PromotionMailTest.java b/students/992331664/ood/ood/src/test/java/com/coderising/ood/srp/PromotionMailTest.java new file mode 100644 index 0000000000..a3c91dc4bb --- /dev/null +++ b/students/992331664/ood/ood/src/test/java/com/coderising/ood/srp/PromotionMailTest.java @@ -0,0 +1,34 @@ +package com.coderising.ood.srp; + +import java.io.File; + +import org.junit.Before; +import org.junit.Test; + +import com.coderising.ood.srp.service.ProductService; +import com.coderising.ood.srp.service.SubscriptionsService; +import com.coderising.ood.srp.service.impl.ProductServiceImpl; +import com.coderising.ood.srp.service.impl.SubscriptionsServiceImpl; + +public class PromotionMailTest { + + PromotionMail promotionMail; + + @Before + public void before() { + SubscriptionsService subscriptionsService = new SubscriptionsServiceImpl(); + ProductService productService = new ProductServiceImpl(); + promotionMail = new PromotionMail(subscriptionsService, productService); + } + + @Test + public void testSendPromotionMail() throws Exception { + String path = System.getProperty("user.dir"); + + path += "\\bin\\com\\coderising\\ood\\srp\\product_promotion.txt"; + + File file = new File(path); + + promotionMail.sendPromotionMail(file, false); + } +} diff --git a/students/996108220/src/com/coderising/ood/ocp/DateUtil.java b/students/996108220/src/com/coderising/ood/ocp/DateUtil.java new file mode 100644 index 0000000000..13369f5684 --- /dev/null +++ b/students/996108220/src/com/coderising/ood/ocp/DateUtil.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp; + +public class DateUtil { + + + public static String getCurrentDateAsString() { + + return null; + } + +} diff --git a/students/996108220/src/com/coderising/ood/ocp/EmailLog.java b/students/996108220/src/com/coderising/ood/ocp/EmailLog.java new file mode 100644 index 0000000000..20eb93ac9d --- /dev/null +++ b/students/996108220/src/com/coderising/ood/ocp/EmailLog.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp; + +public class EmailLog implements LogMethod{ + int method = 1; + @Override + public void logBehavior(String logMsg) { + + MailUtil.send(logMsg); + } + +} diff --git a/students/996108220/src/com/coderising/ood/ocp/LogMethod.java b/students/996108220/src/com/coderising/ood/ocp/LogMethod.java new file mode 100644 index 0000000000..69677d8c89 --- /dev/null +++ b/students/996108220/src/com/coderising/ood/ocp/LogMethod.java @@ -0,0 +1,6 @@ +package com.coderising.ood.ocp; + +public interface LogMethod { + int method = 0; + public abstract void logBehavior(String logMsg); +} diff --git a/students/996108220/src/com/coderising/ood/ocp/LogType.java b/students/996108220/src/com/coderising/ood/ocp/LogType.java new file mode 100644 index 0000000000..bd6de81087 --- /dev/null +++ b/students/996108220/src/com/coderising/ood/ocp/LogType.java @@ -0,0 +1,6 @@ +package com.coderising.ood.ocp; + +public interface LogType { + int type = 0; + public abstract String getLogMsg(String msg) ; +} diff --git a/students/996108220/src/com/coderising/ood/ocp/Logger.java b/students/996108220/src/com/coderising/ood/ocp/Logger.java new file mode 100644 index 0000000000..e0105f9b23 --- /dev/null +++ b/students/996108220/src/com/coderising/ood/ocp/Logger.java @@ -0,0 +1,19 @@ +package com.coderising.ood.ocp; + +public class Logger { + + public LogType logType; + public LogMethod logMethod; + + public Logger(LogType logType, LogMethod logMethod){ + this.logType = logType; + this.logMethod = logMethod; + } + public void log(String msg){ + + String logMsg = logType.getLogMsg(msg); + logMethod.logBehavior(logMsg); + + } +} + diff --git a/students/996108220/src/com/coderising/ood/ocp/MailUtil.java b/students/996108220/src/com/coderising/ood/ocp/MailUtil.java new file mode 100644 index 0000000000..59d77649a2 --- /dev/null +++ b/students/996108220/src/com/coderising/ood/ocp/MailUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class MailUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/996108220/src/com/coderising/ood/ocp/PrintLog.java b/students/996108220/src/com/coderising/ood/ocp/PrintLog.java new file mode 100644 index 0000000000..b2391ecd52 --- /dev/null +++ b/students/996108220/src/com/coderising/ood/ocp/PrintLog.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp; + +public class PrintLog implements LogMethod{ + int method = 3; + @Override + public void logBehavior(String logMsg) { + System.out.println(logMsg); + + } + +} diff --git a/students/996108220/src/com/coderising/ood/ocp/RawLog.java b/students/996108220/src/com/coderising/ood/ocp/RawLog.java new file mode 100644 index 0000000000..0ac45244c8 --- /dev/null +++ b/students/996108220/src/com/coderising/ood/ocp/RawLog.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class RawLog implements LogType{ + int type = 1; + @Override + public String getLogMsg(String msg) { + return msg; + } + +} diff --git a/students/996108220/src/com/coderising/ood/ocp/RawLogWithData.java b/students/996108220/src/com/coderising/ood/ocp/RawLogWithData.java new file mode 100644 index 0000000000..280fb3b54f --- /dev/null +++ b/students/996108220/src/com/coderising/ood/ocp/RawLogWithData.java @@ -0,0 +1,12 @@ +package com.coderising.ood.ocp; + +public class RawLogWithData implements LogType{ + int type = 2; + @Override + public String getLogMsg(String msg) { + String txtDate = DateUtil.getCurrentDateAsString(); + String logMsg = txtDate + ": " + msg; + return logMsg; + } + +} diff --git a/students/996108220/src/com/coderising/ood/ocp/SMSUtil.java b/students/996108220/src/com/coderising/ood/ocp/SMSUtil.java new file mode 100644 index 0000000000..fab4cd01b7 --- /dev/null +++ b/students/996108220/src/com/coderising/ood/ocp/SMSUtil.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class SMSUtil { + + public static void send(String logMsg) { + // TODO Auto-generated method stub + + } + +} diff --git a/students/996108220/src/com/coderising/ood/ocp/SmsLog.java b/students/996108220/src/com/coderising/ood/ocp/SmsLog.java new file mode 100644 index 0000000000..e61938d844 --- /dev/null +++ b/students/996108220/src/com/coderising/ood/ocp/SmsLog.java @@ -0,0 +1,10 @@ +package com.coderising.ood.ocp; + +public class SmsLog implements LogMethod{ + int method = 2; + @Override + public void logBehavior(String logMsg) { + SMSUtil.send(logMsg); + } + +} diff --git a/students/996108220/src/com/coderising/ood/ocp/good/Formatter.java b/students/996108220/src/com/coderising/ood/ocp/good/Formatter.java new file mode 100644 index 0000000000..b6e2ccbc16 --- /dev/null +++ b/students/996108220/src/com/coderising/ood/ocp/good/Formatter.java @@ -0,0 +1,7 @@ +package com.coderising.ood.ocp.good; + +public interface Formatter { + + String format(String msg); + +} diff --git a/students/996108220/src/com/coderising/ood/ocp/good/FormatterFactory.java b/students/996108220/src/com/coderising/ood/ocp/good/FormatterFactory.java new file mode 100644 index 0000000000..3c2009a674 --- /dev/null +++ b/students/996108220/src/com/coderising/ood/ocp/good/FormatterFactory.java @@ -0,0 +1,13 @@ +package com.coderising.ood.ocp.good; + +public class FormatterFactory { + public static Formatter createFormatter(int type){ + if(type == 1){ + return new RawFormatter(); + } + if (type == 2){ + return new HtmlFormatter(); + } + return null; + } +} diff --git a/students/996108220/src/com/coderising/ood/ocp/good/HtmlFormatter.java b/students/996108220/src/com/coderising/ood/ocp/good/HtmlFormatter.java new file mode 100644 index 0000000000..3d375f5acc --- /dev/null +++ b/students/996108220/src/com/coderising/ood/ocp/good/HtmlFormatter.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp.good; + +public class HtmlFormatter implements Formatter { + + @Override + public String format(String msg) { + + return null; + } + +} diff --git a/students/996108220/src/com/coderising/ood/ocp/good/Logger.java b/students/996108220/src/com/coderising/ood/ocp/good/Logger.java new file mode 100644 index 0000000000..f206472d0d --- /dev/null +++ b/students/996108220/src/com/coderising/ood/ocp/good/Logger.java @@ -0,0 +1,18 @@ +package com.coderising.ood.ocp.good; + +public class Logger { + + private Formatter formatter; + private Sender sender; + + public Logger(Formatter formatter,Sender sender){ + this.formatter = formatter; + this.sender = sender; + } + public void log(String msg){ + sender.send(formatter.format(msg)) ; + } + + +} + diff --git a/students/996108220/src/com/coderising/ood/ocp/good/RawFormatter.java b/students/996108220/src/com/coderising/ood/ocp/good/RawFormatter.java new file mode 100644 index 0000000000..7f1cb4ae30 --- /dev/null +++ b/students/996108220/src/com/coderising/ood/ocp/good/RawFormatter.java @@ -0,0 +1,11 @@ +package com.coderising.ood.ocp.good; + +public class RawFormatter implements Formatter { + + @Override + public String format(String msg) { + + return null; + } + +} diff --git a/students/996108220/src/com/coderising/ood/ocp/good/Sender.java b/students/996108220/src/com/coderising/ood/ocp/good/Sender.java new file mode 100644 index 0000000000..aaa46c1fb7 --- /dev/null +++ b/students/996108220/src/com/coderising/ood/ocp/good/Sender.java @@ -0,0 +1,7 @@ +package com.coderising.ood.ocp.good; + +public interface Sender { + + void send(String msg); + +} diff --git a/students/996108220/src/com/coderising/ood/srp/Configuration.java b/students/996108220/src/com/coderising/ood/srp/Configuration.java new file mode 100644 index 0000000000..f328c1816a --- /dev/null +++ b/students/996108220/src/com/coderising/ood/srp/Configuration.java @@ -0,0 +1,23 @@ +package com.coderising.ood.srp; +import java.util.HashMap; +import java.util.Map; + +public class Configuration { + + static Map configurations = new HashMap<>(); + static{ + configurations.put(ConfigurationKeys.SMTP_SERVER, "smtp.163.com"); + configurations.put(ConfigurationKeys.ALT_SMTP_SERVER, "smtp1.163.com"); + configurations.put(ConfigurationKeys.EMAIL_ADMIN, "admin@company.com"); + } + /** + * 应该从配置文件读, 但是这里简化为直接从一个map 中去读 + * @param key + * @return + */ + public String getProperty(String key) { + + return configurations.get(key); + } + +} diff --git a/students/996108220/src/com/coderising/ood/srp/ConfigurationKeys.java b/students/996108220/src/com/coderising/ood/srp/ConfigurationKeys.java new file mode 100644 index 0000000000..8695aed644 --- /dev/null +++ b/students/996108220/src/com/coderising/ood/srp/ConfigurationKeys.java @@ -0,0 +1,9 @@ +package com.coderising.ood.srp; + +public class ConfigurationKeys { + + public static final String SMTP_SERVER = "smtp.server"; + public static final String ALT_SMTP_SERVER = "alt.smtp.server"; + public static final String EMAIL_ADMIN = "email.admin"; + +} diff --git a/students/996108220/src/com/coderising/ood/srp/DBUtil.java b/students/996108220/src/com/coderising/ood/srp/DBUtil.java new file mode 100644 index 0000000000..683ce1712e --- /dev/null +++ b/students/996108220/src/com/coderising/ood/srp/DBUtil.java @@ -0,0 +1,38 @@ +package com.coderising.ood.srp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DBUtil { + static ProductUtil productUtil=new ProductUtil(); + /** + * 应该从数据库读, 但是简化为直接生成。 + * @param sql + * @return + */ + public static List query(String sql){ + + List userList = new ArrayList(); + for (int i = 1; i <= 3; i++) { + HashMap userInfo = new HashMap(); + userInfo.put("NAME", "User" + i); + userInfo.put("EMAIL", "aa@bb.com"); + userList.add(userInfo); + } + + return userList; + } + protected static List loadMailingList() throws Exception { + + String sendMailQuery = LoadQuery(); + return DBUtil.query(sendMailQuery); + } + protected static String LoadQuery() throws Exception { + String productID = productUtil.getProductID(); + System.out.println("loadQuery set"); + return "Select name from subscriptions " + + "where product_id= '" + productID +"' " + + "and send_mail=1 "; + + } +} diff --git a/students/996108220/src/com/coderising/ood/srp/MailUtil.java b/students/996108220/src/com/coderising/ood/srp/MailUtil.java new file mode 100644 index 0000000000..38ad395d83 --- /dev/null +++ b/students/996108220/src/com/coderising/ood/srp/MailUtil.java @@ -0,0 +1,74 @@ +package com.coderising.ood.srp; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +public class MailUtil { + + private static Configuration config=new Configuration(); ; + private static ProductUtil productUtil = new ProductUtil(); + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + protected static void sendEmail(String userName,String toAddress,String smtpHost,Boolean debug) throws IOException + { + String subject = "您关注的产品降价了"; + String message = "尊敬的 "+userName+", 您关注的产品 " + productUtil.getProductDesc() + " 降价了,欢迎购买!" ; + String fromAddress=config.getProperty(ConfigurationKeys.EMAIL_ADMIN); + StringBuilder buffer = new StringBuilder(); + buffer.append("From:").append(fromAddress).append("\n"); + buffer.append("To:").append(toAddress).append("\n"); + buffer.append("Subject:").append(subject).append("\n"); + buffer.append("Content:").append(message).append("\n"); + System.out.println(buffer); + } + + + + private static void sendEmail(String userName,String toAddress,Boolean debug) { + try + { + String smtpHost=config.getProperty(ConfigurationKeys.SMTP_SERVER); + sendEmail( userName,toAddress,smtpHost, debug); + } + catch (Exception e) + { + + try { + String altSmtpHost=config.getProperty(ConfigurationKeys.ALT_SMTP_SERVER); + sendEmail( userName,toAddress,altSmtpHost, debug); + + } catch (Exception e2) + { + System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage()); + } + } + } + + protected static void sendEMails(boolean debug,List mailingList) throws IOException + { + + System.out.println("开始发送邮件"); + + + if (mailingList != null) { + Iterator iter = mailingList.iterator(); + while (iter.hasNext()) { + HashMap userInfo = (HashMap)iter.next(); + String userName = userInfo.get(NAME_KEY); + String toAddress = userInfo.get(EMAIL_KEY); + sendEmail( userName, toAddress, debug); + } + } + + else { + System.out.println("没有邮件发送"); + } + + } + + +} diff --git a/students/996108220/src/com/coderising/ood/srp/ProductUtil.java b/students/996108220/src/com/coderising/ood/srp/ProductUtil.java new file mode 100644 index 0000000000..be40fd203c --- /dev/null +++ b/students/996108220/src/com/coderising/ood/srp/ProductUtil.java @@ -0,0 +1,39 @@ +package com.coderising.ood.srp; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +public class ProductUtil { + private String productConfigPath="D:\\JavaCoding\\students\\996108220\\src" + + "\\com\\coderising\\ood\\srp\\product_promotion.txt"; + + private String[] readFile() throws IOException // @02C + { + File file=new File(productConfigPath); + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(file)); + String temp = br.readLine(); + String[] data = temp.split(" ");; + return data; + + } catch (IOException e) { + throw new IOException(e.getMessage()); + } finally { + br.close(); + } + } + + public String getProductID() throws IOException { + String[] data= readFile(); + return data[0]; + } + + public String getProductDesc() throws IOException { + String[] data= readFile(); + return data[1]; + } + +} diff --git a/students/996108220/src/com/coderising/ood/srp/PromotionMail.java b/students/996108220/src/com/coderising/ood/srp/PromotionMail.java new file mode 100644 index 0000000000..2795a54b2a --- /dev/null +++ b/students/996108220/src/com/coderising/ood/srp/PromotionMail.java @@ -0,0 +1,49 @@ + package com.coderising.ood.srp; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +public class PromotionMail { + + //读取用户信息 + + private static final String NAME_KEY = "NAME"; + private static final String EMAIL_KEY = "EMAIL"; + + + public static void main(String[] args) throws Exception { + + boolean emailDebug = false; + PromotionMail pe = new PromotionMail(); + List userInfo = DBUtil.loadMailingList(); + List mailingList = pe.filterUserInfo(userInfo); + MailUtil.sendEMails(emailDebug, mailingList); + } + + + + + protected List filterUserInfo(List userList) throws IOException + { + + if (userList != null) { + Iterator iter = userList.iterator(); + while (iter.hasNext()) { + HashMap userInfo = (HashMap)iter.next(); + String userName = userInfo.get(NAME_KEY); + String toAddress = userInfo.get(EMAIL_KEY); + if (toAddress.length() <= 0) + userInfo.remove(userInfo); + } + } + return userList; + + } + + + + +} diff --git a/students/996108220/src/com/coderising/ood/srp/product_promotion.txt b/students/996108220/src/com/coderising/ood/srp/product_promotion.txt new file mode 100644 index 0000000000..0c0124cc61 --- /dev/null +++ b/students/996108220/src/com/coderising/ood/srp/product_promotion.txt @@ -0,0 +1,4 @@ +P8756 iPhone8 +P3946 XiaoMi10 +P8904 Oppo_R15 +P4955 Vivo_X20 \ No newline at end of file