From c421b0862c56d153d9dd6fe84718e7f82368ed1d Mon Sep 17 00:00:00 2001 From: Lizhy Date: Mon, 20 Mar 2017 21:23:48 +0800 Subject: [PATCH 01/20] =?UTF-8?q?=E6=96=B0=E5=8A=A0=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 并修改一些ArrayUtil方法 --- .../homework/second/array/ArrayUtil.java | 56 ++++++------ .../homework/second/array/ArrayUtilTest.java | 90 +++++++++++++++++++ 2 files changed, 121 insertions(+), 25 deletions(-) create mode 100644 group26/lizhy2017/homework/second/array/ArrayUtilTest.java diff --git a/group26/lizhy2017/homework/second/array/ArrayUtil.java b/group26/lizhy2017/homework/second/array/ArrayUtil.java index 253356ef7d..1e7855bd1b 100644 --- a/group26/lizhy2017/homework/second/array/ArrayUtil.java +++ b/group26/lizhy2017/homework/second/array/ArrayUtil.java @@ -9,14 +9,14 @@ public class ArrayUtil { * 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] * 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] * - * @param origin + * @param origin 整形数组 */ - public void reverseArray(int[] origin) { - if (null != origin) return; - for (int i = 0; i < origin.length; i++) { + public static void reverseArray(int[] origin) { + if (null == origin) return; + for (int i = 0; i < origin.length / 2; i++) { int temp = origin[i]; origin[i] = origin[origin.length - i - 1]; - origin[i] = temp; + origin[origin.length - i - 1] = temp; } } @@ -29,16 +29,18 @@ public void reverseArray(int[] origin) { * @return */ - public int[] removeZero(int[] oldArray) { - if (null != oldArray) { - return null; - } + public static int[] removeZero(int[] oldArray) { + if (null == oldArray) return null; + int size = oldArray.length; for (int i = 0; i < oldArray.length; i++) { if (oldArray[i] == 0) { System.arraycopy(oldArray, i + 1, oldArray, i, oldArray.length - i - 1); + size--; } } - return oldArray; + int[] newArray = new int[size]; + System.arraycopy(oldArray, 0, newArray, 0, size); + return newArray; } /** @@ -50,30 +52,34 @@ public int[] removeZero(int[] oldArray) { * @return */ - public int[] merge(int[] array1, int[] array2) { - if (null != array1 && null != array2) return null; + public static int[] merge(int[] array1, int[] array2) { + if (null == array1 || null == array2) return null; int[] temp = new int[array1.length + array2.length]; int i = 0, j = 0; if (array1.length >= array2.length) { while (i < array2.length) { - i++; if (array1[i] <= array2[i]) temp[i] = array1[i]; else temp[i] = array2[i]; + i++; } - System.arraycopy(array1, i + 1, temp, i + 1, temp.length - i - 1); + System.arraycopy(array1, i - 1, temp, 2 * i - 1, temp.length - 2 * i - 1); } else { - while (j < array1.length) { - j++; - if (array1[j] <= array2[j]) + while (j < array1.length - 1) { + if (array1[j] <= array2[j]) { temp[j] = array1[j]; - else + if (array1[j + 1] > array2[j]) { + temp[j] = array2[j]; + } + } else temp[j] = array2[j]; + j++; + } - System.arraycopy(array1, j + 1, temp, j + 1, temp.length - j - 1); + System.arraycopy(array2, j - 1, temp, 2 * j - 1, temp.length - 2 * j - 1); } - return null; + return temp; } /** @@ -86,7 +92,7 @@ public int[] merge(int[] array1, int[] array2) { * @param size * @return */ - public int[] grow(int[] oldArray, int size) { + public static int[] grow(int[] oldArray, int size) { int oldCapacity = oldArray.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity < size) { @@ -106,7 +112,7 @@ public int[] grow(int[] oldArray, int size) { * @param max * @return */ - public int[] fibonacci(int max) { + public static int[] fibonacci(int max) { if (max <= 1) return new int[0]; int[] temp = new int[max]; @@ -131,7 +137,7 @@ public int[] fibonacci(int max) { * @param max * @return */ -// public int[] getPrimes(int max) { +// public static int[] getPrimes(int max) { // int[] temp = new int[max]; // if (max < 2) // return new int[0]; @@ -165,7 +171,7 @@ public int[] fibonacci(int max) { * @param max * @return */ - public int[] getPerfectNumbers(int max) { + public static int[] getPerfectNumbers(int max) { int[] temp = new int[max]; int index = 0; for (int i = 1; i <= max; i++) { @@ -192,7 +198,7 @@ public int[] getPerfectNumbers(int max) { * @param seperator * @return */ - public String join(int[] array, String seperator) { + public static String join(int[] array, String seperator) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < array.length; i++) { if (i == array.length - 1) { diff --git a/group26/lizhy2017/homework/second/array/ArrayUtilTest.java b/group26/lizhy2017/homework/second/array/ArrayUtilTest.java new file mode 100644 index 0000000000..58827657da --- /dev/null +++ b/group26/lizhy2017/homework/second/array/ArrayUtilTest.java @@ -0,0 +1,90 @@ +package second.array; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * ${} + * Created by spark_lizhy on 2017/3/20. + */ + +public class ArrayUtilTest { + + private int[] temp; + private int size; + + @Before + public void setUp() throws Exception { + size = 10; + temp = new int[size]; + for (int i = 0; i < size; i++) { + temp[i] = i; + } + + } + + @Test + public void reverseArray() throws Exception { + ArrayUtil.reverseArray(temp); + for (int i = 0; i < size; i++) { + Assert.assertEquals(size - 1 - i, temp[i]); + } + } + + @Test + public void removeZero() throws Exception { + for (int i = 0; i < size; i++) { + if (i % 5 == 0) { + temp[i] = 0; + } else { + temp[i] = i; + } + } + + temp = ArrayUtil.removeZero(temp); + Assert.assertNotNull(temp); + for (int i = 0; i < temp.length; i++) { + if (temp[i] != 0) { + continue; + } + Assert.assertEquals(temp[i], i); + } + + // 测试空数组 + { + int[] testArray = new int[5]; + for (int i = 0; i < 5; i++) { + testArray[i] = 0; + } + + int[] newArray = ArrayUtil.removeZero(testArray); + Assert.assertNotNull(newArray); + Assert.assertEquals(newArray.length, 0); + } + } + + @Test + public void merge() throws Exception { + // 构建数组 + int[] array1 = new int[10]; + int[] array2 = new int[11]; + array2[10] = 100; + for (int i = 0; i < 10; i++) { + if (i % 2 == 0) { + array1[i / 2] = i; // 0, 2, 4, 6, 8 + } else { + array2[i / 2] = i; // 1, 3, 5, 7, 9 + } + } + + // 测试merge + { + int[] merge = ArrayUtil.merge(array1, array2); + Assert.assertNotNull(merge); + Assert.assertEquals(merge.length, 21); + } + + } + +} From 23892fb0c02cdefb7ee1484a0b94bd66104c08c0 Mon Sep 17 00:00:00 2001 From: MAC Date: Fri, 24 Mar 2017 20:05:09 +0800 Subject: [PATCH 02/20] upload week03 download commit --- .../source/download/DownloadThread.java | 40 +++++++ .../source/download/FileDownloader.java | 101 ++++++++++++++++++ .../source/download/api/Connection.java | 16 +++ .../download/api/ConnectionException.java | 10 ++ .../download/api/ConnectionManager.java | 10 ++ .../source/download/api/DownloadListener.java | 10 ++ .../source/download/impl/ConnectionImpl.java | 43 ++++++++ .../download/impl/ConnectionManagerImpl.java | 27 +++++ .../src/week03/test/TestDownload.java | 57 ++++++++++ 9 files changed, 314 insertions(+) create mode 100644 group26/89460886/src/week03/source/download/DownloadThread.java create mode 100644 group26/89460886/src/week03/source/download/FileDownloader.java create mode 100644 group26/89460886/src/week03/source/download/api/Connection.java create mode 100644 group26/89460886/src/week03/source/download/api/ConnectionException.java create mode 100644 group26/89460886/src/week03/source/download/api/ConnectionManager.java create mode 100644 group26/89460886/src/week03/source/download/api/DownloadListener.java create mode 100644 group26/89460886/src/week03/source/download/impl/ConnectionImpl.java create mode 100644 group26/89460886/src/week03/source/download/impl/ConnectionManagerImpl.java create mode 100644 group26/89460886/src/week03/test/TestDownload.java diff --git a/group26/89460886/src/week03/source/download/DownloadThread.java b/group26/89460886/src/week03/source/download/DownloadThread.java new file mode 100644 index 0000000000..53d700fb78 --- /dev/null +++ b/group26/89460886/src/week03/source/download/DownloadThread.java @@ -0,0 +1,40 @@ +package coding.coderising.download; + +import coding.coderising.download.api.Connection; + +import java.io.IOException; + +/** + * @author jiaxun + */ +public class DownloadThread extends Thread{ + + private Connection connection; + private int startPos; + private int endPos; + private byte[] downloadByte; + + public DownloadThread(Connection connection, int startPos, int endPos) { + this.connection = connection; + this.startPos = startPos; + this.endPos = endPos; + } + + @Override + public void run() { + try { + downloadByte = connection.read(startPos, endPos); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public byte[] getDownloadByte() { + return downloadByte; + } + + public int getStartPos() { + return startPos; + } + +} diff --git a/group26/89460886/src/week03/source/download/FileDownloader.java b/group26/89460886/src/week03/source/download/FileDownloader.java new file mode 100644 index 0000000000..6398a1db19 --- /dev/null +++ b/group26/89460886/src/week03/source/download/FileDownloader.java @@ -0,0 +1,101 @@ +package coding.coderising.download; + +import coding.coderising.download.api.Connection; +import coding.coderising.download.api.ConnectionManager; +import coding.coderising.download.api.DownloadListener; + +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.util.ArrayList; +import java.util.List; + +/** + * @author jiaxun + */ +public class FileDownloader { + + private static final int THREAD_COUNT = 3; + + private int threadCount; + private String downloadUrl; + private DownloadListener downloadListener; + private ConnectionManager connectionManager; + private String savePath; + + public FileDownloader(String downloadUrl, String savePath) { + this.downloadUrl = downloadUrl; + this.savePath = savePath; + this.threadCount = THREAD_COUNT; + } + + public void execute() { + Connection connection = null; + RandomAccessFile out = null; + try { + connection = connectionManager.open(downloadUrl); + int length = connection.getContentLength(); + connection.close(); + + int downloadOffset = 0; + List threadList = new ArrayList<>(); + for (int i = 0; i < threadCount; i++) { + DownloadThread thread = new DownloadThread(connectionManager.open(downloadUrl), downloadOffset, downloadOffset + (i + 1) * (length / threadCount)); + threadList.add(thread); + thread.start(); + downloadOffset = (i + 1) * (length / threadCount) + 1; + } + if (downloadOffset < length) { + DownloadThread thread = new DownloadThread(connectionManager.open(downloadUrl), downloadOffset, length - 1); + threadList.add(thread); + thread.start(); + } + + for (DownloadThread thread : threadList) { + thread.join(); + } + + File file = new File(savePath); + out = new RandomAccessFile(file, "rwd"); + for (DownloadThread thread : threadList) { + out.seek(thread.getStartPos()); + out.write(thread.getDownloadByte()); + } + + if (downloadListener != null) { + downloadListener.notifyFinished(); + } + + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (connection != null) { + connection.close(); + } + try { + if (out != null) { + out.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public void setConnectionManager(ConnectionManager connectionManager) { + this.connectionManager = connectionManager; + } + + public void setDownloadListener(DownloadListener downloadListener) { + this.downloadListener = downloadListener; + } + + public DownloadListener getDownloadListener() { + return this.downloadListener; + } + + public void setThreadCount(int threadCount) { + this.threadCount = threadCount; + } + +} diff --git a/group26/89460886/src/week03/source/download/api/Connection.java b/group26/89460886/src/week03/source/download/api/Connection.java new file mode 100644 index 0000000000..faa1ca0b8c --- /dev/null +++ b/group26/89460886/src/week03/source/download/api/Connection.java @@ -0,0 +1,16 @@ +package coding.coderising.download.api; + +import java.io.IOException; + +/** + * @author jiaxun + */ +public interface Connection { + + byte[] read(int startPos, int endPos) throws IOException; + + int getContentLength(); + + void close(); + +} diff --git a/group26/89460886/src/week03/source/download/api/ConnectionException.java b/group26/89460886/src/week03/source/download/api/ConnectionException.java new file mode 100644 index 0000000000..c4b62c8ddf --- /dev/null +++ b/group26/89460886/src/week03/source/download/api/ConnectionException.java @@ -0,0 +1,10 @@ +package coding.coderising.download.api; + +/** + * @author jiaxun + */ +public class ConnectionException extends Exception { + + + +} diff --git a/group26/89460886/src/week03/source/download/api/ConnectionManager.java b/group26/89460886/src/week03/source/download/api/ConnectionManager.java new file mode 100644 index 0000000000..9e5bec4564 --- /dev/null +++ b/group26/89460886/src/week03/source/download/api/ConnectionManager.java @@ -0,0 +1,10 @@ +package coding.coderising.download.api; + +/** + * @author jiaxun + */ +public interface ConnectionManager { + + Connection open(String url) throws ConnectionException; + +} diff --git a/group26/89460886/src/week03/source/download/api/DownloadListener.java b/group26/89460886/src/week03/source/download/api/DownloadListener.java new file mode 100644 index 0000000000..be45f69dde --- /dev/null +++ b/group26/89460886/src/week03/source/download/api/DownloadListener.java @@ -0,0 +1,10 @@ +package coding.coderising.download.api; + +/** + * @author jiaxun + */ +public interface DownloadListener { + + void notifyFinished(); + +} diff --git a/group26/89460886/src/week03/source/download/impl/ConnectionImpl.java b/group26/89460886/src/week03/source/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..fa07be7cf4 --- /dev/null +++ b/group26/89460886/src/week03/source/download/impl/ConnectionImpl.java @@ -0,0 +1,43 @@ +package coding.coderising.download.impl; + +import coding.coderising.download.api.Connection; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; + +/** + * @author jiaxun + */ +public class ConnectionImpl implements Connection { + + private HttpURLConnection urlConnection; + + public ConnectionImpl(HttpURLConnection urlConnection) { + this.urlConnection = urlConnection; + } + + @Override + public byte[] read(int startPos, int endPos) throws IOException { + urlConnection.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos); + InputStream input = urlConnection.getInputStream(); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + int length; + byte[] byteArray = new byte[1024]; + while ((length = input.read(byteArray)) != -1) { + output.write(byteArray, 0, length); + } + return output.toByteArray(); + } + + @Override + public int getContentLength() { + return urlConnection.getContentLength(); + } + + @Override + public void close() { + urlConnection.disconnect(); + } +} diff --git a/group26/89460886/src/week03/source/download/impl/ConnectionManagerImpl.java b/group26/89460886/src/week03/source/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..569afb0cb3 --- /dev/null +++ b/group26/89460886/src/week03/source/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,27 @@ +package coding.coderising.download.impl; + +import coding.coderising.download.api.Connection; +import coding.coderising.download.api.ConnectionException; +import coding.coderising.download.api.ConnectionManager; + +import java.net.HttpURLConnection; +import java.net.URL; + +/** + * @author jiaxun + */ +public class ConnectionManagerImpl implements ConnectionManager { + + @Override + public Connection open(String urlString) throws ConnectionException { + + try { + URL url = new URL(urlString); + return new ConnectionImpl((HttpURLConnection) url.openConnection()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + +} diff --git a/group26/89460886/src/week03/test/TestDownload.java b/group26/89460886/src/week03/test/TestDownload.java new file mode 100644 index 0000000000..7bfcb8e589 --- /dev/null +++ b/group26/89460886/src/week03/test/TestDownload.java @@ -0,0 +1,57 @@ +package coding.coderising.download; + +import coding.coderising.download.api.ConnectionManager; +import coding.coderising.download.api.DownloadListener; +import coding.coderising.download.impl.ConnectionManagerImpl; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** + * @author jiaxun + */ +public class TestDownload { + + private static boolean downloaderFinished = false; + + @Before + public void setUp() { + + } + + @After + public void tearDown() { + + } + + @Test + public void testDownload() { + String downloadUrl = "http://img.ithome.com/newsuploadfiles/2017/3/20170324_152202_144.jpg"; + String savePath = "/Users/jiaxun/Downloads/download_thread.jpg"; + + FileDownloader downloader = new FileDownloader(downloadUrl, savePath); + + ConnectionManager connectionManager = new ConnectionManagerImpl(); + downloader.setConnectionManager(connectionManager); + + downloader.setDownloadListener(new DownloadListener() { + @Override + public void notifyFinished() { + downloaderFinished = true; + } + }); + + downloader.execute(); + + while (!downloaderFinished) { + try { + System.out.println("还没有下载完成,休眠五秒"); + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + System.out.println("下载完成!"); + } + +} From 7518a62dc270a8ae3bf866257f5c7b85c395861b Mon Sep 17 00:00:00 2001 From: MAC Date: Sat, 25 Mar 2017 15:46:23 +0800 Subject: [PATCH 03/20] supple LinkedList commit --- .../source/linkedlist/SinglyLinkedList.java | 357 ++++++++++++++++++ .../src/week03/test/TestSinglyLinkedList.java | 156 ++++++++ 2 files changed, 513 insertions(+) create mode 100644 group26/89460886/src/week03/source/linkedlist/SinglyLinkedList.java create mode 100644 group26/89460886/src/week03/test/TestSinglyLinkedList.java diff --git a/group26/89460886/src/week03/source/linkedlist/SinglyLinkedList.java b/group26/89460886/src/week03/source/linkedlist/SinglyLinkedList.java new file mode 100644 index 0000000000..a35cbfa944 --- /dev/null +++ b/group26/89460886/src/week03/source/linkedlist/SinglyLinkedList.java @@ -0,0 +1,357 @@ +package list; + +/** + * @author jiaxun + */ +public class SinglyLinkedList implements List { + + private Node head; + private int size; + + public SinglyLinkedList() { + size = 0; + } + + public void addFirst(Object data) { + Node node = new Node(data); + node.setNext(head); + head = node; + size++; + } + + public Node removeFirst() { + Node object = head; + head = object.getNext(); + size--; + return object; + } + + public Node removeLast() { + Node curr = head; + Node prev = null; + while (curr != null) { + prev = curr; + curr = curr.getNext(); + } + if (prev != null) { + prev.setNext(null); + } + size--; + return curr; + } + + public Node get(int index) { + if (index > size) { + throw new IndexOutOfBoundsException(); + } + Node curr = head; + while (curr != null) { + if (index == 0) + break; + curr = curr.getNext(); + index--; + + } + return curr; + } + + public Node remove(int index) { + Node curr = head; + Node prev = null; + while (curr != null) { + if (index == 0) + break; + prev = curr; + curr = curr.getNext(); + index--; + } + if (prev != null) { + prev.setNext(curr.getNext()); + curr.setNext(null); + } + size--; + return curr; + } + + public void addLast(Object object) { + if (head == null) { + head = new Node(object); + } else { + Node curr = head; + Node prev = null; + while (curr != null) { + prev = curr; + curr = curr.getNext(); + } + prev.setNext(new Node(object)); + } + size++; + } + + @Override + public void add(Object o) { + addLast(o); + } + + public void add(int index, Object object) { + Node curr = head; + Node prev = null; + while (curr != null) { + if (index == 0) + break; + prev = curr; + curr = curr.getNext(); + index--; + } + if (prev != null) { + Node newNode = new Node(object); + newNode.setNext(curr); + prev.setNext(newNode); + size++; + } + } + + public int size() { + return size; + } + + public Iterator iterator() { + return new SinglyLinkedListIterator(this); + } + + public void reverse() { + if (head == null || head.getNext() == null) return; + Node prev = null; + Node next = null; + Node curr = head; + while (curr != null) { + next = curr.getNext(); + curr.setNext(prev); + prev = curr; + curr = next; + } + head = prev; + } + + public void removeFirstHalf() { + if (head == null) return; + int half = size / 2; + Node curr = head; + while (half != 0) { + curr = curr.getNext(); + half--; + } + head = curr; + } + + public void remove(int i, int length) { + if (head == null || length == 0 || i >= size) return; + if (i + length >= size) length = size - i - 1; + Node prev = head; + Node curr = head; + int firstPos = i; + while (curr != null) { + if (firstPos == 0) + break; + prev = curr; + curr = curr.getNext(); + firstPos--; + } + int lastPos = length - i; + while (curr != null) { + if (lastPos == 0) + break; + curr = curr.getNext(); + lastPos--; + } + prev.setNext(curr == null ? null : curr.getNext()); + } + + public int[] getElements(SinglyLinkedList list) { + if (list == null || list.size() == 0) return null; + int[] resultList = new int[list.size()]; + int offset = 0; + int count = 0; + Node curr = head; + for (int i = 0, len = list.size(); i < len; i++) { + int index = (int) list.get(i).getData(); + index = index - offset; + offset = (int) list.get(i).getData(); + while (curr != null) { + if (index == 0) { + resultList[count++] = (int) curr.getData(); + break; + } + curr = curr.getNext(); + index--; + } + } + return resultList; + } + + public void subtract(SinglyLinkedList list) { + if (head == null || list == null) return; + Node curr = head; + Node prev = null; + int bCount = 0; + while (curr != null) { + if (bCount == list.size()) break; + int currData = (int) curr.getData(); + int bData = (int) list.get(bCount).getData(); + if (currData == bData) { + if (prev != null) { + prev.setNext(curr.getNext()); + } else { + head = curr.getNext(); + } + bCount++; + } else { + prev = curr; + } + curr = curr.getNext(); + } + } + + public void removeDuplicateValues() { + if (size <= 1) return; + Node prev = head; + Node curr = head.getNext(); + while (curr != null) { + if (prev.getData().equals(curr.getData())) { + if (curr.getNext() != null) { + curr = curr.getNext(); + } else { + curr = curr.getNext(); + prev.setNext(null); + } + } else { + prev.setNext(curr); + prev = curr; + curr = curr.getNext(); + } + } + } + + public void removeRange(int min, int max) { + if (head == null || (int) head.getData() > max) return; + Node prev = null; + Node next = null; + Node curr = head; + boolean lessHead = false; + if ((int) head.getData() > min) { + prev = head; + lessHead = true; + } + while (curr != null) { + int data = (int) curr.getData(); + if (!lessHead && data < min) { + prev = curr; + } + if (data > max) { + next = curr; + } + curr = curr.getNext(); + } + if (prev != null) { + if (prev == head && lessHead) { + head = next; + } else { + prev.setNext(next); + } + } + } + + public SinglyLinkedList intersection(SinglyLinkedList list) { + SinglyLinkedList resultList = new SinglyLinkedList(); + Node aCurr = head; + Node bCurr = list.head; + while (aCurr != null && bCurr != null) { + int a = (int) aCurr.getData(); + int b = (int) bCurr.getData(); + if (a < b) { + resultList.add(aCurr.getData()); + aCurr = aCurr.getNext(); + } else if (a > b) { + resultList.add(bCurr.getData()); + bCurr = bCurr.getNext(); + } else { + resultList.add(aCurr.getData()); + aCurr = aCurr.getNext(); + bCurr = bCurr.getNext(); + } + } + while (aCurr != null) { + resultList.add(aCurr.getData()); + aCurr = aCurr.getNext(); + } + while (bCurr != null) { + resultList.add(bCurr.getData()); + bCurr = bCurr.getNext(); + } + return resultList; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + Node current = head; + while (current != null) { + builder.append(current.toString()); + current = current.getNext(); + } + return builder.toString(); + } + + private class SinglyLinkedListIterator implements Iterator { + + private SinglyLinkedList linkedList; + private int currentPosition = 0; + + public SinglyLinkedListIterator(SinglyLinkedList linkedList) { + this.linkedList = linkedList; + } + + @Override + public boolean hasNext() { + return currentPosition < size; + } + + @Override + public Object next() { + return linkedList.get(currentPosition++); + } + + @Override + public Object remove() { + return linkedList.remove(--currentPosition); + } + } + + public static class Node { + + private Object data; + private Node next; + + public Node(Object data) { + this.data = data; + } + + public Object getData() { + return data; + } + + public Node getNext() { + return next; + } + + public void setNext(Node next) { + this.next = next; + } + + @Override + public String toString() { + return "[data is " + getData() + "]"; + } + } + +} diff --git a/group26/89460886/src/week03/test/TestSinglyLinkedList.java b/group26/89460886/src/week03/test/TestSinglyLinkedList.java new file mode 100644 index 0000000000..8ae36aed9a --- /dev/null +++ b/group26/89460886/src/week03/test/TestSinglyLinkedList.java @@ -0,0 +1,156 @@ +package list; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * @author jiaxun + */ +public class TestSinglyLinkedList { + + SinglyLinkedList singlyLinkedList; + + @Before + public void setUp() { + singlyLinkedList = new SinglyLinkedList(); + } + + @After + public void tearDown() { + + } + + @Test + public void testReverse() { + singlyLinkedList.add(3); + singlyLinkedList.add(7); + singlyLinkedList.add(10); + singlyLinkedList.reverse(); + int[] resultList = {10, 7, 3}; + for (int i = 0, len = resultList.length; i < len; i++) { + Assert.assertEquals(resultList[i], singlyLinkedList.get(i).getData()); + } + } + + @Test + public void testRemoveFirstHalf() { + singlyLinkedList.add(2); + singlyLinkedList.add(5); + singlyLinkedList.add(7); + singlyLinkedList.add(8); + singlyLinkedList.add(10); + singlyLinkedList.removeFirstHalf(); + int[] resultList = {7, 8, 10}; + for (int i = 0, len = resultList.length; i < len; i++) { + Assert.assertEquals(resultList[i], singlyLinkedList.get(i).getData()); + } + } + + @Test + public void testRemove() { + singlyLinkedList.add(1); + singlyLinkedList.add(2); + singlyLinkedList.add(3); + singlyLinkedList.add(4); + int[] resultList = {1, 3, 4}; + singlyLinkedList.remove(1, 1); + for (int i = 0, len = resultList.length; i < len; i++) { + Assert.assertEquals(singlyLinkedList.get(i).getData(), resultList[i]); + } + } + + @Test + public void testGetElements() { + singlyLinkedList.add(11); + singlyLinkedList.add(101); + singlyLinkedList.add(201); + singlyLinkedList.add(301); + singlyLinkedList.add(401); + singlyLinkedList.add(501); + singlyLinkedList.add(601); + singlyLinkedList.add(701); + SinglyLinkedList listB = new SinglyLinkedList(); + listB.add(1); + listB.add(3); + listB.add(4); + listB.add(6); + int[] expectedArray = {101, 301, 401, 601}; + int[] resultArray = singlyLinkedList.getElements(listB); + for (int i = 0, len = expectedArray.length; i < len; i++) { + Assert.assertEquals(expectedArray[i], resultArray[i]); + } + } + + @Test + public void testSubtract() { + singlyLinkedList.add(11); + singlyLinkedList.add(101); + singlyLinkedList.add(201); + singlyLinkedList.add(301); + singlyLinkedList.add(401); + singlyLinkedList.add(501); + singlyLinkedList.add(601); + singlyLinkedList.add(701); + SinglyLinkedList listB = new SinglyLinkedList(); + listB.add(101); + listB.add(301); + listB.add(401); + listB.add(601); + singlyLinkedList.subtract(listB); + int[] expectedArray = {11, 201, 501, 701}; + for (int i = 0, len = expectedArray.length; i < len; i++) { + Assert.assertEquals(expectedArray[i], singlyLinkedList.get(i).getData()); + } + } + + @Test + public void testRemoveDuplicateValues() { + singlyLinkedList.add(11); + singlyLinkedList.add(101); + singlyLinkedList.add(201); + singlyLinkedList.add(201); + singlyLinkedList.add(301); + singlyLinkedList.add(301); + singlyLinkedList.add(301); + singlyLinkedList.removeDuplicateValues(); + int[] expectedArray = {11, 101, 201, 301}; + for (int i = 0, len = expectedArray.length; i < len; i++) { + Assert.assertEquals(expectedArray[i], singlyLinkedList.get(i).getData()); + } + } + + @Test + public void testRemoveRange() { + singlyLinkedList.add(11); + singlyLinkedList.add(101); + singlyLinkedList.add(201); + singlyLinkedList.add(301); + singlyLinkedList.add(401); + singlyLinkedList.removeRange(10, 400); + int[] expectedArray = {401}; + for (int i = 0, len = expectedArray.length; i < len; i++) { + Assert.assertEquals(expectedArray[i], singlyLinkedList.get(i).getData()); + } + } + + @Test + public void testIntersection() { + singlyLinkedList.add(12); + singlyLinkedList.add(18); + singlyLinkedList.add(32); + singlyLinkedList.add(98); + SinglyLinkedList bList = new SinglyLinkedList(); + bList.add(34); + bList.add(51); + bList.add(53); + bList.add(78); + SinglyLinkedList resultList = singlyLinkedList.intersection(bList); + int[] expectedArray = {12, 18, 32, 34, 51, 53, 78, 98}; + for (int i = 0, len = expectedArray.length; i < len; i++) { + Assert.assertEquals(expectedArray[i], resultList.get(i).getData()); + } + } + +} From ca4a1ed438cf6a9b86fefbb599f2ac554db2cea7 Mon Sep 17 00:00:00 2001 From: zhunan Date: Mon, 27 Mar 2017 11:58:21 +0800 Subject: [PATCH 04/20] zndbl --- .../week1/collection/MyArrayList.java | 65 +++++++ .../week1/collection/MyLinkedList.java | 115 ++++++++++++ .../2441547139/week1/collection/MyQueue.java | 29 +++ .../2441547139/week1/collection/MyStack.java | 29 +++ .../week2/arrayutil/ArrayUtils.java | 172 ++++++++++++++++++ .../2441547139/week2/struts/LoginAction.java | 39 ++++ .../week2/struts/LoginOutAction.java | 5 + group26/2441547139/week2/struts/Struts.java | 74 ++++++++ group26/2441547139/week2/struts/View.java | 23 +++ group26/2441547139/week2/struts/struts.xml | 8 + group26/2441547139/week3/DownloadThread.java | 63 +++++++ group26/2441547139/week3/FileDownload.java | 53 ++++++ group26/2441547139/week3/ThreadDownload.java | 37 ++++ 13 files changed, 712 insertions(+) create mode 100644 group26/2441547139/week1/collection/MyArrayList.java create mode 100644 group26/2441547139/week1/collection/MyLinkedList.java create mode 100644 group26/2441547139/week1/collection/MyQueue.java create mode 100644 group26/2441547139/week1/collection/MyStack.java create mode 100644 group26/2441547139/week2/arrayutil/ArrayUtils.java create mode 100644 group26/2441547139/week2/struts/LoginAction.java create mode 100644 group26/2441547139/week2/struts/LoginOutAction.java create mode 100644 group26/2441547139/week2/struts/Struts.java create mode 100644 group26/2441547139/week2/struts/View.java create mode 100644 group26/2441547139/week2/struts/struts.xml create mode 100644 group26/2441547139/week3/DownloadThread.java create mode 100644 group26/2441547139/week3/FileDownload.java create mode 100644 group26/2441547139/week3/ThreadDownload.java diff --git a/group26/2441547139/week1/collection/MyArrayList.java b/group26/2441547139/week1/collection/MyArrayList.java new file mode 100644 index 0000000000..979ee23d8c --- /dev/null +++ b/group26/2441547139/week1/collection/MyArrayList.java @@ -0,0 +1,65 @@ +package week1.collection; + +import java.util.Arrays; +/** + * Created by zndbl on 2017/3/11. + */ +public class MyArrayList { + + private int size; + private Object[] arr; + + public MyArrayList() { + this(10); + } + + public MyArrayList(int oldLength) { + if(oldLength < 0) { + throw new RuntimeException("创建集合失败"); + } + arr = new Object[oldLength]; + } + + public int size() { + return size; + } + + /** + * 数组的长度扩充策略 + */ + public void ensureCapacity(int minCapatity ) { + int oldCapacity = arr.length; + if(minCapatity > oldCapacity) { + int newCapatity = 3 * oldCapacity / 2 + 1; + if(minCapatity > newCapatity) { + newCapatity = minCapatity; + } + arr = Arrays.copyOf(arr,newCapatity); + } + } + + public void add(Object element) { + ensureCapacity(size+1); + arr[size++] = element; + } + + public void add(int index, Object element) { + if(index < 0 || index > size) { + throw new RuntimeException("数组越界"); + } + ensureCapacity(size+1); + System.arraycopy(arr,index,arr,index+1,size-index); + arr[index] = element; + size++; + } + + public boolean remove(Object o) { + for(int i=0; i index ; i--) { + cussor = cussor.prev; + } + return cussor; + } + } + + public Object get(int index) { + checkRange(index); + return node(index).item; + } + + public void checkRange(int index) { + if(index >= size || index < 0) { + throw new RuntimeException("index超过界限"); + } + } + + public int indexOf(Object element) { + Node cussor = first; + int count = 0; + while (cussor != null) { + if(element.equals(cussor.item)) { + return count; + } + count++; + cussor = cussor.next; + } + return -1; + } + + public boolean remove(Object o) { + int index = indexOf(o); + if(index < 0) { + return false; + } + deleteLink(index); + return true; + } + + public Object deleteLink(int index) { + Node l = node(index); + Object item = l.item; + Node prevNode = l.prev; + Node nextNode = l.next; + + if(prevNode == null) { + first = nextNode; + } else { + prevNode.next = nextNode; + l.next = null; + } + if(nextNode == null) { + last = prevNode; + } else { + nextNode.prev = prevNode; + l.prev = null; + } + size--; + l.item = null; + return item; + + } + + +} diff --git a/group26/2441547139/week1/collection/MyQueue.java b/group26/2441547139/week1/collection/MyQueue.java new file mode 100644 index 0000000000..2721b305a7 --- /dev/null +++ b/group26/2441547139/week1/collection/MyQueue.java @@ -0,0 +1,29 @@ +package week1.collection; + +/** + * Created by zndbl on 2017/3/12. + */ +public class MyQueue { + + private Object[] data; + private int head; + private int tail; + + public MyQueue() { + data = new Object[10]; + head = 1; + tail = 1; + } + + public void put(Object obj) { + data[tail] = obj; + tail++; + } + + public Object get() { + Object obj = data[head]; + head++; + return obj; + } + +} diff --git a/group26/2441547139/week1/collection/MyStack.java b/group26/2441547139/week1/collection/MyStack.java new file mode 100644 index 0000000000..1b2b8c5d2c --- /dev/null +++ b/group26/2441547139/week1/collection/MyStack.java @@ -0,0 +1,29 @@ +package week1.collection; + +/** + * Created by zndbl on 2017/3/12. + */ +public class MyStack { + + private Object[] data; + private int top; + + public MyStack() { + data = new Object[100]; + top = -1; + } + + public void put(Object t) { + data[data.length] = t; + top++; + } + + public Object pop() { + if(top < 0) { + return null; + } + Object object = data[top]; + top--; + return object; + } +} diff --git a/group26/2441547139/week2/arrayutil/ArrayUtils.java b/group26/2441547139/week2/arrayutil/ArrayUtils.java new file mode 100644 index 0000000000..5bb9f6582f --- /dev/null +++ b/group26/2441547139/week2/arrayutil/ArrayUtils.java @@ -0,0 +1,172 @@ +package week2.arrayutil; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Created by zndbl on 2017/3/23. + */ +public class ArrayUtils { + + public static void main(String[] args) { +// int[] oldArray = new int[]{4,6,2,1,0,5,0,8}; +// int[] newArray = reverseArray(oldArray); +// int[] newArray = removeZero(oldArray); +// String array = "["; +// for(int i = 0 ; i < newArray.length ; i++) { +// array += newArray[i]; +// } +// array += "]"; +// System.out.println(array); +// String s = seperatorArray(oldArray); +// System.out.println(s); +// List math = getAllMath(6); +// int[] array = getPrimeArray(23); +// printArray(array); + getFibonacci(15); + } + + public static void printArray(int[] newArray) { + String array = "["; + for (int i = 0; i < newArray.length; i++) { + array += (newArray[i]+","); + } + array += "]"; + System.out.println(array); + } + + /** + * 数组的反转 + * + * @param oldArray + * @return + */ + public static int[] reverseArray(int[] oldArray) { + int[] newArray = new int[oldArray.length]; + for (int i = 0; i < (oldArray.length); i++) { + newArray[i] = oldArray[oldArray.length - 1 - i]; + } + return newArray; + } + + /** + * 清除数组中的元素0 + * + * @param array + * @return + */ + public static int[] removeZero(int[] array) { + int[] newArray = new int[array.length]; + int j = 0; + for (int i = 0; i < array.length; i++) { + if (array[i] != 0) { + newArray[j++] = array[i]; + } + } + System.out.println(j); + Arrays.copyOf(newArray, j); + return newArray; + } + + /** + * 连接字符 + * + * @param oldArray + * @return + */ + public static String seperatorArray(int[] oldArray) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < oldArray.length; i++) { + if (i == oldArray.length - 1) { + sb.append(oldArray[i]); + break; + } + sb.append(oldArray[i]).append("_"); + } + return sb.toString(); + } + + /** + * 传100,求小于100的所有完数 + * + * @param old + * @return + */ + public static List getAllMath(int old) { + List list = new ArrayList<>(); + int count = 0; + for (int i = 1; i <= old - 1; i++) { + if (old % i == 0) { + System.out.println(i); + count = count + i; + list.add(i); + } + } + if (count == old) { + return list; + } + return new ArrayList(); + } + + /** + * 返回所有小于给定数的素数数组 + * + * @param old + * @return + */ + public static int[] getPrimeArray(int old) { + int[] primeArray = new int[old]; + int k = 0; + for (int i = 1; i < old; i++) { + if (isPrime(i)) { + primeArray[k] = i; + k++; + } + } + return Arrays.copyOf(primeArray, k ); + } + + /** + * 判断一个数是不是素数 + * + * @param i + * @return + */ + public static boolean isPrime(int i) { + int count = 0; + for (int j = 1; j <= i; j++) { + if (i % j == 0) { + count++; + } + } + if (count > 2 || count == 1) { + return false; + } + return true; + } + + /** + * 小于给定数的斐波那契数列 + * 传进去15,1 1 2 3 5 8 13 + * @param old + * @return + */ + public static void getFibonacci(int old) { + int first = 1; + int second = 1; + int num = add(first, second, old); + System.out.println(num); + } + + public static int add(int first, int second, int old) { + int last = first + second; + int before = second; + if(last > old) { + return before; + } + return add(before, last, old); + } + + +} diff --git a/group26/2441547139/week2/struts/LoginAction.java b/group26/2441547139/week2/struts/LoginAction.java new file mode 100644 index 0000000000..b7bf1adc62 --- /dev/null +++ b/group26/2441547139/week2/struts/LoginAction.java @@ -0,0 +1,39 @@ +package week2.struts; + +/** + * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 + * @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/group26/2441547139/week2/struts/LoginOutAction.java b/group26/2441547139/week2/struts/LoginOutAction.java new file mode 100644 index 0000000000..450d158339 --- /dev/null +++ b/group26/2441547139/week2/struts/LoginOutAction.java @@ -0,0 +1,5 @@ +package week2.struts; + +public class LoginOutAction { + +} diff --git a/group26/2441547139/week2/struts/Struts.java b/group26/2441547139/week2/struts/Struts.java new file mode 100644 index 0000000000..ddc5509539 --- /dev/null +++ b/group26/2441547139/week2/struts/Struts.java @@ -0,0 +1,74 @@ +package week2.struts; + + +import org.dom4j.Attribute; +import org.dom4j.Document; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +import java.io.File; +import java.util.List; + +public class Struts { + + public static void main(String[] args) { + runAction(); + } + + public static void runAction() { + + /* + + 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字段中。 + + */ + File file = new File("src/week2/struts/struts.xml"); + SAXReader saxReader = new SAXReader(); + try { + Document document = saxReader.read(file); + Element rootElement = document.getRootElement(); +// List elements = rootElement.elements("action"); +// for (Element element : elements) { +// String aClass = element.attributeValue("class"); +// Class firstClass = Class.forName(aClass); +// Object obj = firstClass.newInstance(); +// Method setName = firstClass.getMethod("setName",String.class); +// Method setPassWord = firstClass.getMethod("setPassword",String.class); +// Method execute = firstClass.getMethod("execute"); +// setName.invoke(obj , "test"); +// setPassWord.invoke(obj , "1234"); +// String result = (String) execute.invoke(obj); +// System.out.println(result); +// } + //根节点的子节点 + List elements = rootElement.elements(); + for(Element element : elements) { + //节点的属性 + List attributes = element.attributes(); + List list = element.elements(); + for(Element e : list) { + if(e.attributeValue("name").equals("success")) { + String jsp = e.getTextTrim(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/group26/2441547139/week2/struts/View.java b/group26/2441547139/week2/struts/View.java new file mode 100644 index 0000000000..2b8c86c49f --- /dev/null +++ b/group26/2441547139/week2/struts/View.java @@ -0,0 +1,23 @@ +package week2.struts; + +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/group26/2441547139/week2/struts/struts.xml b/group26/2441547139/week2/struts/struts.xml new file mode 100644 index 0000000000..5b508e48c8 --- /dev/null +++ b/group26/2441547139/week2/struts/struts.xml @@ -0,0 +1,8 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + \ No newline at end of file diff --git a/group26/2441547139/week3/DownloadThread.java b/group26/2441547139/week3/DownloadThread.java new file mode 100644 index 0000000000..c0d0065021 --- /dev/null +++ b/group26/2441547139/week3/DownloadThread.java @@ -0,0 +1,63 @@ +package week3; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.RandomAccessFile; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.concurrent.CountDownLatch; + +/** + * Created by zndbl on 2017/3/27. + */ +public class DownloadThread extends Thread { + + private File file; + private CountDownLatch countDownLatch; + private String address; + private int startPos; + private int endPos; + + public DownloadThread(File file, CountDownLatch countDownLatch, String address, int startPos, int endPos ) { + this.file = file; + this.countDownLatch = countDownLatch; + this.address = address; + this.startPos = startPos; + this.endPos = endPos; + } + + public void run() { + Thread current = Thread.currentThread(); + System.out.println(current.getName() + "开始下载" + startPos + "_" + endPos); + RandomAccessFile randomAccessFile = null; + InputStream inputStream = null; + try { + URL url = new URL(address); + HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); + httpURLConnection.setRequestProperty("Range", "bytes=" + startPos + "_" + endPos); + inputStream = httpURLConnection.getInputStream(); + randomAccessFile = new RandomAccessFile(file, "rw"); + randomAccessFile.seek(startPos); + byte[] bytes = new byte[1024]; + int length = 0; + while ((length = inputStream.read(bytes)) != -1) { + randomAccessFile.write(bytes, 0, length); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + randomAccessFile.close(); + inputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println(current.getName() + "下载完成"); + countDownLatch.countDown(); + } + + } + + +} diff --git a/group26/2441547139/week3/FileDownload.java b/group26/2441547139/week3/FileDownload.java new file mode 100644 index 0000000000..7cd939a753 --- /dev/null +++ b/group26/2441547139/week3/FileDownload.java @@ -0,0 +1,53 @@ +package week3; + +import java.io.File; +import java.io.RandomAccessFile; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.concurrent.CountDownLatch; + +/** + * Created by zndbl on 2017/3/27. + */ +public class FileDownload { + + private String address; + + public FileDownload(String address) { + this.address = address; + } + + public void download(int threadCount) { + try { + URL url = new URL(address); + HttpURLConnection HttpurlConnection = (HttpURLConnection) url.openConnection(); + int length = HttpurlConnection.getContentLength(); + System.out.println("文件大小"+length); + File file = new File("D:\\download.jpg"); + RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); + randomAccessFile.setLength(length); + randomAccessFile.close(); + CountDownLatch countDownLatch = new CountDownLatch(threadCount); + int blockSize = length / threadCount; + for (int i = 0; i < threadCount ; i++) { + int startPos = blockSize * i; + int endPos = blockSize * (i + 1); + if(i == threadCount - 1) { + endPos = length; + } + new DownloadThread(file, countDownLatch, address, startPos, endPos - 1).start(); + } + while (countDownLatch.getCount() != 0) { + System.out.println("下载中"); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + System.out.println("下载完成"); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/group26/2441547139/week3/ThreadDownload.java b/group26/2441547139/week3/ThreadDownload.java new file mode 100644 index 0000000000..c760844225 --- /dev/null +++ b/group26/2441547139/week3/ThreadDownload.java @@ -0,0 +1,37 @@ +package week3; + +/** + * Created by zndbl on 2017/3/26. + */ +public class ThreadDownload { + + public static void main(String[] args) { +// //单线程下载 +// try { +// String url = "http://img.alicdn.com/bao/uploaded/i2/412712826/TB2eNIZXXYC11BjSspfXXXcPFXa_!!412712826.jpg_240x240.jpg"; +// HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); +// conn.setRequestMethod("GET"); +// conn.setReadTimeout(5000); +// conn.setConnectTimeout(5000); +// InputStream in = conn.getInputStream(); +// BufferedInputStream bufferedInputStream = new BufferedInputStream(in); +// File file = new File("D:/a.jpg"); +// BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file)); +// byte[] buffer = new byte[1024]; +// int len = -1; +// while ((len = bufferedInputStream.read(buffer)) != -1) { +// bufferedOutputStream.write(buffer, 0, len); +// bufferedOutputStream.flush(); +// } +// } catch (Exception e) { +// e.printStackTrace(); +// } + + //多线程部分参考网上的 + String url = "http://wx.qlogo.cn/mmopen/fqCl7qHPjf2JaKGXwqRe3WoMwnBouoSNG2Xd3kYAcfLEmibXEpZH9HVDyDiassfPgiav8kx9wNDypGxaibxdQFIXzIhib2N2ibuo07/0"; + FileDownload fileDownload = new FileDownload(url); + fileDownload.download(3); + + + } +} From 36f0af91248033a989bd4ba0863e3335df487f6a Mon Sep 17 00:00:00 2001 From: ajie9608 <1778842360@qq.com> Date: Mon, 27 Mar 2017 20:41:44 +0800 Subject: [PATCH 05/20] Signed-off-by: ajie9608 <1778842360@qq.com> --- .../third homework/LinkedList/LinkedList.java | 518 ++++++++++++++++++ .../LinkedList/LinkedListTest.java | 192 +++++++ .../third homework/TTD/ConfigurationTest.java | 41 ++ .../third homework/TTD/Configureation.java | 99 ++++ .../third homework/TTD/LoginAction.java | 42 ++ .../third homework/TTD/ReflectionUtil.java | 76 +++ .../TTD/ReflectionUtilTest.java | 108 ++++ .../1778842360/third homework/TTD/Struts.java | 56 ++ .../1778842360/third homework/TTD/View.java | 27 + 9 files changed, 1159 insertions(+) create mode 100644 group26/1778842360/third homework/LinkedList/LinkedList.java create mode 100644 group26/1778842360/third homework/LinkedList/LinkedListTest.java create mode 100644 group26/1778842360/third homework/TTD/ConfigurationTest.java create mode 100644 group26/1778842360/third homework/TTD/Configureation.java create mode 100644 group26/1778842360/third homework/TTD/LoginAction.java create mode 100644 group26/1778842360/third homework/TTD/ReflectionUtil.java create mode 100644 group26/1778842360/third homework/TTD/ReflectionUtilTest.java create mode 100644 group26/1778842360/third homework/TTD/Struts.java create mode 100644 group26/1778842360/third homework/TTD/View.java diff --git a/group26/1778842360/third homework/LinkedList/LinkedList.java b/group26/1778842360/third homework/LinkedList/LinkedList.java new file mode 100644 index 0000000000..89c5a87aed --- /dev/null +++ b/group26/1778842360/third homework/LinkedList/LinkedList.java @@ -0,0 +1,518 @@ +package first; + +import java.util.Stack; + + +public class LinkedList implements List { + + private Node head; + int size; + public LinkedList() + { + size=0; + head=null; + } + public void add(Object o){ + if(head==null) + { + head=new Node(o); + head.next=null; + head.data=o; + } + else{ + Node p=head; + { + while(p.next!=null) + { + p=p.next; + } + Node n=new Node(o); + p.next=n; + n.data=o; + n.next=null; + } + } + size++; + } + public void add(int index , Object o){ + int i=1; + Node p=head; + while(iindex) {return null;} + return p.data; + } + public Object remove(int index){ + int i=1; + Node p=head; + Object o=null; + if(index==1) + { + o=head.data; + if(head.next!=null) + { + p=head.next; + head.data=p.data; + p=head; + } + else{ + head=null; + } + } + else{ + while(i7->10 , 逆置后变为 10->7->3 + */ + public void reverse() + { + if(head==null||null==head.next) + { + return; + } + Stack s=new Stack(); + Node currentNode=head; + while(currentNode!=null) + { + s.push(currentNode); + Node nextNode=currentNode.next; + currentNode.next=null; //把链表断开 + currentNode=nextNode; + } + head=s.pop(); + currentNode=head; + while(!s.isEmpty()) + { + Node nextNode=s.pop(); + currentNode.next=nextNode; + currentNode=nextNode; + } + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + */ + public void removeFirstHalf(){ + int length=size/2; + Node p=head; + for(int i=0;isize-1-i) return; + if(i==0) + { + removeFirst(); + for(i=1;i<=length-1;i++) + { + removeFirst(); + } + } + else{ + int j=0; + Node p=head; + while(j101->201->301->401->501->601->701 + * listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + * @param list + */ + public int[] getElements(LinkedList list){ + if(this.size<1) return null; + if((int)(list.get(list.size))>this.size) return null; + //将链表转为数组 + int[] listToArray=new int[this.size]; + Node n=head; + for(int i=0;i actions=new HashMap<>(); + + public Configureation(String fileName) + { + String packageName=this.getClass().getPackage().getName(); + packageName=packageName.replace('.', '/'); + InputStream is=this.getClass().getResourceAsStream("/"+packageName+"/"+fileName); + parseXML(is); + + try{ + is.close(); + } + catch(IOException e){ + e.printStackTrace(); + } + } + + private void parseXML(InputStream is) { + + SAXBuilder builder=new SAXBuilder(); + + try{ + Document doc=builder.build(is); + Element root =doc.getRootElement(); + for(Element actionElement :root.getChildren("action")) + { + String actionName=actionElement.getAttributeValue("name"); + String clzName=actionElement.getAttributeValue("class"); + ActionConfig ac=new ActionConfig(actionName,clzName); + for(Element resultElement:actionElement.getChildren()) + { + String resultName=resultElement.getAttributeValue("name"); + String viewName=resultElement.getText().trim(); + + ac.addViewResult(resultName, viewName); + + } + this.actions.put(actionName, ac);//把actionName以及其下面的resultName和viewName构成一个键值对 + } + } + catch(JDOMException e){ + e.printStackTrace(); + } catch(IOException e) + { + e.printStackTrace(); + } + } + + public String getClassName(String action) { + ActionConfig ac=this.actions.get(action); + if(ac==null) + { + return null; + } + return ac.getClassName(); + } + + public String getResultView(String action,String resultName) + { + ActionConfig ac=this.actions.get(action); + if(ac==null){ + return null; + } + return ac.getViewName(resultName); + } + private static class ActionConfig{ + String name; + String clzName; + Map viewResult=new HashMap<>(); + + public ActionConfig(String actionName,String clzName){ + this.name=actionName; + this.clzName=clzName; + } + public String getClassName(){ + return clzName; + } + public void addViewResult(String name,String viewName){ + viewResult.put(name, viewName); + } + public String getViewName(String resultName) + { + return viewResult.get(resultName); + } + } +} diff --git a/group26/1778842360/third homework/TTD/LoginAction.java b/group26/1778842360/third homework/TTD/LoginAction.java new file mode 100644 index 0000000000..e398f0d39a --- /dev/null +++ b/group26/1778842360/third homework/TTD/LoginAction.java @@ -0,0 +1,42 @@ +package com.coderising.litestruts; + +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 you user/pwd"; + return "fail"; + } + public void setName(String name) { + + this.name=name; + } + + public void setPassword(String password) { + + this.password=password; + } + public String getMessage() + { + return message; + } + +} diff --git a/group26/1778842360/third homework/TTD/ReflectionUtil.java b/group26/1778842360/third homework/TTD/ReflectionUtil.java new file mode 100644 index 0000000000..186edb6c5a --- /dev/null +++ b/group26/1778842360/third homework/TTD/ReflectionUtil.java @@ -0,0 +1,76 @@ +package com.coderising.litestruts; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ReflectionUtil { + + public static List getSetterMethods(Class clz) { + + return getMethods(clz,"set"); + } + + public static void setParameters(Object o, Map params) { + + List methods=getSetterMethods(o.getClass()); + + for(String name:params.keySet()) + { + String methodName="set"+name; + for(Method m:methods) + { + if(m.getName().equalsIgnoreCase(methodName)) + { + try{ + m.invoke(o, params.get(name)); + }catch(IllegalAccessException | IllegalArgumentException | InvocationTargetException e) + { + e.printStackTrace(); + } + } + } + } + } + + public static List getGetterMethods(Class clz) { + return getMethods(clz,"get"); + } + + public static List getMethods(Class clz,String startWithName) + { + List methods=new ArrayList<>(); + for(Method m:clz.getDeclaredMethods()) + { + if(m.getName().startsWith(startWithName)) + { + methods.add(m); + } + } + return methods; + } + + public static Map getParamterMap(Object o) { + Map params=new HashMap<>(); + + List methods=getGetterMethods(o.getClass()); + + for(Method m:methods) + { + String methodName=m.getName(); + String name=methodName.replaceFirst("get","").toLowerCase(); + try{ + Object value=m.invoke(o); + params.put(name, value); + }catch(Exception e) + { + e.printStackTrace(); + } + } + return params; + } + +} diff --git a/group26/1778842360/third homework/TTD/ReflectionUtilTest.java b/group26/1778842360/third homework/TTD/ReflectionUtilTest.java new file mode 100644 index 0000000000..27a56433ca --- /dev/null +++ b/group26/1778842360/third homework/TTD/ReflectionUtilTest.java @@ -0,0 +1,108 @@ +package com.coderising.litestruts; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + +public class ReflectionUtilTest { + + @Before + public void setUp() throws Exception{ + + } + @After + public void TearDown() throws Exception{ + + } + @Test + public void testGetSetterMethod() throws ClassNotFoundException { + String name="com.coderising.litestruts.LoginAction"; + Class clz=Class.forName(name); + List methods=ReflectionUtil.getSetterMethods(clz); + + Assert.assertEquals(2, methods.size()); + + List expectedNames=new ArrayList<>(); + expectedNames.add("setName"); + expectedNames.add("setPassword"); + + Set actualNames=new HashSet<>(); + for(Method m:methods){ + actualNames.add(m.getName()); + } + Assert.assertTrue(actualNames.containsAll(expectedNames)); + } + @Test + public void testSetParameter() throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, InstantiationException + { + String name="com.coderising.litestruts.LoginAction"; + Class clz=Class.forName(name); + + Object o=clz.newInstance(); + + Map params=new HashMap(); + params.put("name", "test"); + params.put("password", "1234"); + + ReflectionUtil.setParameters(o,params); + + Field f=clz.getDeclaredField("name"); + f.setAccessible(true); + Assert.assertEquals("test", f.get(o)); + + f=clz.getDeclaredField("password"); + f.setAccessible(true); + Assert.assertEquals("1234", f.get(o)); + } + @Test + public void testGetGetterMethod() throws Exception + { + String name="com.coderising.litestruts.LoginAction"; + Class clz=Class.forName(name); + List methods=ReflectionUtil.getGetterMethods(clz); + + Assert.assertEquals(3,methods.size()); + + List expectedNames=new ArrayList<>(); + expectedNames.add("getMessage"); + expectedNames.add("getName"); + expectedNames.add("getPassword"); + + Set actualNames=new HashSet<>(); + for(Method m:methods) + { + actualNames.add(m.getName()); + } + Assert.assertTrue(actualNames.containsAll(expectedNames)); + } + @Test + public void testGetParmters() throws Exception + { + String name="com.coderising.litestruts.LoginAction"; + Class clz=Class.forName(name); + + LoginAction action=(LoginAction)clz.newInstance(); + action.setName("test"); + action.setPassword("123456"); + + Map params=ReflectionUtil.getParamterMap(action); + Assert.assertEquals(3,params.size()); + + Assert.assertEquals(null, params.get("message")); + Assert.assertEquals("test",params.get("name")); + Assert.assertEquals("123456",params.get("password")); + } + + +} diff --git a/group26/1778842360/third homework/TTD/Struts.java b/group26/1778842360/third homework/TTD/Struts.java new file mode 100644 index 0000000000..ab704cf7e9 --- /dev/null +++ b/group26/1778842360/third homework/TTD/Struts.java @@ -0,0 +1,56 @@ +package com.coderising.litestruts; + +import java.lang.reflect.Method; +import java.util.Map; + +public class Struts { + private final static Configureation cfg=new Configureation("struts.xml"); + 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字段中。 + + */ + String clzName=cfg.getClassName(actionName); + if(clzName==null) + { + return null; + } + try{ + Class clz=Class.forName(clzName); + Object action=clz.newInstance(); + + ReflectionUtil.setParameters(action, parameters); + + Method m=clz.getDeclaredMethod("execute"); + String resultName=(String) m.invoke(action); + + Map params=ReflectionUtil.getParamterMap(action); + String resultView=cfg.getResultView(actionName, resultName); + + View view=new View(); + view.setParameters(params); + view.setJsp(resultView); + return view; + }catch(Exception e) + { + e.printStackTrace(); + } + return null; + } +} diff --git a/group26/1778842360/third homework/TTD/View.java b/group26/1778842360/third homework/TTD/View.java new file mode 100644 index 0000000000..46138088a9 --- /dev/null +++ b/group26/1778842360/third homework/TTD/View.java @@ -0,0 +1,27 @@ +package com.coderising.litestruts; + +import java.util.Map; + +public class View { + + private String jsp; + private Map parameters; + public View setParameters(Map params) { + this.parameters=params; + return this; + } + + public View setJsp(String jsp) { + this.jsp=jsp; + return this; + } + public Map getParameters() + { + return parameters; + } + public String getJsp() + { + return jsp; + } + +} From f7e585e4846717b827edf29e49b07dd09dc0d394 Mon Sep 17 00:00:00 2001 From: SJsunshine Date: Mon, 27 Mar 2017 22:35:07 +0800 Subject: [PATCH 06/20] week2 --- group26/1515345281/.classpath | 8 + group26/1515345281/.gitignore | 6 +- group26/1515345281/.project | 17 ++ .../week1/collection/test/ArrayListTest.java | 138 ++++++------- .../collection/test/BinarySearchTreeTest.java | 46 ++--- .../week1/collection/test/LinkedListTest.java | 180 ++++++++-------- .../src/week1/collection/test/QueueTest.java | 54 ++--- .../src/week1/collection/test/StackTest.java | 112 +++++----- .../src/week2/arrayutil/ArrayUtilTest.java | 194 +++++++++--------- .../src/week2/litestruts/LoginAction.java | 39 ++++ .../src/week2/litestruts/ReflectionUtil.java | 123 +++++++++++ .../week2/litestruts/ReflectionUtilTest.java | 113 ++++++++++ .../src/week2/litestruts/Struts.java | 68 ++++++ .../src/week2/litestruts/StrutsTest.java | 43 ++++ .../1515345281/src/week2/litestruts/View.java | 23 +++ .../src/week2/struts2/Configuration.java | 122 +++++++++++ .../week2/struts2/ConfigurationException.java | 20 ++ .../1515345281/src/week2/struts2/struts.xml | 23 ++- .../week2/struts2/test/ConfigurationTest.java | 40 ++++ .../src/week3/download/FileDownloader.java | 0 .../week3/download/FileDownloaderTest.java | 0 21 files changed, 994 insertions(+), 375 deletions(-) create mode 100644 group26/1515345281/.classpath create mode 100644 group26/1515345281/.project create mode 100644 group26/1515345281/src/week2/litestruts/LoginAction.java create mode 100644 group26/1515345281/src/week2/litestruts/ReflectionUtil.java create mode 100644 group26/1515345281/src/week2/litestruts/ReflectionUtilTest.java create mode 100644 group26/1515345281/src/week2/litestruts/Struts.java create mode 100644 group26/1515345281/src/week2/litestruts/StrutsTest.java create mode 100644 group26/1515345281/src/week2/litestruts/View.java create mode 100644 group26/1515345281/src/week2/struts2/Configuration.java create mode 100644 group26/1515345281/src/week2/struts2/ConfigurationException.java create mode 100644 group26/1515345281/src/week2/struts2/test/ConfigurationTest.java create mode 100644 group26/1515345281/src/week3/download/FileDownloader.java create mode 100644 group26/1515345281/src/week3/download/FileDownloaderTest.java diff --git a/group26/1515345281/.classpath b/group26/1515345281/.classpath new file mode 100644 index 0000000000..0b147a3172 --- /dev/null +++ b/group26/1515345281/.classpath @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/group26/1515345281/.gitignore b/group26/1515345281/.gitignore index 4f4c622218..50fe13f0ff 100644 --- a/group26/1515345281/.gitignore +++ b/group26/1515345281/.gitignore @@ -1,2 +1,4 @@ -/bin -/.project/.classpath \ No newline at end of file +/bin +/.project/.classpath +/.settings +/lib \ No newline at end of file diff --git a/group26/1515345281/.project b/group26/1515345281/.project new file mode 100644 index 0000000000..a58f6ad71c --- /dev/null +++ b/group26/1515345281/.project @@ -0,0 +1,17 @@ + + + 1515345281Learning + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/group26/1515345281/src/week1/collection/test/ArrayListTest.java b/group26/1515345281/src/week1/collection/test/ArrayListTest.java index 0fa7701041..552420ba65 100644 --- a/group26/1515345281/src/week1/collection/test/ArrayListTest.java +++ b/group26/1515345281/src/week1/collection/test/ArrayListTest.java @@ -1,69 +1,69 @@ -package week1.test; - -import static org.junit.Assert.*; - -import org.junit.Test; - -import week1.collection.ArrayList; -import week1.collection.Iterator; - -public class ArrayListTest { - - private ArrayList list=new ArrayList(); - - @Test - public void testAddObject(){ - list.add(1); - assertEquals(1 , list.get(0)); - } - - @Test - public void testAddIndexObject(){ - list.add("aa"); - list.add("bb"); - list.add(0,"cc"); - assertEquals("cc",list.get(0)); - try{ - list.add(-1,"pp"); - fail("- can't be index"); - - list.add(list.size()+100,"bb"); - fail("index should <= size"); - - }catch(Exception ex){ - - } - } - - @Test - public void testGetObject(){ - list.add(1); - assertEquals(1,list.get(0)); - } - - @Test - public void testRemoveObject(){ - list.add(1); - list.add(2); - list.add(3); - list.remove(0); - list.remove(2); - assertEquals(2,list.get(0)); - } - - @Test - public void testSize(){ - assertEquals(0,list.size()); - } - - @Test - public void testIterator(){ - list.add(1); - list.add(2); - list.add(3); - Iterator it=list.iterator(); - while(it.hasNext()){ - System.out.println(it.next()); - } - } -} +package week1.collection.test; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import week1.collection.ArrayList; +import week1.collection.Iterator; + +public class ArrayListTest { + + private ArrayList list=new ArrayList(); + + @Test + public void testAddObject(){ + list.add(1); + assertEquals(1 , list.get(0)); + } + + @Test + public void testAddIndexObject(){ + list.add("aa"); + list.add("bb"); + list.add(0,"cc"); + assertEquals("cc",list.get(0)); + try{ + list.add(-1,"pp"); + fail("- can't be index"); + + list.add(list.size()+100,"bb"); + fail("index should <= size"); + + }catch(Exception ex){ + + } + } + + @Test + public void testGetObject(){ + list.add(1); + assertEquals(1,list.get(0)); + } + + @Test + public void testRemoveObject(){ + list.add(1); + list.add(2); + list.add(3); + list.remove(0); + list.remove(2); + assertEquals(2,list.get(0)); + } + + @Test + public void testSize(){ + assertEquals(0,list.size()); + } + + @Test + public void testIterator(){ + list.add(1); + list.add(2); + list.add(3); + Iterator it=list.iterator(); + while(it.hasNext()){ + System.out.println(it.next()); + } + } +} diff --git a/group26/1515345281/src/week1/collection/test/BinarySearchTreeTest.java b/group26/1515345281/src/week1/collection/test/BinarySearchTreeTest.java index a6ea1cac3f..b612bfb0ee 100644 --- a/group26/1515345281/src/week1/collection/test/BinarySearchTreeTest.java +++ b/group26/1515345281/src/week1/collection/test/BinarySearchTreeTest.java @@ -1,23 +1,23 @@ -package week1.test; - -import static org.junit.Assert.*; - -import org.junit.Test; - -import week1.collection.BinaryTreeNode; - -public class BinarySearchTreeTest { - - private BinaryTreeNode root=new BinaryTreeNode(5); - - @Test - public void testInsert(){ - root.insert(2); - root.insert(2); - root.insert(7); - root.insert(1); - root.insert(4); - root.insert(3); - assertEquals(3,root.getLeft().getRight().getLeft().getData()); - } -} +package week1.collection.test; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import week1.collection.BinaryTreeNode; + +public class BinarySearchTreeTest { + + private BinaryTreeNode root=new BinaryTreeNode(5); + + @Test + public void testInsert(){ + root.insert(2); + root.insert(2); + root.insert(7); + root.insert(1); + root.insert(4); + root.insert(3); + assertEquals(3,root.getLeft().getRight().getLeft().getData()); + } +} diff --git a/group26/1515345281/src/week1/collection/test/LinkedListTest.java b/group26/1515345281/src/week1/collection/test/LinkedListTest.java index cba45c719d..94475a22bb 100644 --- a/group26/1515345281/src/week1/collection/test/LinkedListTest.java +++ b/group26/1515345281/src/week1/collection/test/LinkedListTest.java @@ -1,90 +1,90 @@ -package week1.test; - -import static org.junit.Assert.*; - -import org.junit.Test; - -import week1.collection.Iterator; -import week1.collection.LinkedList; - -public class LinkedListTest { - - private LinkedList list=new LinkedList(); - - @Test - public void testAdd(){ - list.add("1"); - list.add("2"); - list.add("3"); - assertEquals("1",list.get(0)); - assertEquals("2",list.get(1)); - assertEquals(3,list.size()); - } - - @Test - public void testAddByIndex(){ - list.add(2); - list.add(4); - list.add(6); - list.add(0,0); - list.add(3,3); - list.add(5,7); - assertEquals(0, list.get(0)); - assertEquals(3, list.get(3)); - assertEquals(7, list.get(5)); - try{ - list.add(-1,0); - fail("-1 not a correctly index"); - }catch(Exception ex){ - - } - } - - @Test - public void testGet(){ - list.add(0); - list.add(1); - list.add(2); - assertEquals(0,list.get(0)); - } - - @Test - public void testRemove(){ - list.add(0); - list.add(1); - list.add(2); - list.add(3); - list.add(4); - assertEquals(0,list.remove(0)); - assertEquals(4,list.remove(3)); - assertEquals(2,list.remove(1)); - } - - @Test - public void testSize(){ - list.add(0); - list.addLast(0); - list.addFirst(0); - list.remove(0); - list.removeLast(); - list.removeFirst(); - assertEquals(0,list.size()); - } - - @Test - public void testOther(){ - list.add(1); - list.add(1); - list.add(1); - list.add(1); - list.addFirst(0); - list.addLast(2); - list.removeFirst(); - list.removeLast(); - Iterator it=list.iterator(); - while(it.hasNext()){ - System.out.print(it.next()+" "); - } - } - -} +package week1.collection.test; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import week1.collection.Iterator; +import week1.collection.LinkedList; + +public class LinkedListTest { + + private LinkedList list=new LinkedList(); + + @Test + public void testAdd(){ + list.add("1"); + list.add("2"); + list.add("3"); + assertEquals("1",list.get(0)); + assertEquals("2",list.get(1)); + assertEquals(3,list.size()); + } + + @Test + public void testAddByIndex(){ + list.add(2); + list.add(4); + list.add(6); + list.add(0,0); + list.add(3,3); + list.add(5,7); + assertEquals(0, list.get(0)); + assertEquals(3, list.get(3)); + assertEquals(7, list.get(5)); + try{ + list.add(-1,0); + fail("-1 not a correctly index"); + }catch(Exception ex){ + + } + } + + @Test + public void testGet(){ + list.add(0); + list.add(1); + list.add(2); + assertEquals(0,list.get(0)); + } + + @Test + public void testRemove(){ + list.add(0); + list.add(1); + list.add(2); + list.add(3); + list.add(4); + assertEquals(0,list.remove(0)); + assertEquals(4,list.remove(3)); + assertEquals(2,list.remove(1)); + } + + @Test + public void testSize(){ + list.add(0); + list.addLast(0); + list.addFirst(0); + list.remove(0); + list.removeLast(); + list.removeFirst(); + assertEquals(0,list.size()); + } + + @Test + public void testOther(){ + list.add(1); + list.add(1); + list.add(1); + list.add(1); + list.addFirst(0); + list.addLast(2); + list.removeFirst(); + list.removeLast(); + Iterator it=list.iterator(); + while(it.hasNext()){ + System.out.print(it.next()+" "); + } + } + +} diff --git a/group26/1515345281/src/week1/collection/test/QueueTest.java b/group26/1515345281/src/week1/collection/test/QueueTest.java index 81979682a6..96d61403eb 100644 --- a/group26/1515345281/src/week1/collection/test/QueueTest.java +++ b/group26/1515345281/src/week1/collection/test/QueueTest.java @@ -1,27 +1,27 @@ -package week1.test; - -import static org.junit.Assert.*; - -import org.junit.Test; - -import week1.collection.Queue; - -public class QueueTest { - - private Queue queue=new Queue(); - - @Test - public void testEnQueue(){ - queue.enQueue("123"); - queue.enQueue("456"); - assertEquals("123",queue.deQueue()); - } - - @Test - public void testDeQueue(){ - queue.enQueue("123"); - queue.enQueue("456"); - queue.deQueue(); - assertEquals("456",queue.deQueue()); - } -} +package week1.collection.test; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import week1.collection.Queue; + +public class QueueTest { + + private Queue queue=new Queue(); + + @Test + public void testEnQueue(){ + queue.enQueue("123"); + queue.enQueue("456"); + assertEquals("123",queue.deQueue()); + } + + @Test + public void testDeQueue(){ + queue.enQueue("123"); + queue.enQueue("456"); + queue.deQueue(); + assertEquals("456",queue.deQueue()); + } +} diff --git a/group26/1515345281/src/week1/collection/test/StackTest.java b/group26/1515345281/src/week1/collection/test/StackTest.java index 717bf9b6a8..6d0f49947e 100644 --- a/group26/1515345281/src/week1/collection/test/StackTest.java +++ b/group26/1515345281/src/week1/collection/test/StackTest.java @@ -1,56 +1,56 @@ -package week1.test; - -import static org.junit.Assert.*; - -import org.junit.Test; - -import week1.collection.Stack; - -public class StackTest { - - private Stack stack=new Stack(); - - @Test - public void testPush(){ - stack.push("hello"); - stack.push("world"); - assertEquals("world",stack.peek()); - } - - @Test - public void testPop(){ - stack.push("hello"); - stack.push("world"); - assertEquals("world",stack.pop()); - assertEquals(1,stack.size()); - } - - @Test - public void testPeek(){ - stack.push("world"); - assertEquals("world",stack.peek()); - stack.pop(); - try{ - stack.peek(); - fail("stack is empty,can't do peek"); - - }catch(Exception ex){ - - } - } - - @Test - public void testEmpty(){ - assertEquals(true,stack.isEmpty()); - stack.push("hello"); - stack.push("world"); - assertEquals(false,stack.isEmpty()); - } - - @Test - public void testSize(){ - stack.push("hello"); - stack.pop(); - assertEquals(0,stack.size()); - } -} +package week1.collection.test; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import week1.collection.Stack; + +public class StackTest { + + private Stack stack=new Stack(); + + @Test + public void testPush(){ + stack.push("hello"); + stack.push("world"); + assertEquals("world",stack.peek()); + } + + @Test + public void testPop(){ + stack.push("hello"); + stack.push("world"); + assertEquals("world",stack.pop()); + assertEquals(1,stack.size()); + } + + @Test + public void testPeek(){ + stack.push("world"); + assertEquals("world",stack.peek()); + stack.pop(); + try{ + stack.peek(); + fail("stack is empty,can't do peek"); + + }catch(Exception ex){ + + } + } + + @Test + public void testEmpty(){ + assertEquals(true,stack.isEmpty()); + stack.push("hello"); + stack.push("world"); + assertEquals(false,stack.isEmpty()); + } + + @Test + public void testSize(){ + stack.push("hello"); + stack.pop(); + assertEquals(0,stack.size()); + } +} diff --git a/group26/1515345281/src/week2/arrayutil/ArrayUtilTest.java b/group26/1515345281/src/week2/arrayutil/ArrayUtilTest.java index 7b0d3c94e0..979ec3bd05 100644 --- a/group26/1515345281/src/week2/arrayutil/ArrayUtilTest.java +++ b/group26/1515345281/src/week2/arrayutil/ArrayUtilTest.java @@ -1,97 +1,97 @@ - -package week2.test; - -import static org.junit.Assert.*; - -import org.junit.Test; - -import week2.arrayutil.ArrayUtil; - -public class ArrayUtilTest { - - private ArrayUtil arrayUtil=new ArrayUtil(); - - @Test - public void testReverseArray(){ - - int[] origin={1,2,3,4}; - arrayUtil.reverseArray(origin); - assertArrayEquals(new int[]{4,3,2,1}, origin); - - int[] origin1={5,6,7}; - arrayUtil.reverseArray(origin1); - assertArrayEquals(new int[]{7,6,5},origin1); - } - - @Test - public void testRemoveArray(){ - - int[] oldArray={0,0,1,2,0,0,3,4,0,0}; - int[] result=arrayUtil.removeZero(oldArray); - assertArrayEquals(new int[]{1,2,3,4},result); - } - - @Test - public void testMerge(){ - int[] array1={3,5,7,8}; - int[] array2={4,5,6,7}; - int[] array=arrayUtil.merge(array1, array2); - assertArrayEquals(new int[]{3,4,5,6,7,8}, array); - } - - @Test - public void testGrow(){ - int[] oldArray={2,3,6}; - int size=3; - int[] newArray=new int[oldArray.length+size]; - newArray=arrayUtil.grow(oldArray, size); - assertArrayEquals(new int[]{2,3,6,0,0,0},newArray); - } - - @Test - public void testFibonacci(){ - int max=1; - int[] result=arrayUtil.fibonacci(max); - assertArrayEquals(new int[0],result); - - max=2; - int[] result1=arrayUtil.fibonacci(max); - assertEquals(1,result1[0]); - - max=15; - int[] result2=arrayUtil.fibonacci(max); - assertArrayEquals(new int[]{1,1,2,3,5,8,13},result2); - } - - @Test - public void testGetPrime(){ - int max=-1; - int[] result=arrayUtil.getPrimes(max); - assertEquals(new int[0],result); - - max=23; - result=arrayUtil.getPrimes(max); - assertEquals(new int[]{2,3,5,7,11,13,17,19},result); - - } - - @Test - public void testGetPerfectNumbers(){ - int max=7; - int[] result=arrayUtil.getPerfectNumbers(max); - assertArrayEquals(new int[]{6},result); - - max=100; - result=arrayUtil.getPerfectNumbers(max); - assertArrayEquals(new int[]{6,28},result); - } - - @Test - public void testJoin(){ - String seperator="-"; - int[] array={3,5,8}; - String result=arrayUtil.join(array, seperator); - assertEquals("3-5-8",result); - - } -} + +package week2.arrayutil; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import week2.arrayutil.ArrayUtil; + +public class ArrayUtilTest { + + private ArrayUtil arrayUtil=new ArrayUtil(); + + @Test + public void testReverseArray(){ + + int[] origin={1,2,3,4}; + arrayUtil.reverseArray(origin); + assertArrayEquals(new int[]{4,3,2,1}, origin); + + int[] origin1={5,6,7}; + arrayUtil.reverseArray(origin1); + assertArrayEquals(new int[]{7,6,5},origin1); + } + + @Test + public void testRemoveArray(){ + + int[] oldArray={0,0,1,2,0,0,3,4,0,0}; + int[] result=arrayUtil.removeZero(oldArray); + assertArrayEquals(new int[]{1,2,3,4},result); + } + + @Test + public void testMerge(){ + int[] array1={3,5,7,8}; + int[] array2={4,5,6,7}; + int[] array=arrayUtil.merge(array1, array2); + assertArrayEquals(new int[]{3,4,5,6,7,8}, array); + } + + @Test + public void testGrow(){ + int[] oldArray={2,3,6}; + int size=3; + int[] newArray=new int[oldArray.length+size]; + newArray=arrayUtil.grow(oldArray, size); + assertArrayEquals(new int[]{2,3,6,0,0,0},newArray); + } + + @Test + public void testFibonacci(){ + int max=1; + int[] result=arrayUtil.fibonacci(max); + assertArrayEquals(new int[0],result); + + max=2; + int[] result1=arrayUtil.fibonacci(max); + assertEquals(1,result1[0]); + + max=15; + int[] result2=arrayUtil.fibonacci(max); + assertArrayEquals(new int[]{1,1,2,3,5,8,13},result2); + } + + @Test + public void testGetPrime(){ + int max=-1; + int[] result=arrayUtil.getPrimes(max); + assertEquals(new int[0],result); + + max=23; + result=arrayUtil.getPrimes(max); + assertEquals(new int[]{2,3,5,7,11,13,17,19},result); + + } + + @Test + public void testGetPerfectNumbers(){ + int max=7; + int[] result=arrayUtil.getPerfectNumbers(max); + assertArrayEquals(new int[]{6},result); + + max=100; + result=arrayUtil.getPerfectNumbers(max); + assertArrayEquals(new int[]{6,28},result); + } + + @Test + public void testJoin(){ + String seperator="-"; + int[] array={3,5,8}; + String result=arrayUtil.join(array, seperator); + assertEquals("3-5-8",result); + + } +} diff --git a/group26/1515345281/src/week2/litestruts/LoginAction.java b/group26/1515345281/src/week2/litestruts/LoginAction.java new file mode 100644 index 0000000000..1916b37335 --- /dev/null +++ b/group26/1515345281/src/week2/litestruts/LoginAction.java @@ -0,0 +1,39 @@ +package week2.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/group26/1515345281/src/week2/litestruts/ReflectionUtil.java b/group26/1515345281/src/week2/litestruts/ReflectionUtil.java new file mode 100644 index 0000000000..5866c547f3 --- /dev/null +++ b/group26/1515345281/src/week2/litestruts/ReflectionUtil.java @@ -0,0 +1,123 @@ +package week2.litestruts; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ReflectionUtil { + + public static List getSetterMethods(Class clz) { + + return getMethods(clz,"set"); + + } + + public static void setParameters(Object o, Map params) { + + List methods = getSetterMethods(o.getClass()); + + for(String name : params.keySet() ){ + + String methodName = "set" + name; + + for(Method m: methods){ + + if(m.getName().equalsIgnoreCase(methodName)){ + try { + m.invoke(o, params.get(name)); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + e.printStackTrace(); + } + } + } + } + + } + + public static List getGetterMethods(Class clz) { + return getMethods(clz,"get"); + } + + private static List getMethods(Class clz, String startWithName){ + + List methods = new ArrayList<>(); + + for(Method m : clz.getDeclaredMethods()){ + + if(m.getName().startsWith(startWithName)){ + + methods.add(m); + + } + + } + + return methods; + } + + public static Map getParamterMap(Object o) { + + Map params = new HashMap<>(); + + List methods = getGetterMethods(o.getClass()); + + for(Method m : methods){ + + String methodName = m.getName(); + String name = methodName.replaceFirst("get", "").toLowerCase(); + try { + Object value = m.invoke(o); + params.put(name, value); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + + e.printStackTrace(); + } + } + + return params; + } + + ////////////////////////Backup /////////////////////////////////// + + public static List getGetterMethods_V1(Class clz) { + + List methods = new ArrayList<>(); + + for(Method m : clz.getDeclaredMethods()){ + + if(m.getName().startsWith("get")){ + + methods.add(m); + + } + + } + + return methods; + } + + public static List getSetterMethods_V1(Class clz) { + + List methods = new ArrayList<>(); + + for(Method m : clz.getDeclaredMethods()){ + + if(m.getName().startsWith("set")){ + + methods.add(m); + + } + + } + + return methods; + + } + + + + +} diff --git a/group26/1515345281/src/week2/litestruts/ReflectionUtilTest.java b/group26/1515345281/src/week2/litestruts/ReflectionUtilTest.java new file mode 100644 index 0000000000..8bd08063d6 --- /dev/null +++ b/group26/1515345281/src/week2/litestruts/ReflectionUtilTest.java @@ -0,0 +1,113 @@ +package week2.litestruts; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + + +public class ReflectionUtilTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetSetterMethod() throws Exception { + + String name = "com.coderising.litestruts.LoginAction"; + Class clz = Class.forName(name); + List methods = ReflectionUtil.getSetterMethods(clz); + + Assert.assertEquals(2, methods.size()); + + List expectedNames = new ArrayList<>(); + expectedNames.add("setName"); + expectedNames.add("setPassword"); + + Set acctualNames = new HashSet<>(); + for(Method m : methods){ + acctualNames.add(m.getName()); + } + + Assert.assertTrue(acctualNames.containsAll(expectedNames)); + } + + @Test + public void testSetParameters() throws Exception{ + + String name = "com.coderising.litestruts.LoginAction"; + Class clz = Class.forName(name); + Object o = clz.newInstance(); + + Map params = new HashMap(); + params.put("name","test"); + params.put("password","1234"); + + ReflectionUtil.setParameters(o,params); + + + + Field f = clz.getDeclaredField("name"); + f.setAccessible(true); + Assert.assertEquals("test", f.get(o)); + + f = clz.getDeclaredField("password"); + f.setAccessible(true); + Assert.assertEquals("1234", f.get(o)); + } + @Test + public void testGetGetterMethod() throws Exception{ + String name = "com.coderising.litestruts.LoginAction"; + Class clz = Class.forName(name); + List methods = ReflectionUtil.getGetterMethods(clz); + + Assert.assertEquals(3, methods.size()); + + List expectedNames = new ArrayList<>(); + expectedNames.add("getMessage"); + expectedNames.add("getName"); + expectedNames.add("getPassword"); + + Set acctualNames = new HashSet<>(); + for(Method m : methods){ + acctualNames.add(m.getName()); + } + + Assert.assertTrue(acctualNames.containsAll(expectedNames)); + } + + @Test + public void testGetParamters() throws Exception{ + String name = "com.coderising.litestruts.LoginAction"; + Class clz = Class.forName(name); + LoginAction action = (LoginAction)clz.newInstance(); + action.setName("test"); + action.setPassword("123456"); + + + + + Map params = ReflectionUtil.getParamterMap(action); + + Assert.assertEquals(3, params.size()); + + Assert.assertEquals(null, params.get("messaage") ); + Assert.assertEquals("test", params.get("name") ); + Assert.assertEquals("123456", params.get("password") ); + } +} diff --git a/group26/1515345281/src/week2/litestruts/Struts.java b/group26/1515345281/src/week2/litestruts/Struts.java new file mode 100644 index 0000000000..fa90e87fa0 --- /dev/null +++ b/group26/1515345281/src/week2/litestruts/Struts.java @@ -0,0 +1,68 @@ +package week2.litestruts; + +import java.lang.reflect.Method; +import java.util.Map; + + + +public class Struts { + + private final static Configuration cfg = new Configuration("struts.xml"); + + 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字段中。 + + */ + + + + String clzName = cfg.getClassName(actionName); + + if(clzName == null){ + return null; + } + + try { + + Class clz = Class.forName(clzName); + Object action = clz.newInstance(); + + ReflectionUtil.setParameters(action, parameters); + + Method m = clz.getDeclaredMethod("execute"); + String resultName = (String)m.invoke(action); + + Map params = ReflectionUtil.getParamterMap(action); + String resultView = cfg.getResultView(actionName, resultName); + View view = new View(); + view.setParameters(params); + view.setJsp(resultView); + return view; + + + + } catch (Exception e) { + + e.printStackTrace(); + } + return null; + } + +} diff --git a/group26/1515345281/src/week2/litestruts/StrutsTest.java b/group26/1515345281/src/week2/litestruts/StrutsTest.java new file mode 100644 index 0000000000..d5f78939a5 --- /dev/null +++ b/group26/1515345281/src/week2/litestruts/StrutsTest.java @@ -0,0 +1,43 @@ +package week2.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/group26/1515345281/src/week2/litestruts/View.java b/group26/1515345281/src/week2/litestruts/View.java new file mode 100644 index 0000000000..bdd700a71c --- /dev/null +++ b/group26/1515345281/src/week2/litestruts/View.java @@ -0,0 +1,23 @@ +package week2.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/group26/1515345281/src/week2/struts2/Configuration.java b/group26/1515345281/src/week2/struts2/Configuration.java new file mode 100644 index 0000000000..ddb27cc229 --- /dev/null +++ b/group26/1515345281/src/week2/struts2/Configuration.java @@ -0,0 +1,122 @@ +package week2.struts2; + +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + +import org.jdom2.Document; +import org.jdom2.Element; +import org.jdom2.JDOMException; +import org.jdom2.input.SAXBuilder; + + +/** + * 配置解析struts.xml文件 + * @author Administrator + * + */ +public class Configuration { + + Map actions=new HashMap<>(); + + public Configuration(String fileName) { + + //获取当前类包名 + String packageName=this.getClass().getPackage().getName(); + + packageName=packageName.replace(".", "/"); + //获取文件流 + InputStream input=this.getClass().getResourceAsStream("/"+packageName+"/"+fileName); + + parseXml(input); + + try{ + input.close(); + }catch(IOException e){ + throw new ConfigurationException(e); + } + } + + private void parseXml(InputStream input) { + + SAXBuilder builder=new SAXBuilder(); + + try { + Document document=builder.build(input); + + Element root=document.getRootElement(); + + for(Element actionElement:root.getChildren("action")){ + + String actionName=actionElement.getAttributeValue("name"); + String clazzName=actionElement.getAttributeValue("class"); + + ActionConfig ac=new ActionConfig(actionName,clazzName); + + for(Element resultElement:actionElement.getChildren("result")){ + + String resultName=resultElement.getAttributeValue("name"); + String viewName=resultElement.getText().trim(); + + ac.setViewResult(resultName, viewName); + } + + actions.put(actionName, ac); + } + + } catch (JDOMException e) { + throw new ConfigurationException(e); + } catch (IOException e) { + throw new ConfigurationException(e); + } + + } + + public String getClassName(String actionName) { + + ActionConfig ac=this.actions.get(actionName); + + if(null == ac){ + return null; + } + + return ac.getClazzName(); + } + + public String getResultView(String actionName, String resultName) { + + ActionConfig ac=this.actions.get(actionName); + + if(null == ac){ + return null; + } + + return ac.getViewResult(resultName); + } + + private static class ActionConfig{ + + String actionName; + String clazzName; + Map viewResults=new HashMap<>(); + + public ActionConfig(String actionName,String clazzName){ + this.actionName=actionName; + this.clazzName=clazzName; + } + + public String getClazzName() { + return clazzName; + } + + public void setViewResult(String name,String viewName){ + viewResults.put(name, viewName); + } + + public String getViewResult(String name){ + String viewName=viewResults.get(name); + return viewName; + } + } +} diff --git a/group26/1515345281/src/week2/struts2/ConfigurationException.java b/group26/1515345281/src/week2/struts2/ConfigurationException.java new file mode 100644 index 0000000000..842ca1866b --- /dev/null +++ b/group26/1515345281/src/week2/struts2/ConfigurationException.java @@ -0,0 +1,20 @@ +package week2.struts2; + +import java.io.IOException; + +import org.jdom2.JDOMException; + +public class ConfigurationException extends RuntimeException{ + + public ConfigurationException(String msg){ + super(msg); + } + + public ConfigurationException(JDOMException e){ + super(e); + } + + public ConfigurationException(IOException e){ + super(e); + } +} diff --git a/group26/1515345281/src/week2/struts2/struts.xml b/group26/1515345281/src/week2/struts2/struts.xml index 9e69fa4e47..139267b2f8 100644 --- a/group26/1515345281/src/week2/struts2/struts.xml +++ b/group26/1515345281/src/week2/struts2/struts.xml @@ -1,12 +1,13 @@ - - - - /jsp/homepage.jsp - /jsp/showLogin.jsp - - - - /jsp/welcome.jsp - /jsp/error.jsp - + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + + /jsp/welcome.jsp + /jsp/error.jsp + + \ No newline at end of file diff --git a/group26/1515345281/src/week2/struts2/test/ConfigurationTest.java b/group26/1515345281/src/week2/struts2/test/ConfigurationTest.java new file mode 100644 index 0000000000..dbbaf30eee --- /dev/null +++ b/group26/1515345281/src/week2/struts2/test/ConfigurationTest.java @@ -0,0 +1,40 @@ +package week2.struts2.test; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import week2.struts2.Configuration; + +public class ConfigurationTest { + + Configuration config=new Configuration("struts.xml"); + + @Test + public void testGetClassName(){ + + String clazzName=config.getClassName("login"); + assertEquals("week2.struts2.LoginAction",clazzName); + + clazzName=config.getClassName("logout"); + assertEquals("week2.struts2.LoginOutAction",clazzName); + + clazzName=config.getClassName("logoutf"); + } + + @Test + public void testGetResultView(){ + + String jsp=config.getResultView("login","success"); + assertEquals("/jsp/homepage.jsp",jsp); + + jsp=config.getResultView("login", "fail"); + assertEquals("/jsp/showLogin.jsp",jsp); + + jsp=config.getResultView("logout", "success"); + assertEquals("/jsp/welcome.jsp",jsp); + + jsp=config.getResultView("logout", "error"); + assertEquals("/jsp/error.jsp",jsp); + } +} diff --git a/group26/1515345281/src/week3/download/FileDownloader.java b/group26/1515345281/src/week3/download/FileDownloader.java new file mode 100644 index 0000000000..e69de29bb2 diff --git a/group26/1515345281/src/week3/download/FileDownloaderTest.java b/group26/1515345281/src/week3/download/FileDownloaderTest.java new file mode 100644 index 0000000000..e69de29bb2 From 53c3bd5d2fc1507cf2c044e1e2fdbff9cf5a1786 Mon Sep 17 00:00:00 2001 From: luojunyi Date: Sat, 18 Mar 2017 23:22:42 +0800 Subject: [PATCH 07/20] =?UTF-8?q?=E7=AC=AC=E4=B8=89=E5=91=A8=E4=BD=9C?= =?UTF-8?q?=E4=B8=9A=EF=BC=8C=E5=9B=A0=E4=B8=8A=E5=91=A8=E6=9C=89=E4=BA=8B?= =?UTF-8?q?=E8=80=BD=E8=AF=AF=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: luojunyi --- .../com/coding/litestruts/LoginAction.java | 52 ++++++ .../week2/com/coding/litestruts/Struts.java | 156 ++++++++++++++++++ .../com/coding/litestruts/StrutsTest.java | 41 +++++ .../src/week2/com/coding/litestruts/View.java | 23 +++ .../week2/com/coding/litestruts/struts.xml | 11 ++ .../com/coding/download/DownloadThread.java | 65 ++++++++ .../com/coding/download/FileDownloader.java | 145 ++++++++++++++++ .../coding/download/FileDownloaderTest.java | 66 ++++++++ .../com/coding/download/api/Connection.java | 28 ++++ .../download/api/ConnectionException.java | 5 + .../download/api/ConnectionManager.java | 10 ++ .../coding/download/api/DownloadListener.java | 6 + .../coding/download/impl/ConnectionImpl.java | 70 ++++++++ .../download/impl/ConnectionManagerImpl.java | 42 +++++ 14 files changed, 720 insertions(+) create mode 100644 group26/191191717/src/week2/com/coding/litestruts/LoginAction.java create mode 100644 group26/191191717/src/week2/com/coding/litestruts/Struts.java create mode 100644 group26/191191717/src/week2/com/coding/litestruts/StrutsTest.java create mode 100644 group26/191191717/src/week2/com/coding/litestruts/View.java create mode 100644 group26/191191717/src/week2/com/coding/litestruts/struts.xml create mode 100644 group26/191191717/src/week3/com/coding/download/DownloadThread.java create mode 100644 group26/191191717/src/week3/com/coding/download/FileDownloader.java create mode 100644 group26/191191717/src/week3/com/coding/download/FileDownloaderTest.java create mode 100644 group26/191191717/src/week3/com/coding/download/api/Connection.java create mode 100644 group26/191191717/src/week3/com/coding/download/api/ConnectionException.java create mode 100644 group26/191191717/src/week3/com/coding/download/api/ConnectionManager.java create mode 100644 group26/191191717/src/week3/com/coding/download/api/DownloadListener.java create mode 100644 group26/191191717/src/week3/com/coding/download/impl/ConnectionImpl.java create mode 100644 group26/191191717/src/week3/com/coding/download/impl/ConnectionManagerImpl.java diff --git a/group26/191191717/src/week2/com/coding/litestruts/LoginAction.java b/group26/191191717/src/week2/com/coding/litestruts/LoginAction.java new file mode 100644 index 0000000000..a8bad2d7df --- /dev/null +++ b/group26/191191717/src/week2/com/coding/litestruts/LoginAction.java @@ -0,0 +1,52 @@ +package week2.com.coding.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/group26/191191717/src/week2/com/coding/litestruts/Struts.java b/group26/191191717/src/week2/com/coding/litestruts/Struts.java new file mode 100644 index 0000000000..e9b902c518 --- /dev/null +++ b/group26/191191717/src/week2/com/coding/litestruts/Struts.java @@ -0,0 +1,156 @@ +package week2.com.coding.litestruts; + +import java.io.File; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.dom4j.DocumentException; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; + +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字段中。 + * + */ + File file = new File("src/week2/com/coding/litestruts/struts.xml"); + resolveXml(file); + Object object = actions.get(actionName); + Set set = parameters.keySet();// 获取键值 + Iterator it = set.iterator(); + View view = new View(); + try + { + while (it.hasNext()) + { + String keyName = it.next(); + String setMethodName = "set" + keyName.substring(0, 1).toUpperCase() + keyName.substring(1);// 组合方法名 + + Method method = object.getClass().getMethod(setMethodName, String.class); + if (method == null) + { + continue; + } + method.invoke(object, parameters.get(keyName));// 执行set方法 + } + + Method exeMethod = object.getClass().getMethod("execute"); + String result = (String)exeMethod.invoke(object);// 获取execute方法返回值 + // 获取对象所有的属性值 + Field[] fs = object.getClass().getDeclaredFields(); + HashMap resultMap = new HashMap(); + for (Field f : fs) + { + String fieldName = f.getName(); + Method m2 = object.getClass() + .getMethod("get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1)); + String rs2 = (String)m2.invoke(object); + // 将所有get方法的返回值存入map + resultMap.put(fieldName, rs2); + } + view.setParameters(resultMap); + // 根据result的值找到xml配置的值 + if (null != result) + { + String viewURL = (String)actions.get(actionName + "_" + result); + view.setJsp(viewURL); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + return view; + } + + static Map actions = new HashMap(); + + /** + * 解析XML,将xml映射对象,以及返回值的属性存入actions + * + * @param file + */ + @SuppressWarnings("unchecked") + public static void resolveXml(File file) + { + SAXReader read = new SAXReader(); + Element rootElement = null; + try + { + rootElement = read.read(file).getRootElement(); + List actionList = rootElement.elements("action"); + for (Element ele : actionList) + { + String name = ele.attributeValue("name"); + String clz = ele.attributeValue("class");// 找到类名 + Object obj = Class.forName(clz).newInstance(); + actions.put(name, obj); + if (ele.hasContent())// 如果还有节点 + { + List list = ele.elements("result"); + for (Element e : list) + { + String cName = e.attributeValue("name"); + String cValue = e.getTextTrim(); + actions.put(name + "_" + cName, cValue);// 示例key:login_success + } + } + } + } + catch (DocumentException e) + { + e.printStackTrace(); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + public static void main(String[] args) + throws Exception + { + File file = new File("src/week2/com/coding/litestruts/struts.xml"); + resolveXml(file); + System.out.println(actions.toString()); + // Map parameters = new HashMap(); + // parameters.put("name", "luojunyi"); + // runAction("login", parameters); + // Class clazz = Class.forName("week2.com.coding.litestruts.LoginAction"); + // Object obj = clz.newInstance(); + // System.out.println(obj.toString()); + // Method m1 = clz.getMethod("setName", java.lang.String.class); + // System.out.println(m1.getName()); + // m1.invoke(obj, "hello"); + // Method m2 = clz.getMethod("getName"); + // System.out.println(m2.getName()); + // String s = (String)m2.invoke(obj); + // System.out.println(s); + // Field[] f = clazz.getDeclaredFields(); + // for (int i = 0; i < f.length; i++) + // { + // System.out.println(f[i].getName()); + // } + } +} diff --git a/group26/191191717/src/week2/com/coding/litestruts/StrutsTest.java b/group26/191191717/src/week2/com/coding/litestruts/StrutsTest.java new file mode 100644 index 0000000000..7f5125c107 --- /dev/null +++ b/group26/191191717/src/week2/com/coding/litestruts/StrutsTest.java @@ -0,0 +1,41 @@ +package week2.com.coding.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/group26/191191717/src/week2/com/coding/litestruts/View.java b/group26/191191717/src/week2/com/coding/litestruts/View.java new file mode 100644 index 0000000000..3d0708b0c0 --- /dev/null +++ b/group26/191191717/src/week2/com/coding/litestruts/View.java @@ -0,0 +1,23 @@ +package week2.com.coding.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/group26/191191717/src/week2/com/coding/litestruts/struts.xml b/group26/191191717/src/week2/com/coding/litestruts/struts.xml new file mode 100644 index 0000000000..d63e7651d8 --- /dev/null +++ b/group26/191191717/src/week2/com/coding/litestruts/struts.xml @@ -0,0 +1,11 @@ + + + + /jsp/homepage.jsp + /jsp/showLogin.jsp + + + \ No newline at end of file diff --git a/group26/191191717/src/week3/com/coding/download/DownloadThread.java b/group26/191191717/src/week3/com/coding/download/DownloadThread.java new file mode 100644 index 0000000000..6fc0a88f24 --- /dev/null +++ b/group26/191191717/src/week3/com/coding/download/DownloadThread.java @@ -0,0 +1,65 @@ +package week3.com.coding.download; + +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; + +import week3.com.coding.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() + { + File f = new File("d:\\test.txt"); + RandomAccessFile raf = null; + try + { + raf = new RandomAccessFile(f, "rwd"); + raf.seek(startPos);// ��λ��ǰ��ָ�� + // raf.close(); + byte[] bs = conn.read(startPos, endPos); + raf.write(bs); + } + catch (IOException e) + { + e.printStackTrace(); + } + } + + /** + * ��Դ�ͷ� + * + * @param raf + * @param conn + */ + public void release(RandomAccessFile raf, Connection conn) + { + try + { + raf.close(); + } + catch (IOException e) + { + e.printStackTrace(); + } + conn.close(); + } +} diff --git a/group26/191191717/src/week3/com/coding/download/FileDownloader.java b/group26/191191717/src/week3/com/coding/download/FileDownloader.java new file mode 100644 index 0000000000..eec402fbe1 --- /dev/null +++ b/group26/191191717/src/week3/com/coding/download/FileDownloader.java @@ -0,0 +1,145 @@ +package week3.com.coding.download; + +import java.io.IOException; + +import week3.com.coding.download.api.Connection; +import week3.com.coding.download.api.ConnectionException; +import week3.com.coding.download.api.ConnectionManager; +import week3.com.coding.download.api.DownloadListener; +import week3.com.coding.download.impl.ConnectionImpl; +import week3.com.coding.download.impl.ConnectionManagerImpl; + +public class FileDownloader +{ + + String url; + + DownloadListener listener; + + ConnectionManager cm; + + int ThreadNum; + + public FileDownloader(String url, int threadNum) + { + super(); + this.url = url; + ThreadNum = threadNum; + } + + 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 = (ConnectionImpl)cm.open(this.url); + int length = conn.getContentLength();// 获取文件的长度 + // 三个线程,每个线程下载长度要平均 + int blockSize = length / this.ThreadNum; + for (int i = 1; i <= this.ThreadNum; i++) + { + int sPos = (i - 1) * blockSize; + int ePos = i * blockSize - 1; + // 如果是最后一个,则结束位置等于最后的地方 + if (i == this.ThreadNum) + { + ePos = length; + } + new DownloadThread(conn, sPos, ePos).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; + } + + public String getUrl() + { + return url; + } + + public void setUrl(String url) + { + this.url = url; + } + + public ConnectionManager getCm() + { + return cm; + } + + public void setCm(ConnectionManager cm) + { + this.cm = cm; + } + + public int getThreadNum() + { + return ThreadNum; + } + + public void setThreadNum(int threadNum) + { + ThreadNum = threadNum; + } + + public static void main(String[] args) + throws ConnectionException, IOException + { + + String url = "http://localhost:8088/JSPDemo/test.txt"; + // ConnectionImpl ci=(ConnectionImpl)cm.open(url); + // System.out.println(new String(ci.read(2, 31))); + // File f = new File("d:\\test.txt"); + // RandomAccessFile raf = new RandomAccessFile(f, "rwd"); + // raf.seek(raf.length());// 定位当前的指针 + + FileDownloader downloader = new FileDownloader(url,3); + downloader.setConnectionManager(new ConnectionManagerImpl()); + downloader.execute(); + // int length = conn.getContentLength();// 获取文件的长度 + // System.out.println("urlConn: " + length); + // int blockSize = length / 3; + + // new DownloadThread(conn, 0, blockSize - 1).start();// 第一个线程 + // new DownloadThread(conn, blockSize, blockSize * 2 - 1).start();// 第二个线程 + // new DownloadThread(conn, blockSize * 2 , length - 1).start();// 第三个线程 + } +} diff --git a/group26/191191717/src/week3/com/coding/download/FileDownloaderTest.java b/group26/191191717/src/week3/com/coding/download/FileDownloaderTest.java new file mode 100644 index 0000000000..45cdff4b8e --- /dev/null +++ b/group26/191191717/src/week3/com/coding/download/FileDownloaderTest.java @@ -0,0 +1,66 @@ +package week3.com.coding.download; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import week3.com.coding.download.api.ConnectionManager; +import week3.com.coding.download.api.DownloadListener; +import week3.com.coding.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:8088/JSPDemo/test.txt"; + + FileDownloader downloader = new FileDownloader(url,3); + 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/group26/191191717/src/week3/com/coding/download/api/Connection.java b/group26/191191717/src/week3/com/coding/download/api/Connection.java new file mode 100644 index 0000000000..a4c14a90dd --- /dev/null +++ b/group26/191191717/src/week3/com/coding/download/api/Connection.java @@ -0,0 +1,28 @@ +package week3.com.coding.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(); +} \ No newline at end of file diff --git a/group26/191191717/src/week3/com/coding/download/api/ConnectionException.java b/group26/191191717/src/week3/com/coding/download/api/ConnectionException.java new file mode 100644 index 0000000000..9a0daa3f86 --- /dev/null +++ b/group26/191191717/src/week3/com/coding/download/api/ConnectionException.java @@ -0,0 +1,5 @@ +package week3.com.coding.download.api; + +public class ConnectionException extends Exception { + +} diff --git a/group26/191191717/src/week3/com/coding/download/api/ConnectionManager.java b/group26/191191717/src/week3/com/coding/download/api/ConnectionManager.java new file mode 100644 index 0000000000..6eae1f7256 --- /dev/null +++ b/group26/191191717/src/week3/com/coding/download/api/ConnectionManager.java @@ -0,0 +1,10 @@ +package week3.com.coding.download.api; + +public interface ConnectionManager { + /** + * 给定一个url , 打开一个连接 + * @param url + * @return + */ + public Connection open(String url) throws ConnectionException; +} diff --git a/group26/191191717/src/week3/com/coding/download/api/DownloadListener.java b/group26/191191717/src/week3/com/coding/download/api/DownloadListener.java new file mode 100644 index 0000000000..f7aea53397 --- /dev/null +++ b/group26/191191717/src/week3/com/coding/download/api/DownloadListener.java @@ -0,0 +1,6 @@ +package week3.com.coding.download.api; + +public interface DownloadListener +{ + public void notifyFinished(); +} diff --git a/group26/191191717/src/week3/com/coding/download/impl/ConnectionImpl.java b/group26/191191717/src/week3/com/coding/download/impl/ConnectionImpl.java new file mode 100644 index 0000000000..f66705b1c5 --- /dev/null +++ b/group26/191191717/src/week3/com/coding/download/impl/ConnectionImpl.java @@ -0,0 +1,70 @@ +package week3.com.coding.download.impl; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; + +import week3.com.coding.download.api.Connection; + +public class ConnectionImpl implements Connection +{ + HttpURLConnection conn; + + public ConnectionImpl() + { + } + + public ConnectionImpl(HttpURLConnection urlConn) + { + this.conn = urlConn; + } + + public HttpURLConnection getConn() + { + return conn; + } + + public void setConn(HttpURLConnection conn) + { + this.conn = conn; + } + + @Override + public byte[] read(int startPos, int endPos) + throws IOException + { + System.out.println("startPos: " + startPos + " endPos " + endPos); + conn.setRequestProperty("Range", "bytes=" + startPos + "-" + (endPos + 1)); + InputStream is = conn.getInputStream(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buff = new byte[1024]; + int len = 0; + while ((len = is.read(buff)) != -1) + { + out.write(buff, 0, len); + } + byte[] bs = out.toByteArray(); + return bs; + } + + /** + * ��ȡ���������ļ��ij��� + */ + @Override + public int getContentLength() + { + + return conn == null ? 0 : conn.getContentLength(); + } + + @Override + public void close() + { + if (conn != null) + { + conn.disconnect(); + } + } + +} diff --git a/group26/191191717/src/week3/com/coding/download/impl/ConnectionManagerImpl.java b/group26/191191717/src/week3/com/coding/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..2e9d0af24b --- /dev/null +++ b/group26/191191717/src/week3/com/coding/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,42 @@ +package week3.com.coding.download.impl; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; + +import week3.com.coding.download.api.Connection; +import week3.com.coding.download.api.ConnectionManager; + +public class ConnectionManagerImpl implements ConnectionManager +{ + /** + * ����һ��url , ��һ������ + * + * @param url + * @return + */ + @Override + public Connection open(String url) + { + Connection conn=null; + URL httpUrl = null; + HttpURLConnection urlConn = null; + try + { + httpUrl = new URL(url); + urlConn = (HttpURLConnection)httpUrl.openConnection(); + } + catch (MalformedURLException e) + { + e.printStackTrace(); + } + catch (IOException e) + { + e.printStackTrace(); + } + conn= new ConnectionImpl(urlConn); + return conn; + } + +} From a89517d30f18ec97a4c9f8d397ac9e015c7a73a0 Mon Sep 17 00:00:00 2001 From: SJsunshine Date: Tue, 28 Mar 2017 19:42:53 +0800 Subject: [PATCH 08/20] week2Update --- .../src/week2/arrayutil/ArrayUtil.java | 458 +++++++++--------- .../src/week2/litestruts/LoginAction.java | 39 -- .../src/week2/litestruts/ReflectionUtil.java | 123 ----- .../week2/litestruts/ReflectionUtilTest.java | 113 ----- .../src/week2/litestruts/Struts.java | 68 --- .../src/week2/litestruts/StrutsTest.java | 43 -- .../1515345281/src/week2/litestruts/View.java | 23 - .../src/week2/struts2/LoginAction.java | 76 +-- .../src/week2/struts2/ReflectionUtil.java | 88 ++++ .../1515345281/src/week2/struts2/Struts.java | 81 +++- .../src/week2/struts2/StrutsTest.java | 41 +- .../1515345281/src/week2/struts2/View.java | 47 +- .../week2/struts2/test/ReflectionTest.java | 110 +++++ 13 files changed, 570 insertions(+), 740 deletions(-) delete mode 100644 group26/1515345281/src/week2/litestruts/LoginAction.java delete mode 100644 group26/1515345281/src/week2/litestruts/ReflectionUtil.java delete mode 100644 group26/1515345281/src/week2/litestruts/ReflectionUtilTest.java delete mode 100644 group26/1515345281/src/week2/litestruts/Struts.java delete mode 100644 group26/1515345281/src/week2/litestruts/StrutsTest.java delete mode 100644 group26/1515345281/src/week2/litestruts/View.java create mode 100644 group26/1515345281/src/week2/struts2/ReflectionUtil.java create mode 100644 group26/1515345281/src/week2/struts2/test/ReflectionTest.java diff --git a/group26/1515345281/src/week2/arrayutil/ArrayUtil.java b/group26/1515345281/src/week2/arrayutil/ArrayUtil.java index dcc530949d..f2a8e33e6e 100644 --- a/group26/1515345281/src/week2/arrayutil/ArrayUtil.java +++ b/group26/1515345281/src/week2/arrayutil/ArrayUtil.java @@ -1,225 +1,233 @@ -package week2.arrayutil; - -import java.util.ArrayList; - -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){ - for(int i=0;i list=new ArrayList(); - int i=0; - int j=0; - while(i array2[j]){ - list.add(array2[j]); - j++; - }else{ - list.add(array1[i]); - i++; - j++; - } - } - while(i=result.length ){ - result=this.grow(result, 5); - } - result[cursor]=result[cursor-2]+result[cursor-1]; - cursor++; - } - return result; - } - - - /** - * 返回小于给定最大值max的所有素数数组 - * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] - * @param max - * @return - */ - public int[] getPrimes(int max){ - if(max<=1){ - return new int[0]; - } - if(max == 2){ - return new int[]{2}; - } - - int[] temp=new int[max]; - temp[2]=2; - int primeNum=0; - for(int i=3;i list=new ArrayList(); - for(int i=6;i list=new ArrayList(); + int i=0; + int j=0; + while(i array2[j]){ + list.add(array2[j]); + j++; + }else{ + list.add(array1[i]); + i++; + j++; + } + } + while(i=result.length ){ + result=this.grow(result, 5); + } + result[cursor]=result[cursor-2]+result[cursor-1]; + cursor++; + } + return result; + } + + + /** + * 返回小于给定最大值max的所有素数数组 + * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] + * @param max + * @return + */ + public int[] getPrimes(int max){ + if(max<=1){ + return new int[0]; + } + if(max == 2){ + return new int[]{2}; + } + + int[] temp=new int[max]; + temp[2]=2; + int primeNum=0; + for(int i=3;i list=new ArrayList(); + for(int i=6;i getSetterMethods(Class clz) { - - return getMethods(clz,"set"); - - } - - public static void setParameters(Object o, Map params) { - - List methods = getSetterMethods(o.getClass()); - - for(String name : params.keySet() ){ - - String methodName = "set" + name; - - for(Method m: methods){ - - if(m.getName().equalsIgnoreCase(methodName)){ - try { - m.invoke(o, params.get(name)); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - e.printStackTrace(); - } - } - } - } - - } - - public static List getGetterMethods(Class clz) { - return getMethods(clz,"get"); - } - - private static List getMethods(Class clz, String startWithName){ - - List methods = new ArrayList<>(); - - for(Method m : clz.getDeclaredMethods()){ - - if(m.getName().startsWith(startWithName)){ - - methods.add(m); - - } - - } - - return methods; - } - - public static Map getParamterMap(Object o) { - - Map params = new HashMap<>(); - - List methods = getGetterMethods(o.getClass()); - - for(Method m : methods){ - - String methodName = m.getName(); - String name = methodName.replaceFirst("get", "").toLowerCase(); - try { - Object value = m.invoke(o); - params.put(name, value); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - - e.printStackTrace(); - } - } - - return params; - } - - ////////////////////////Backup /////////////////////////////////// - - public static List getGetterMethods_V1(Class clz) { - - List methods = new ArrayList<>(); - - for(Method m : clz.getDeclaredMethods()){ - - if(m.getName().startsWith("get")){ - - methods.add(m); - - } - - } - - return methods; - } - - public static List getSetterMethods_V1(Class clz) { - - List methods = new ArrayList<>(); - - for(Method m : clz.getDeclaredMethods()){ - - if(m.getName().startsWith("set")){ - - methods.add(m); - - } - - } - - return methods; - - } - - - - -} diff --git a/group26/1515345281/src/week2/litestruts/ReflectionUtilTest.java b/group26/1515345281/src/week2/litestruts/ReflectionUtilTest.java deleted file mode 100644 index 8bd08063d6..0000000000 --- a/group26/1515345281/src/week2/litestruts/ReflectionUtilTest.java +++ /dev/null @@ -1,113 +0,0 @@ -package week2.litestruts; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - - - -public class ReflectionUtilTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetSetterMethod() throws Exception { - - String name = "com.coderising.litestruts.LoginAction"; - Class clz = Class.forName(name); - List methods = ReflectionUtil.getSetterMethods(clz); - - Assert.assertEquals(2, methods.size()); - - List expectedNames = new ArrayList<>(); - expectedNames.add("setName"); - expectedNames.add("setPassword"); - - Set acctualNames = new HashSet<>(); - for(Method m : methods){ - acctualNames.add(m.getName()); - } - - Assert.assertTrue(acctualNames.containsAll(expectedNames)); - } - - @Test - public void testSetParameters() throws Exception{ - - String name = "com.coderising.litestruts.LoginAction"; - Class clz = Class.forName(name); - Object o = clz.newInstance(); - - Map params = new HashMap(); - params.put("name","test"); - params.put("password","1234"); - - ReflectionUtil.setParameters(o,params); - - - - Field f = clz.getDeclaredField("name"); - f.setAccessible(true); - Assert.assertEquals("test", f.get(o)); - - f = clz.getDeclaredField("password"); - f.setAccessible(true); - Assert.assertEquals("1234", f.get(o)); - } - @Test - public void testGetGetterMethod() throws Exception{ - String name = "com.coderising.litestruts.LoginAction"; - Class clz = Class.forName(name); - List methods = ReflectionUtil.getGetterMethods(clz); - - Assert.assertEquals(3, methods.size()); - - List expectedNames = new ArrayList<>(); - expectedNames.add("getMessage"); - expectedNames.add("getName"); - expectedNames.add("getPassword"); - - Set acctualNames = new HashSet<>(); - for(Method m : methods){ - acctualNames.add(m.getName()); - } - - Assert.assertTrue(acctualNames.containsAll(expectedNames)); - } - - @Test - public void testGetParamters() throws Exception{ - String name = "com.coderising.litestruts.LoginAction"; - Class clz = Class.forName(name); - LoginAction action = (LoginAction)clz.newInstance(); - action.setName("test"); - action.setPassword("123456"); - - - - - Map params = ReflectionUtil.getParamterMap(action); - - Assert.assertEquals(3, params.size()); - - Assert.assertEquals(null, params.get("messaage") ); - Assert.assertEquals("test", params.get("name") ); - Assert.assertEquals("123456", params.get("password") ); - } -} diff --git a/group26/1515345281/src/week2/litestruts/Struts.java b/group26/1515345281/src/week2/litestruts/Struts.java deleted file mode 100644 index fa90e87fa0..0000000000 --- a/group26/1515345281/src/week2/litestruts/Struts.java +++ /dev/null @@ -1,68 +0,0 @@ -package week2.litestruts; - -import java.lang.reflect.Method; -import java.util.Map; - - - -public class Struts { - - private final static Configuration cfg = new Configuration("struts.xml"); - - 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字段中。 - - */ - - - - String clzName = cfg.getClassName(actionName); - - if(clzName == null){ - return null; - } - - try { - - Class clz = Class.forName(clzName); - Object action = clz.newInstance(); - - ReflectionUtil.setParameters(action, parameters); - - Method m = clz.getDeclaredMethod("execute"); - String resultName = (String)m.invoke(action); - - Map params = ReflectionUtil.getParamterMap(action); - String resultView = cfg.getResultView(actionName, resultName); - View view = new View(); - view.setParameters(params); - view.setJsp(resultView); - return view; - - - - } catch (Exception e) { - - e.printStackTrace(); - } - return null; - } - -} diff --git a/group26/1515345281/src/week2/litestruts/StrutsTest.java b/group26/1515345281/src/week2/litestruts/StrutsTest.java deleted file mode 100644 index d5f78939a5..0000000000 --- a/group26/1515345281/src/week2/litestruts/StrutsTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package week2.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/group26/1515345281/src/week2/litestruts/View.java b/group26/1515345281/src/week2/litestruts/View.java deleted file mode 100644 index bdd700a71c..0000000000 --- a/group26/1515345281/src/week2/litestruts/View.java +++ /dev/null @@ -1,23 +0,0 @@ -package week2.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/group26/1515345281/src/week2/struts2/LoginAction.java b/group26/1515345281/src/week2/struts2/LoginAction.java index 0a34e92f18..7bfaee9134 100644 --- a/group26/1515345281/src/week2/struts2/LoginAction.java +++ b/group26/1515345281/src/week2/struts2/LoginAction.java @@ -1,39 +1,43 @@ package week2.struts2; -/** - * 这是一个用来展示登录的业务类, 其中的用户名和密码都是硬编码的。 - * @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; - } +public class LoginAction { + private String userName; + private String password; + private String message; + + + public String excute(){ + if("沈健".equals(userName) && "123456".equals(password)){ + this.message="login successful"; + return "success"; + } + + this.message="login failed,please check your user/pwd"; + return "fail"; + } + + 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 getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + } diff --git a/group26/1515345281/src/week2/struts2/ReflectionUtil.java b/group26/1515345281/src/week2/struts2/ReflectionUtil.java new file mode 100644 index 0000000000..0c9890019b --- /dev/null +++ b/group26/1515345281/src/week2/struts2/ReflectionUtil.java @@ -0,0 +1,88 @@ +package week2.struts2; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ReflectionUtil { + + /** + * 反射赋值 + * @param o:类对象 + * @param params:用户信息 + */ + public static void setParameters(Object o, Map params){ + + List Methods=getSetterMethods(o.getClass()); + + for(String name:params.keySet()){ + + String methodName="set"+name; + + for(Method method:Methods){ + + if(method.getName().equalsIgnoreCase(methodName)){ + try { + method.invoke(o, params.get(name)); + } catch (IllegalAccessException | IllegalArgumentException + | InvocationTargetException e) { + e.printStackTrace(); + } + } + } + } + } + + public static Map getParamterMap(Object o){ + + Map params=new HashMap<>(); + + List methods=getGetterMethods(o.getClass()); + + for(Method method:methods){ + + String name=method.getName().replaceFirst("get", "").toLowerCase(); + + try { + Object object=method.invoke(o); + params.put(name, object); + } catch (IllegalAccessException | IllegalArgumentException + | InvocationTargetException e) { + e.printStackTrace(); + } + } + + return params; + } + + public static List getSetterMethods(Class clazz){ + return getMethod(clazz,"set"); + } + + public static List getGetterMethods(Class clazz){ + return getMethod(clazz,"get"); + } + + /** + *反射获取给定名开始的方法 + * @param clazz + * @param startWithName + * @return + */ + private static List getMethod(Class clazz, String startWithName) { + + List methods=new ArrayList(); + + for(Method method:clazz.getDeclaredMethods()){ + + if(method.getName().startsWith(startWithName)){ + methods.add(method); + } + } + + return methods; + } +} diff --git a/group26/1515345281/src/week2/struts2/Struts.java b/group26/1515345281/src/week2/struts2/Struts.java index 06edfe7e20..caca81418e 100644 --- a/group26/1515345281/src/week2/struts2/Struts.java +++ b/group26/1515345281/src/week2/struts2/Struts.java @@ -1,34 +1,63 @@ package week2.struts2; +import java.lang.reflect.Method; +import java.util.HashMap; 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; - } + private static final Configuration config = new Configuration("struts.xml"); + + 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字段中。 + */ + + String clazzName= config.getClassName(actionName); + if (clazzName == null) { + return null; + } + + try { + + Class clazz=Class.forName(clazzName); + Object action=clazz.newInstance(); + + ReflectionUtil.setParameters(action,parameters); + + Method method=clazz.getDeclaredMethod("excute"); + String result=(String) method.invoke(action); + + Map params=new HashMap<>(); + params=ReflectionUtil.getParamterMap(action); + + String resultView=config.getResultView(actionName, result); + + View view=new View(); + view.setJsp(resultView); + view.setParameters(params); + + return view; + + } catch (Exception e) { + e.printStackTrace(); + } + + return null; + } } diff --git a/group26/1515345281/src/week2/struts2/StrutsTest.java b/group26/1515345281/src/week2/struts2/StrutsTest.java index 68ec3ee4b4..376f7fd431 100644 --- a/group26/1515345281/src/week2/struts2/StrutsTest.java +++ b/group26/1515345281/src/week2/struts2/StrutsTest.java @@ -1,5 +1,7 @@ package week2.struts2; +import static org.junit.Assert.*; + import java.util.HashMap; import java.util.Map; @@ -11,30 +13,27 @@ 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")); + String actionName="login"; + Map params=new HashMap<>(); + + params.put("userName", "沈健"); + params.put("password", "123456"); + + View view=Struts.runAction(actionName, params); + assertEquals("/jsp/homepage.jsp", view.getJsp()); + 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")); + String actionName="login"; + Map params=new HashMap<>(); + + params.put("name", "沈健"); + params.put("password", "1234565"); + + View view=Struts.runAction(actionName, params); + assertEquals("/jsp/showLogin.jsp", view.getJsp()); + assertEquals("login failed,please check your user/pwd", view.getParameters().get("message")); } } diff --git a/group26/1515345281/src/week2/struts2/View.java b/group26/1515345281/src/week2/struts2/View.java index 5a907a455f..6cab04468f 100644 --- a/group26/1515345281/src/week2/struts2/View.java +++ b/group26/1515345281/src/week2/struts2/View.java @@ -1,23 +1,24 @@ -package week2.struts2; - -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; - } -} +package week2.struts2; + +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/group26/1515345281/src/week2/struts2/test/ReflectionTest.java b/group26/1515345281/src/week2/struts2/test/ReflectionTest.java new file mode 100644 index 0000000000..44bebb2343 --- /dev/null +++ b/group26/1515345281/src/week2/struts2/test/ReflectionTest.java @@ -0,0 +1,110 @@ +package week2.struts2.test; + +import static org.junit.Assert.*; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import week2.struts2.LoginAction; +import week2.struts2.ReflectionUtil; + +public class ReflectionTest { + + @Test + public void testGetSetterMethods() throws ClassNotFoundException { + + String clazzName = "week2.struts2.LoginAction"; + + Class clazz = Class.forName(clazzName); + + List methods = ReflectionUtil.getSetterMethods(clazz); + + assertEquals(3, methods.size()); + + List expectedNames = new ArrayList(); + expectedNames.add("setUserName"); + expectedNames.add("setPassword"); + expectedNames.add("setMessage"); + + Set actualsNames = new HashSet<>(); + for (Method m : methods) { + actualsNames.add(m.getName()); + } + + assertTrue(actualsNames.containsAll(expectedNames)); + } + + @Test + public void testGetGetterMethods() throws ClassNotFoundException { + + String clazzName = "week2.struts2.LoginAction"; + Class clazz = Class.forName(clazzName); + List methods = ReflectionUtil.getGetterMethods(clazz); + + assertEquals(3, methods.size()); + + List expectedNames = new ArrayList<>(); + expectedNames.add("getUserName"); + expectedNames.add("getPassword"); + expectedNames.add("getMessage"); + + Set actualNames = new HashSet<>(); + for (Method m : methods) { + actualNames.add(m.getName()); + } + + assertTrue(actualNames.containsAll(expectedNames)); + } + + @Test + public void testSetParameters() throws Exception { + + String clazzName = "week2.struts2.LoginAction"; + Class clazz = Class.forName(clazzName); + + Object o = clazz.newInstance(); + Map params = new HashMap<>(); + params.put("userName", "沈健"); + params.put("password", "123456"); + + ReflectionUtil.setParameters(o, params); + + Field userName = clazz.getDeclaredField("userName"); + userName.setAccessible(true); + assertEquals(userName.get(o), "沈健"); + + Field password = clazz.getDeclaredField("password"); + password.setAccessible(true); + assertEquals(password.get(o), "123456"); + + } + + @Test + public void testGetParameterMap() throws Exception { + + String clazzName = "week2.struts2.LoginAction"; + Class clazz = Class.forName(clazzName); + LoginAction action = (LoginAction) clazz.newInstance(); + action.setUserName("沈健"); + action.setPassword("123456"); + + Map params = ReflectionUtil.getParamterMap(action); + + Assert.assertEquals(3, params.size()); + + Assert.assertEquals(null, params.get("messaage")); + Assert.assertEquals("沈健", params.get("username")); + Assert.assertEquals("123456", params.get("password")); + } + +} From 9311ccd99eb516eab3e03691a73416d5777c1e5f Mon Sep 17 00:00:00 2001 From: MAC Date: Tue, 28 Mar 2017 22:17:46 +0800 Subject: [PATCH 09/20] week04 lru commit --- .../src/week04/source/LRUPageFrame.java | 159 ++++++++++++++++++ .../src/week04/test/TestLRUPageFrame.java | 32 ++++ 2 files changed, 191 insertions(+) create mode 100644 group26/89460886/src/week04/source/LRUPageFrame.java create mode 100644 group26/89460886/src/week04/test/TestLRUPageFrame.java diff --git a/group26/89460886/src/week04/source/LRUPageFrame.java b/group26/89460886/src/week04/source/LRUPageFrame.java new file mode 100644 index 0000000000..44b7ad7a45 --- /dev/null +++ b/group26/89460886/src/week04/source/LRUPageFrame.java @@ -0,0 +1,159 @@ +package list; + +/** + * @author jiaxun + */ +public class LRUPageFrame { + + private int capacity; + private Node first; + private Node last; + private int size = 0; + + public LRUPageFrame(int capacity) { + this.capacity = capacity; + } + + public void access(int pageNum) { + if (size < capacity) { + addFirst(pageNum); + } else { + Node node = searchNode(pageNum); + if (node == null) { + removeLast(); + addFirst(pageNum); + } else { + if (node.getData() == first.getData()) return; + if (node.getData() == last.getData()) { + last = node.getPrev(); + node.getPrev().setNext(null); + node.setPrev(null); + node.setNext(first); + first.setPrev(node); + first = node; + } else { + node.getPrev().setNext(node.getNext()); + node.getNext().setPrev(node.getPrev()); + node.setNext(first); + node.setPrev(null); + first = node; + } + } + } + } + + public Node searchNode(int pageNum) { + Node curr = first; + while (curr != null) { + if (curr.getData() == pageNum) { + return curr; + } + curr = curr.getNext(); + } + return null; + } + + public void addFirst(int data) { + Node node = new Node(data); + if (first == null) { + first = node; + } else if (last == null) { + last = first; + first = node; + first.setNext(last); + last.setPrev(first); + } else { + node.setNext(first); + first.setPrev(node); + first = node; + } + size++; + } + + public void addLast(int data) { + Node node = new Node(data); + if (first == null) { + first = node; + } else if (last == null) { + last = node; + first.setNext(last); + last.setPrev(first); + } else { + node.setPrev(last); + last.setNext(node); + last = node; + } + size++; + } + + public void removeLast() { + if (last != null && last.getPrev() != null) { + Node prev = last.getPrev(); + last.getPrev().setNext(null); + last = prev.getData() == first.getData() ? null : last.getPrev(); + } else if (first != null) { + first = null; + } + if (size > 0) { + size--; + } + } + + public int size() { + return size; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + Node curr = first; + while (curr != null) { + builder.append(curr.getData()); + if (curr.getNext() != null) { + builder.append(","); + } + curr = curr.getNext(); + } + return builder.toString(); + } + + private static class Node { + + private int data; + private Node prev; + private Node next; + + public Node(int data) { + this.data = data; + } + + public int getData() { + return data; + } + + public void setData(int data) { + this.data = data; + } + + public Node getPrev() { + return prev; + } + + public void setPrev(Node prev) { + this.prev = prev; + } + + public Node getNext() { + return next; + } + + public void setNext(Node next) { + this.next = next; + } + + @Override + public String toString() { + return "[data is " + data + "]"; + } + } +} diff --git a/group26/89460886/src/week04/test/TestLRUPageFrame.java b/group26/89460886/src/week04/test/TestLRUPageFrame.java new file mode 100644 index 0000000000..a82a2512ac --- /dev/null +++ b/group26/89460886/src/week04/test/TestLRUPageFrame.java @@ -0,0 +1,32 @@ +package list; + +import org.junit.Assert; +import org.junit.Test; + +/** + * @author jiaxun + */ +public class TestLRUPageFrame { + + @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()); + } + +} From 4d4f2a54a049fb40060f95d531da0df4d95bb415 Mon Sep 17 00:00:00 2001 From: Macx Date: Fri, 31 Mar 2017 02:04:38 +0800 Subject: [PATCH 10/20] jvm --- .../723161901/jvm/loader/ClassFileLoader.java | 63 +++++++++++++ .../jvm/test/ClassFileloaderTest.java | 94 +++++++++++++++++++ group26/723161901/jvm/test/EmployeeV1.java | 28 ++++++ 3 files changed, 185 insertions(+) create mode 100644 group26/723161901/jvm/loader/ClassFileLoader.java create mode 100644 group26/723161901/jvm/test/ClassFileloaderTest.java create mode 100644 group26/723161901/jvm/test/EmployeeV1.java diff --git a/group26/723161901/jvm/loader/ClassFileLoader.java b/group26/723161901/jvm/loader/ClassFileLoader.java new file mode 100644 index 0000000000..a87ca911dd --- /dev/null +++ b/group26/723161901/jvm/loader/ClassFileLoader.java @@ -0,0 +1,63 @@ +package com.jvm.loader; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class ClassFileLoader { + + private List clzPaths = new ArrayList(); + + public byte[] readBinaryCode(String className) throws IOException { + File f = new File(clzPaths.get(0)+File.separatorChar+className+".class"); + if(!f.exists()){ + throw new FileNotFoundException("File not found"); + } + ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length()); + BufferedInputStream in = null; + try { + in = new BufferedInputStream(new FileInputStream(f)); + int buf_size = 1024; + byte[] buffer = new byte[buf_size]; + int len = 0; + while(-1 != (len = in.read(buffer, 0, buf_size))){ + bos.write(buffer, 0, len); + } + return bos.toByteArray(); + } catch (Exception e) { + e.printStackTrace(); + }finally { + try { + in.close(); + } catch (Exception e2) { + e2.printStackTrace(); + } + bos.close(); + } + return null; + } + + + public void addClassPath(String path) { + clzPaths.add(path); + } + + + + public String getClassPath(){ + String results = ""; + for (int i = 0; i < clzPaths.size(); i++) { + results += clzPaths.get(i); + if(i!=clzPaths.size()-1){ + results += ";"; + } + } + return results; + } + +} diff --git a/group26/723161901/jvm/test/ClassFileloaderTest.java b/group26/723161901/jvm/test/ClassFileloaderTest.java new file mode 100644 index 0000000000..bd835c3857 --- /dev/null +++ b/group26/723161901/jvm/test/ClassFileloaderTest.java @@ -0,0 +1,94 @@ +package com.jvm.test; + +import java.io.IOException; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.jvm.loader.ClassFileLoader; + + + + + +public class ClassFileloaderTest { + + + static String path1 = "/Users/Macx/Workspaces/coding2017/mini-jvm/bin/com/jvm/test"; + static String path2 = "/Users/Macx/Workspaces/coding2017/mini-jvm/bin/com/jvm/temp"; + + + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testClassPath(){ + + ClassFileLoader loader = new ClassFileLoader(); + loader.addClassPath(path1); + loader.addClassPath(path2); + + String clzPath = loader.getClassPath(); + + Assert.assertEquals(path1+";"+path2,clzPath); + + } + + @Test + public void testClassFileLength() throws IOException { + + ClassFileLoader loader = new ClassFileLoader(); + loader.addClassPath(path1); + + String className = "EmployeeV1"; + + byte[] byteCodes = loader.readBinaryCode(className); + + // 注意:这个字节数可能和你的JVM版本有关系, 你可以看看编译好的类到底有多大 + Assert.assertEquals(1034, byteCodes.length); + + } + + + @Test + public void testMagicNumber() throws IOException{ + ClassFileLoader loader = new ClassFileLoader(); + loader.addClassPath(path1); + String className = "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 ){ + StringBuffer buffer = new StringBuffer(); + for(int i=0;i Date: Fri, 31 Mar 2017 16:37:51 +0800 Subject: [PATCH 11/20] =?UTF-8?q?=E8=A1=A5=E4=BA=A4=E7=AC=AC=E4=B8=89?= =?UTF-8?q?=E6=AC=A1=E4=BD=9C=E4=B8=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 完成多线程下载 --- .../homework/third/basic/LRUPageFameTest.java | 32 +++++ .../homework/third/basic/LRUPageFrame.java | 63 +++++++++ .../homework/third/basic/LinkedList.java | 125 ++++++++++++++++++ .../third/download/DownloadThread.java | 51 +++++++ .../third/download/FileDownloader.java | 86 ++++++++++++ .../third/download/FileDownloaderTest.java | 58 ++++++++ .../third/download/api/Connection.java | 28 ++++ .../download/api/ConnectionException.java | 12 ++ .../third/download/api/ConnectionManager.java | 16 +++ .../third/download/api/DownloadListener.java | 5 + .../third/download/impl/ConnectionImpl.java | 97 ++++++++++++++ .../download/impl/ConnectionManagerImpl.java | 54 ++++++++ .../third/download/utils/HttpUtil.java | 24 ++++ 13 files changed, 651 insertions(+) create mode 100644 group26/lizhy2017/homework/third/basic/LRUPageFameTest.java create mode 100644 group26/lizhy2017/homework/third/basic/LRUPageFrame.java create mode 100644 group26/lizhy2017/homework/third/basic/LinkedList.java create mode 100644 group26/lizhy2017/homework/third/download/DownloadThread.java create mode 100644 group26/lizhy2017/homework/third/download/FileDownloader.java create mode 100644 group26/lizhy2017/homework/third/download/FileDownloaderTest.java create mode 100644 group26/lizhy2017/homework/third/download/api/Connection.java create mode 100644 group26/lizhy2017/homework/third/download/api/ConnectionException.java create mode 100644 group26/lizhy2017/homework/third/download/api/ConnectionManager.java create mode 100644 group26/lizhy2017/homework/third/download/api/DownloadListener.java create mode 100644 group26/lizhy2017/homework/third/download/impl/ConnectionImpl.java create mode 100644 group26/lizhy2017/homework/third/download/impl/ConnectionManagerImpl.java create mode 100644 group26/lizhy2017/homework/third/download/utils/HttpUtil.java diff --git a/group26/lizhy2017/homework/third/basic/LRUPageFameTest.java b/group26/lizhy2017/homework/third/basic/LRUPageFameTest.java new file mode 100644 index 0000000000..32bf061852 --- /dev/null +++ b/group26/lizhy2017/homework/third/basic/LRUPageFameTest.java @@ -0,0 +1,32 @@ +package third.basic; + +import org.junit.Assert; +import org.junit.Test; + +/** + * ${} + * Created by spark_lizhy on 2017/3/31. + */ + +public class LRUPageFameTest { + @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()); + } +} diff --git a/group26/lizhy2017/homework/third/basic/LRUPageFrame.java b/group26/lizhy2017/homework/third/basic/LRUPageFrame.java new file mode 100644 index 0000000000..29fa687bba --- /dev/null +++ b/group26/lizhy2017/homework/third/basic/LRUPageFrame.java @@ -0,0 +1,63 @@ +package third.basic; + +/** + * ${} + * Created by spark_lizhy on 2017/3/31. + */ +/** + * 用双向链表实现 LRU 算法 + * @author liuxin + * + */ +public class LRUPageFrame { + + private static class Node { + + Node prev; + Node next; + int pageNum; + + Node() { + } + } + + private int capacity; + + + private Node first;// 链表头 + private Node last;// 链表尾 + + + public LRUPageFrame(int capacity) { + + this.capacity = capacity; + + } + + /** + * 获取缓存中对象 + * + * @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/group26/lizhy2017/homework/third/basic/LinkedList.java b/group26/lizhy2017/homework/third/basic/LinkedList.java new file mode 100644 index 0000000000..b011033258 --- /dev/null +++ b/group26/lizhy2017/homework/third/basic/LinkedList.java @@ -0,0 +1,125 @@ +package third.basic; + +/** + * ${} + * Created by spark_lizhy on 2017/3/31. + */ + +public class LinkedList { + + 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/group26/lizhy2017/homework/third/download/DownloadThread.java b/group26/lizhy2017/homework/third/download/DownloadThread.java new file mode 100644 index 0000000000..9fa8cb2659 --- /dev/null +++ b/group26/lizhy2017/homework/third/download/DownloadThread.java @@ -0,0 +1,51 @@ +package third.download; + + +import java.io.IOException; +import java.io.RandomAccessFile; + +import third.download.api.Connection; +import third.download.api.ConnectionException; +import third.download.api.DownloadListener; + +public class DownloadThread extends Thread { + + private RandomAccessFile accessFile; + private DownloadListener listener; + private Connection conn; + private int startPos; + private int endPos; + + public DownloadThread(Connection conn, int startPos, int endPos, DownloadListener listener) { + this.listener = listener; + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + + } + + public void run() { + try { + byte[] bytes = conn.read(startPos, endPos); + accessFile = new RandomAccessFile("./" + conn.getFileName(), "rw"); + accessFile.seek(startPos); + accessFile.write(bytes); + } catch (IOException e) { + e.printStackTrace(); + } catch (ConnectionException e) { + e.printStackTrace(); + } finally { + if (null != accessFile) + try { + accessFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + if (null != conn) + conn.close(); + if (null != listener) + listener.notifyFinished(); + } + } +} diff --git a/group26/lizhy2017/homework/third/download/FileDownloader.java b/group26/lizhy2017/homework/third/download/FileDownloader.java new file mode 100644 index 0000000000..498b09ee97 --- /dev/null +++ b/group26/lizhy2017/homework/third/download/FileDownloader.java @@ -0,0 +1,86 @@ +package third.download; + +import java.util.concurrent.atomic.AtomicInteger; + +import third.download.api.Connection; +import third.download.api.ConnectionException; +import third.download.api.ConnectionManager; +import third.download.api.DownloadListener; + + +public class FileDownloader { + private final static int THREAD_NUM=15; + private String url; + private DownloadListener listener; + private ConnectionManager cm; + private AtomicInteger atomicInteger=new AtomicInteger(); + + 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 { + int length = cm.getContentLength(url); + int perTread_lenth=length/THREAD_NUM; + int redundant=length%THREAD_NUM; + for (int i=0;i Date: Fri, 31 Mar 2017 17:33:18 +0800 Subject: [PATCH 12/20] 3.31 --- .../week3/linkedlist/MyLinkedLists.java | 272 ++++++++++++++++++ .../week3/{ => thread}/DownloadThread.java | 38 +-- .../week3/{ => thread}/FileDownload.java | 34 +-- .../week3/{ => thread}/ThreadDownload.java | 6 +- ...1\351\201\223\347\254\224\350\256\260.txt" | 3 + 5 files changed, 315 insertions(+), 38 deletions(-) create mode 100644 group26/2441547139/week3/linkedlist/MyLinkedLists.java rename group26/2441547139/week3/{ => thread}/DownloadThread.java (67%) rename group26/2441547139/week3/{ => thread}/FileDownload.java (61%) rename group26/2441547139/week3/{ => thread}/ThreadDownload.java (94%) create mode 100644 "group26/2441547139/\346\234\211\351\201\223\347\254\224\350\256\260.txt" diff --git a/group26/2441547139/week3/linkedlist/MyLinkedLists.java b/group26/2441547139/week3/linkedlist/MyLinkedLists.java new file mode 100644 index 0000000000..dfd299dae6 --- /dev/null +++ b/group26/2441547139/week3/linkedlist/MyLinkedLists.java @@ -0,0 +1,272 @@ +package week3.linkedlist; + +import java.util.Iterator; + +/** + * Created by zndbl on 2017/3/29. + */ +public class MyLinkedLists { + + private Node head; + private int size; + + /** + * 删除第一个 + * + * @return + */ + public Node removeFirst() { + Node node = head; + head = node.getNext(); + size--; + return node; + } + + /** + * 删除最后一个 + * + * @return + */ + public Node removeLast() { + Node node = head; + Node pre = null; + while (node != null) { + pre = node; + node = node.getNext(); + } + pre.setNext(null); + size--; + return pre; + } + + /** + * 新增节点在第一个 + * + * @param data + */ + public void addFirst(Object data) { + Node node = new Node(data); + node.setNext(head); + head = node; + size++; + } + + /** + * 得到指定索引的节点 + * + * @param index + * @return + */ + public Node getNode(int index) { + index++; + Node node = null; + for (int i = 0; i < index; i++) { + node = head; + node = node.getNext(); + } + return head; + } + + /** + * 删除指定索引的节点 + * + * @param index + * @return + */ + public Node removeNode(int index) { + Node prevNode = getNode(index--); + Node currNode = getNode(index); + Node succNode = currNode.getNext(); + prevNode.setNext(succNode); + currNode = null; + size--; + return succNode; + } + + /** + * 在最后添加一个节点 + * + * @return + */ + public Node addLast(Object data) { + Node node = new Node(data); + Node curr = head; + Node succ = null; + while (curr != null) { + succ = curr; + curr = curr.getNext(); + } + succ.setNext(node); + size++; + return node; + } + + /** + * 在指定索引增加 + * + * @param index + * @param obj + */ + public void add(int index, Object obj) { + Node curr = head; + Node prev = null; + while (curr != null) { + if (index == 0) { + break; + } + prev = curr; + curr = curr.getNext(); + index--; + } + if (prev != null) { + Node node = new Node(obj); + node.setNext(curr); + prev.setNext(node); + } + } + + /** + * 得到大小 + * + * @return + */ + public int size() { + return size; + } + + /** + * 得到迭代器 + * + * @return + */ + public Iterator iterator() { + return new MyLinkedListsIterator(this); + } + + /** + * 反转节点 + */ + public void reverse() { + Node prev = null; + Node next = null; + Node curr = head; + while (curr != null) { + next = curr.getNext(); + curr.setNext(prev); + prev = curr; + curr = next; + } + head = prev; + } + + /** + * 链表头一半删除 + */ + public void removeFirstHalf() { + Node curr = head; + int half = size / 2; + while (half != 0) { + curr = curr.getNext(); + half--; + } + head = curr; + } + + /** + * 指定索引,指定长度的删除 + * + * @param i + * @param length + */ + public void remove(int i, int length) { + if (i + length >= size - 1) { + length = size - 1 - i; + } + int count = i; + Node pre = null; + Node curr = head; + while (curr != null) { + if (count == 0) { + break; + } + pre = curr; + curr = curr.getNext(); + count--; + } + while (curr != null) { + if (length == 0) { + break; + } + curr = curr.getNext(); + length--; + } + pre.setNext(curr.getNext()); + + } + + /** + * 打印方法 + * @return + */ + public String toString() { + StringBuilder builder = new StringBuilder(); + Node current = head; + while (current == null) { + builder.append(current.toString()); + current = current.getNext(); + } + return builder.toString(); + } + + private class MyLinkedListsIterator implements Iterator { + + private MyLinkedLists linkedList; + private int length = 0; + + public MyLinkedListsIterator(MyLinkedLists linkedList) { + this.linkedList = linkedList; + } + + @Override + public boolean hasNext() { + return length < size; + } + + @Override + public Object next() { + return linkedList.getNode(length++); + } + + @Override + public void remove() { + linkedList.removeNode(length--); + } + } + + + public static class Node { + + private Object data; + private Node next; + + public Node(Object data) { + this.data = data; + } + + public void setNext(Node next) { + this.next = next; + } + + public Node getNext() { + return next; + } + + public Object getData() { + return this.data; + } + + public String toString() { + return "data = "+data; + } + } +} diff --git a/group26/2441547139/week3/DownloadThread.java b/group26/2441547139/week3/thread/DownloadThread.java similarity index 67% rename from group26/2441547139/week3/DownloadThread.java rename to group26/2441547139/week3/thread/DownloadThread.java index c0d0065021..f6ea4ae09f 100644 --- a/group26/2441547139/week3/DownloadThread.java +++ b/group26/2441547139/week3/thread/DownloadThread.java @@ -1,4 +1,4 @@ -package week3; +package week3.thread; import java.io.File; import java.io.IOException; @@ -8,9 +8,6 @@ import java.net.URL; import java.util.concurrent.CountDownLatch; -/** - * Created by zndbl on 2017/3/27. - */ public class DownloadThread extends Thread { private File file; @@ -19,7 +16,9 @@ public class DownloadThread extends Thread { private int startPos; private int endPos; - public DownloadThread(File file, CountDownLatch countDownLatch, String address, int startPos, int endPos ) { + public DownloadThread(File file, CountDownLatch countDownLatch, + String address, int startPos, int endPos) { + super(); this.file = file; this.countDownLatch = countDownLatch; this.address = address; @@ -29,27 +28,34 @@ public DownloadThread(File file, CountDownLatch countDownLatch, String address, public void run() { Thread current = Thread.currentThread(); - System.out.println(current.getName() + "开始下载" + startPos + "_" + endPos); + System.out.println(current.getName() + "开始下载:" + startPos + "-" + + endPos); RandomAccessFile randomAccessFile = null; InputStream inputStream = null; try { URL url = new URL(address); - HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); - httpURLConnection.setRequestProperty("Range", "bytes=" + startPos + "_" + endPos); + HttpURLConnection httpURLConnection = (HttpURLConnection) url + .openConnection(); + httpURLConnection.setRequestProperty("Range", "bytes=" + startPos + + "-" + endPos); inputStream = httpURLConnection.getInputStream(); randomAccessFile = new RandomAccessFile(file, "rw"); randomAccessFile.seek(startPos); byte[] bytes = new byte[1024]; - int length = 0; - while ((length = inputStream.read(bytes)) != -1) { - randomAccessFile.write(bytes, 0, length); + int read = 0; + while ((read = inputStream.read(bytes)) != -1) { + randomAccessFile.write(bytes, 0, read); } - } catch (Exception e) { + } catch (IOException e) { e.printStackTrace(); } finally { try { - randomAccessFile.close(); - inputStream.close(); + if (randomAccessFile != null) { + randomAccessFile.close(); + } + if (inputStream != null) { + inputStream.close(); + } } catch (IOException e) { e.printStackTrace(); } @@ -58,6 +64,4 @@ public void run() { } } - - -} +} \ No newline at end of file diff --git a/group26/2441547139/week3/FileDownload.java b/group26/2441547139/week3/thread/FileDownload.java similarity index 61% rename from group26/2441547139/week3/FileDownload.java rename to group26/2441547139/week3/thread/FileDownload.java index 7cd939a753..7dd7df1a28 100644 --- a/group26/2441547139/week3/FileDownload.java +++ b/group26/2441547139/week3/thread/FileDownload.java @@ -1,14 +1,11 @@ -package week3; +package week3.thread; import java.io.File; -import java.io.RandomAccessFile; +import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.concurrent.CountDownLatch; -/** - * Created by zndbl on 2017/3/27. - */ public class FileDownload { private String address; @@ -20,34 +17,37 @@ public FileDownload(String address) { public void download(int threadCount) { try { URL url = new URL(address); - HttpURLConnection HttpurlConnection = (HttpURLConnection) url.openConnection(); - int length = HttpurlConnection.getContentLength(); - System.out.println("文件大小"+length); + HttpURLConnection httpURLConnection = (HttpURLConnection) url + .openConnection(); + int length = httpURLConnection.getContentLength(); + System.out.println("文件大小:"+length); File file = new File("D:\\download.jpg"); - RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); - randomAccessFile.setLength(length); - randomAccessFile.close(); CountDownLatch countDownLatch = new CountDownLatch(threadCount); + // 计算每个线程下载的数据大小 int blockSize = length / threadCount; - for (int i = 0; i < threadCount ; i++) { + for (int i = 0; i < threadCount; i++) { int startPos = blockSize * i; int endPos = blockSize * (i + 1); - if(i == threadCount - 1) { + if (i == threadCount - 1) { + //最后一个下载剩下的 endPos = length; } - new DownloadThread(file, countDownLatch, address, startPos, endPos - 1).start(); + new DownloadThread(file, countDownLatch, address, startPos, + endPos - 1).start(); } while (countDownLatch.getCount() != 0) { - System.out.println("下载中"); + System.out.println("下载中...."); try { + // 休眠 Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("下载完成"); - } catch (Exception e) { + } catch (IOException e) { e.printStackTrace(); } } -} + +} \ No newline at end of file diff --git a/group26/2441547139/week3/ThreadDownload.java b/group26/2441547139/week3/thread/ThreadDownload.java similarity index 94% rename from group26/2441547139/week3/ThreadDownload.java rename to group26/2441547139/week3/thread/ThreadDownload.java index c760844225..7e09e4f843 100644 --- a/group26/2441547139/week3/ThreadDownload.java +++ b/group26/2441547139/week3/thread/ThreadDownload.java @@ -1,4 +1,4 @@ -package week3; +package week3.thread; /** * Created by zndbl on 2017/3/26. @@ -23,7 +23,7 @@ public static void main(String[] args) { // bufferedOutputStream.write(buffer, 0, len); // bufferedOutputStream.flush(); // } -// } catch (Exception e) { +// } catch (Exception e) {ScheduledThreadPoolExecutor // e.printStackTrace(); // } @@ -31,7 +31,5 @@ public static void main(String[] args) { String url = "http://wx.qlogo.cn/mmopen/fqCl7qHPjf2JaKGXwqRe3WoMwnBouoSNG2Xd3kYAcfLEmibXEpZH9HVDyDiassfPgiav8kx9wNDypGxaibxdQFIXzIhib2N2ibuo07/0"; FileDownload fileDownload = new FileDownload(url); fileDownload.download(3); - - } } diff --git "a/group26/2441547139/\346\234\211\351\201\223\347\254\224\350\256\260.txt" "b/group26/2441547139/\346\234\211\351\201\223\347\254\224\350\256\260.txt" new file mode 100644 index 0000000000..31173ac162 --- /dev/null +++ "b/group26/2441547139/\346\234\211\351\201\223\347\254\224\350\256\260.txt" @@ -0,0 +1,3 @@ +http://note.youdao.com/noteshare?id=63cfdc5e194deb6458f9733681088516 ���� +http://note.youdao.com/noteshare?id=3078d5c9a9f86e590973ee40ba3fdb25 ��������������� +http://note.youdao.com/noteshare?id=8fb7ea6223b152c647f09dc98882751b lucene�򵥽��� From 72a0198637ae6747d3fe567d531fe031aaf0b4ff Mon Sep 17 00:00:00 2001 From: SJsunshine Date: Sat, 1 Apr 2017 13:16:24 +0800 Subject: [PATCH 13/20] week3redo --- .../src/week3/download/DownloadThread.java | 57 +++ .../src/week3/download/FileDownloader.java | 106 +++++ .../week3/download/FileDownloaderTest.java | 0 .../src/week3/download/api/Connection.java | 25 ++ .../download/api/ConnectionException.java | 8 + .../week3/download/api/ConnectionManager.java | 12 + .../week3/download/api/DownloadListener.java | 6 + .../download/api/impl/ConnectionImpl.java | 81 ++++ .../api/impl/ConnectionManagerImpl.java | 17 + .../week3/download/test/ConnectionTest.java | 52 +++ .../download/test/FileDownloaderTest.java | 43 +++ .../1515345281/src/week3/list/Iterator.java | 5 + .../1515345281/src/week3/list/LinkedList.java | 363 ++++++++++++++++++ .../src/week3/list/LinkedListTest.java | 201 ++++++++++ group26/1515345281/src/week3/list/List.java | 14 + .../1515345281/src/week3/list/ListUtils.java | 9 + 16 files changed, 999 insertions(+) create mode 100644 group26/1515345281/src/week3/download/DownloadThread.java delete mode 100644 group26/1515345281/src/week3/download/FileDownloaderTest.java create mode 100644 group26/1515345281/src/week3/download/api/Connection.java create mode 100644 group26/1515345281/src/week3/download/api/ConnectionException.java create mode 100644 group26/1515345281/src/week3/download/api/ConnectionManager.java create mode 100644 group26/1515345281/src/week3/download/api/DownloadListener.java create mode 100644 group26/1515345281/src/week3/download/api/impl/ConnectionImpl.java create mode 100644 group26/1515345281/src/week3/download/api/impl/ConnectionManagerImpl.java create mode 100644 group26/1515345281/src/week3/download/test/ConnectionTest.java create mode 100644 group26/1515345281/src/week3/download/test/FileDownloaderTest.java create mode 100644 group26/1515345281/src/week3/list/Iterator.java create mode 100644 group26/1515345281/src/week3/list/LinkedList.java create mode 100644 group26/1515345281/src/week3/list/LinkedListTest.java create mode 100644 group26/1515345281/src/week3/list/List.java create mode 100644 group26/1515345281/src/week3/list/ListUtils.java diff --git a/group26/1515345281/src/week3/download/DownloadThread.java b/group26/1515345281/src/week3/download/DownloadThread.java new file mode 100644 index 0000000000..21e29bac91 --- /dev/null +++ b/group26/1515345281/src/week3/download/DownloadThread.java @@ -0,0 +1,57 @@ +package week3.download; + +import java.io.IOException; +import java.io.RandomAccessFile; +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CyclicBarrier; + +import week3.download.api.Connection; + +public class DownloadThread extends Thread { + + Connection conn; + int startPos; + int endPos; + String localFile; + // 它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point)。 + // 在涉及一组固定大小的线程的程序中,这些线程必须不时地互相等待 + CyclicBarrier barrier; + + public DownloadThread(Connection conn, int startPos, int endPos, + String localFile, CyclicBarrier barrier) { + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + this.localFile = localFile; + this.barrier = barrier; + } + + @Override + public void run() { + + System.out.println("Begin to read [" + startPos + "-" + endPos + "]"); + + try { + byte[] data = conn.read(startPos, endPos); + + RandomAccessFile file = new RandomAccessFile(localFile, "rw"); + + file.seek(startPos); + + file.write(data); + + file.close(); + + conn.close(); + + barrier.await();//等待别的线程完成 + + } catch (IOException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (BrokenBarrierException e) { + e.printStackTrace(); + } + } +} diff --git a/group26/1515345281/src/week3/download/FileDownloader.java b/group26/1515345281/src/week3/download/FileDownloader.java index e69de29bb2..467c95843a 100644 --- a/group26/1515345281/src/week3/download/FileDownloader.java +++ b/group26/1515345281/src/week3/download/FileDownloader.java @@ -0,0 +1,106 @@ +package week3.download; + +import java.net.URL; +import java.util.concurrent.CyclicBarrier; + +import week3.download.api.Connection; +import week3.download.api.ConnectionException; +import week3.download.api.ConnectionManager; +import week3.download.api.DownloadListener; +import week3.download.api.impl.ConnectionManagerImpl; + +public class FileDownloader { + + private String url; + private String localFile; + private static final int DOWNLOAD_THREAD_NUM = 6; + + private DownloadListener listener; + + public FileDownloader(String url, String localFile) { + this.url = url; + this.localFile = localFile; + } + + 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方法 + + // 下面的代码是示例代码, 也就是说只有一个线程, 你需要改造成多线程的。 + + CyclicBarrier barrier = new CyclicBarrier(DOWNLOAD_THREAD_NUM, + new Runnable() { + @Override + public void run() { + listener.notifyFinished(); + } + }); + + ConnectionManager connManager = new ConnectionManagerImpl(); + + Connection conn = null; + + try { + conn = connManager.open(url); + int totalLen = conn.getContentLength(); + + int[][] range=allocateDownloadRange(DOWNLOAD_THREAD_NUM,totalLen); + + for (int i = 0; i < DOWNLOAD_THREAD_NUM; i++) { + + DownloadThread thread = new DownloadThread(connManager.open(url), range[i][0], + range[i][1], localFile, barrier); + + thread.start(); + } + + } catch (ConnectionException e) { + e.printStackTrace(); + } finally { + if (conn != null) { + conn.close(); + } + } + } + + private int[][] allocateDownloadRange(int threadNum,int totalLen){ + + int[][] range=new int[threadNum][2]; + + int eachThreadSize=totalLen/threadNum; + + int left=totalLen%threadNum;//剩余的由最后一个线程处理 + + for(int i=0;i totalLen){ + byte[] data=baos.toByteArray(); + return Arrays.copyOf(data, totalLen); + } + + return baos.toByteArray(); + } + +} diff --git a/group26/1515345281/src/week3/download/api/impl/ConnectionManagerImpl.java b/group26/1515345281/src/week3/download/api/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..47bfcc62d0 --- /dev/null +++ b/group26/1515345281/src/week3/download/api/impl/ConnectionManagerImpl.java @@ -0,0 +1,17 @@ +package week3.download.api.impl; + +import java.io.IOException; + +import week3.download.api.Connection; +import week3.download.api.ConnectionException; +import week3.download.api.ConnectionManager; + +public class ConnectionManagerImpl implements ConnectionManager { + + @Override + public Connection open(String url) throws ConnectionException { + + return new ConnectionImpl(url); + } + +} diff --git a/group26/1515345281/src/week3/download/test/ConnectionTest.java b/group26/1515345281/src/week3/download/test/ConnectionTest.java new file mode 100644 index 0000000000..36bb9d1761 --- /dev/null +++ b/group26/1515345281/src/week3/download/test/ConnectionTest.java @@ -0,0 +1,52 @@ +package week3.download.test; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import week3.download.api.Connection; +import week3.download.api.ConnectionManager; +import week3.download.api.impl.ConnectionManagerImpl; + + +public class ConnectionTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testContentLength() throws Exception{ + ConnectionManager connMan = new ConnectionManagerImpl(); + Connection conn = connMan.open("http://pic.sc.chinaz.com/files/pic/pic9/201508/apic14052.jpg"); + Assert.assertEquals(112504, conn.getContentLength()); + } + + @Test + public void testRead() throws Exception{ + + ConnectionManager connMan = new ConnectionManagerImpl(); + Connection conn = connMan.open("http://pic.sc.chinaz.com/files/pic/pic9/201508/apic14052.jpg"); + + byte[] data = conn.read(0, 35469); + + Assert.assertEquals(35470, data.length); + + data = conn.read(0, 1023); + + Assert.assertEquals(1024, data.length); + + data = conn.read(1024, 2023); + + Assert.assertEquals(1000, data.length); + + + // 测试不充分,没有断言内容是否正确 + } + +} diff --git a/group26/1515345281/src/week3/download/test/FileDownloaderTest.java b/group26/1515345281/src/week3/download/test/FileDownloaderTest.java new file mode 100644 index 0000000000..3c1d25f742 --- /dev/null +++ b/group26/1515345281/src/week3/download/test/FileDownloaderTest.java @@ -0,0 +1,43 @@ +package week3.download.test; + +import org.junit.Test; + +import week3.download.FileDownloader; +import week3.download.api.DownloadListener; + +public class FileDownloaderTest { + + boolean downloadFinished = false; + + @Test + public void testFileDownloader() { + + String url = "http://210.43.133.109:9999/dldir1.qq.com/qqfile/qq/QQ8.9.1/20437/QQ8.9.1.exe"; + String localFile = "e://qq8.exe"; + long begin=System.currentTimeMillis(); + FileDownloader downloader = new FileDownloader(url, localFile); + downloader.setListener(new DownloadListener() { + + @Override + public void notifyFinished() {// + downloadFinished = true; + } + }); + + downloader.execute(); + + // 等待多线程下载程序执行完毕 + while (!downloadFinished) { + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + long end=System.currentTimeMillis(); + + long cost=(end-begin)/1000; + + System.out.println("下载完成!时间为"+cost+"秒"); + } +} \ No newline at end of file diff --git a/group26/1515345281/src/week3/list/Iterator.java b/group26/1515345281/src/week3/list/Iterator.java new file mode 100644 index 0000000000..223fec106d --- /dev/null +++ b/group26/1515345281/src/week3/list/Iterator.java @@ -0,0 +1,5 @@ +package week3.list; +public interface Iterator{ + public boolean hasNext(); + public Object next(); +} \ No newline at end of file diff --git a/group26/1515345281/src/week3/list/LinkedList.java b/group26/1515345281/src/week3/list/LinkedList.java new file mode 100644 index 0000000000..14dd9a5d9c --- /dev/null +++ b/group26/1515345281/src/week3/list/LinkedList.java @@ -0,0 +1,363 @@ +package week3.list; + +import java.util.Stack; + + +public class LinkedList implements List{ + + private int size=0;//表示该链表的长度 + private Node head;//链表的头元素 + + public void add(Object o){ + if(null == head){ + head = new Node(o); + size++; + return ; + } + + Node node=head; + while(null != node.next){ + node=node.next; + } + Node addNode=new Node(o); + node.next=addNode; + size++; + } + + public void add(int index , Object o){ + if(size == 0 || index ==size){ + add(o); + return ; + } + + ListUtils.checkIndexRange(index, size); + + if(index==0){ + Node node=new Node(head.next.data); + node.next=head.next; + head.next=node; + head.data=o; + size++; + return ; + } + + Node node=head; + for(int i=0;i7->10 , 逆置后变为 10->7->3 + */ + public void reverse(){ + + if(null == head || null ==head.next) + return ; + + Stack stack=new Stack(); + + Node currentNode=head; + + while(currentNode!=null){ + + stack.push(currentNode); + + Node tempNode=currentNode.next; + currentNode.next=null;//断开连接 + + currentNode=tempNode; + + } + + head=stack.pop(); + currentNode=head; + + while(!stack.isEmpty()){ + + currentNode.next=stack.pop(); + currentNode=currentNode.next; + } + } + + /** + * 删除一个单链表的前半部分 + * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 + * 如果list = 2->5->7->8->10 ,删除以后的值为7,8,10 + + */ + public void removeFirstHalf(){ + + int num=size()/2; + for(int i=0;i= size){ + throw new IndexOutOfBoundsException(); + } + + int len=size()-i>=length ? length:size-i; + + int k=0; + + while(k101->201->301->401->501->601->701 + * listB = 1->3->4->6 + * 返回的结果应该是[101,301,401,601] + * @param list + */ + public int[] getElements(LinkedList list){ + + int[] arr=new int[list.size()]; + + for(int i=0;i min && (int)head.data < max){ + head=head.next; + } + + Node cur=head; + + while(cur.next!=null){ + Node next=cur.next; + if( (int)next.data> min && (int)next.data < max){ + cur.next=next.next; + }else{ + cur=cur.next; + } + } + } + + /** + * 假设当前链表和参数list指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) + * 现要求生成新链表C,其元素为当前链表和list中元素的交集,且表C中的元素有依值递增有序排列 + * @param list + */ + public LinkedList intersection( LinkedList list){ + + LinkedList result=new LinkedList(); + Node cur=head; + int i=0; + while(cur!=null && i(int)list.get(i)){ + i++; + }else{ + cur=cur.next; + } + } + return result; + } + + public String toString(){ + StringBuffer buffer = new StringBuffer(); + buffer.append("["); + Node node = head; + while(node != null){ + buffer.append(node.data); + if(node.next != null){ + buffer.append(","); + } + node = node.next; + } + buffer.append("]"); + return buffer.toString(); + } +} \ No newline at end of file diff --git a/group26/1515345281/src/week3/list/LinkedListTest.java b/group26/1515345281/src/week3/list/LinkedListTest.java new file mode 100644 index 0000000000..766eafe426 --- /dev/null +++ b/group26/1515345281/src/week3/list/LinkedListTest.java @@ -0,0 +1,201 @@ +package week3.list; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class LinkedListTest { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testReverse() { + LinkedList l = new LinkedList(); + + Assert.assertEquals("[]", l.toString()); + + l.add(1); + l.reverse(); + Assert.assertEquals("[1]", l.toString()); + + l.add(2); + l.add(3); + l.add(4); + + l.reverse(); + Assert.assertEquals("[4,3,2,1]", l.toString()); + } + + + @Test + public void testRemoveFirstHalf() { + { + LinkedList linkedList = new LinkedList(); + linkedList.add(1); + linkedList.add(2); + linkedList.add(3); + linkedList.add(4); + linkedList.removeFirstHalf(); + Assert.assertEquals("[3,4]", linkedList.toString()); + } + { + LinkedList linkedList = new LinkedList(); + linkedList.add(1); + linkedList.add(2); + linkedList.add(3); + linkedList.add(4); + linkedList.add(5); + linkedList.removeFirstHalf(); + Assert.assertEquals("[3,4,5]", linkedList.toString()); + } + } + + @Test + public void testRemoveIntInt() { + + { + LinkedList linkedList = new LinkedList(); + linkedList.add(1); + linkedList.add(2); + linkedList.add(3); + linkedList.add(4); + linkedList.remove(0, 2); + Assert.assertEquals("[3,4]", linkedList.toString()); + } + { + LinkedList linkedList = new LinkedList(); + linkedList.add(1); + linkedList.add(2); + linkedList.add(3); + linkedList.add(4); + linkedList.remove(3, 2); + Assert.assertEquals("[1,2,3]", linkedList.toString()); + } + { + LinkedList linkedList = new LinkedList(); + linkedList.add(1); + linkedList.add(2); + linkedList.add(3); + linkedList.add(4); + linkedList.remove(2, 2); + Assert.assertEquals("[1,2]", linkedList.toString()); + } + + } + @Test + public void testGetElements() { + LinkedList linkedList = new LinkedList(); + linkedList.add(11); + linkedList.add(101); + linkedList.add(201); + linkedList.add(301); + linkedList.add(401); + linkedList.add(501); + linkedList.add(601); + linkedList.add(701); + LinkedList list = new LinkedList(); + list.add(1); + list.add(3); + list.add(4); + list.add(6); + Assert.assertArrayEquals(new int[]{101,301,401,601}, linkedList.getElements(list)); + } + + @Test + public void testSubtract() { + LinkedList list1 = new LinkedList(); + list1.add(101); + list1.add(201); + list1.add(301); + list1.add(401); + list1.add(501); + list1.add(601); + list1.add(701); + + LinkedList list2 = new LinkedList(); + + list2.add(201); + list2.add(301); + list2.add(501); + + list1.subtract(list2); + + Assert.assertEquals("[101,401,601,701]", list1.toString()); + } + + + @Test + public void testRemoveDuplicateValues() { + LinkedList list = new LinkedList(); + list.add(1); + list.add(1); + list.add(2); + list.add(2); + list.add(3); + list.add(5); + list.add(5); + list.add(6); + list.add(6); + list.removeDuplicateValues(); + + Assert.assertEquals("[1,2,3,5,6]", list.toString()); + } + + + @Test + public void testRemoveRange() { + + { + LinkedList linkedList = new LinkedList(); + + linkedList.add(11); + linkedList.add(12); + linkedList.add(13); + linkedList.add(14); + linkedList.add(16); + linkedList.add(16); + linkedList.add(19); + + linkedList.removeRange(10, 19); + Assert.assertEquals("[19]", linkedList.toString()); + } + + { + LinkedList linkedList = new LinkedList(); + + linkedList.add(11); + linkedList.add(12); + linkedList.add(13); + linkedList.add(14); + linkedList.add(16); + linkedList.add(16); + linkedList.add(19); + + linkedList.removeRange(10, 14); + Assert.assertEquals("[14,16,16,19]", linkedList.toString()); + } + } + @Test + public void testIntersection() { + LinkedList list1 = new LinkedList(); + list1.add(1); + list1.add(6); + list1.add(7); + + LinkedList list2 = new LinkedList(); + list2.add(2); + list2.add(5); + list2.add(6); + + LinkedList newList = list1.intersection(list2); + Assert.assertEquals("[6]", newList.toString()); + } + +} diff --git a/group26/1515345281/src/week3/list/List.java b/group26/1515345281/src/week3/list/List.java new file mode 100644 index 0000000000..cc4a2cb261 --- /dev/null +++ b/group26/1515345281/src/week3/list/List.java @@ -0,0 +1,14 @@ +package week3.list; + +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/group26/1515345281/src/week3/list/ListUtils.java b/group26/1515345281/src/week3/list/ListUtils.java new file mode 100644 index 0000000000..641cea3284 --- /dev/null +++ b/group26/1515345281/src/week3/list/ListUtils.java @@ -0,0 +1,9 @@ +package week3.list; + +public class ListUtils { + + public static void checkIndexRange(int index, int size) { + if (index < 0 || index > size) + throw new IndexOutOfBoundsException(); + } +} From e98df32110384933f1f92619b7e7d2029e346c06 Mon Sep 17 00:00:00 2001 From: SJsunshine Date: Sat, 1 Apr 2017 13:34:04 +0800 Subject: [PATCH 14/20] blog --- group26/1515345281/src/week2/blog | 1 + group26/1515345281/src/week3/blog | 1 + 2 files changed, 2 insertions(+) create mode 100644 group26/1515345281/src/week2/blog create mode 100644 group26/1515345281/src/week3/blog diff --git a/group26/1515345281/src/week2/blog b/group26/1515345281/src/week2/blog new file mode 100644 index 0000000000..19c1272ec0 --- /dev/null +++ b/group26/1515345281/src/week2/blog @@ -0,0 +1 @@ +数筛法的具体应用--素数求解问题:http://blog.csdn.net/sjshenjian/article/details/68943399 \ No newline at end of file diff --git a/group26/1515345281/src/week3/blog b/group26/1515345281/src/week3/blog new file mode 100644 index 0000000000..2c4d2cdc00 --- /dev/null +++ b/group26/1515345281/src/week3/blog @@ -0,0 +1 @@ +图片验证码生成 : http://blog.csdn.net/sjshenjian/article/details/68943294 \ No newline at end of file From 91f56979f88eead9f314e3a186df0945bd2ff73b Mon Sep 17 00:00:00 2001 From: Lizhy Date: Sat, 1 Apr 2017 18:02:42 +0800 Subject: [PATCH 15/20] LinkedList --- .../homework/third/basic/LinkedList.java | 143 ++++++++++++++---- 1 file changed, 111 insertions(+), 32 deletions(-) diff --git a/group26/lizhy2017/homework/third/basic/LinkedList.java b/group26/lizhy2017/homework/third/basic/LinkedList.java index b011033258..49265f7b31 100644 --- a/group26/lizhy2017/homework/third/basic/LinkedList.java +++ b/group26/lizhy2017/homework/third/basic/LinkedList.java @@ -1,59 +1,113 @@ package third.basic; +import java.util.Objects; + /** * ${} * Created by spark_lizhy on 2017/3/31. */ -public class LinkedList { - - private Node head; +public class LinkedList { + private Node mHead; + private Node mCurrent; + private int mSize = 0; - public void add(Object o){ + public void add(T o) { + addLast(o); + mSize++; } - public void add(int index , Object o){ + + public void add(int index, T o) { + checkIndex(index); + + Node next = find(index); + Node pre = next.previous; + Node current = new Node<>(o, next, pre); + next.previous = current; + pre.next = current; + mSize++; } - public Object get(int index){ - return null; - } - public Object remove(int index){ - return null; + + private Node find(int index) { + Node tra = mHead; + if (index < (mSize >> 1)) { + for (int i = 0; i <= index; i++) { + tra = tra.next; + } + } else { + for (int i = mSize; i > index; i--) { + tra = tra.previous; + } + } + return tra; } - public int size(){ - return -1; + private void checkIndex(int index) { + if (index >= mSize || index < 0) { + throw new IndexOutOfBoundsException("Index:" + index + " Size:" + mSize); + } } - public void addFirst(Object o){ + public Object get(int index) { + checkIndex(index); + return find(index).data; } - public void addLast(Object o){ + public T remove(int index) { + checkIndex(index); + //重链接 + Node temp = this.find(index); + Node next = temp.next; + Node pre = temp.previous; + pre.next = next; + next.previous = pre; + //清除数据 + T removedObject = temp.data; + temp.data = null; + temp.next = null; + temp.previous = null; + mSize--; + return removedObject; } - public Object removeFirst(){ - return null; + + public int size() { + return mSize; } - public Object removeLast(){ - return null; + + public void addFirst(T o) { + Node next = mHead.next; + Node first = new Node<>(o, next, mHead); + next.next = first; + next.previous = first; + mSize++; + } -// public Iterator iterator(){ -// return null; -// } + public void addLast(T o) { + Node last = mHead.previous; + Node temp = new Node<>(o, mHead, last); + mHead.previous = temp; + last.next = temp; + mSize++; + } - private static class Node{ - Object data; - Node next; + public T removeFirst() { + return remove(0); + } + public T removeLast() { + return remove(mSize - 1); } + /** * 把该链表逆置 * 例如链表为 3->7->10 , 逆置后变为 10->7->3 */ - public void reverse(){ + public void reverse() { } @@ -62,37 +116,41 @@ public void reverse(){ * 例如:list = 2->5->7->8 , 删除以后的值为 7->8 * 如果 list = 2->5->7->8->10 , 删除以后的值为 7,8,10 */ - public void removeFirstHalf(){ + public void removeFirstHalf() { } /** * 从第 i 个元素开始, 删除 length 个元素 , 注意 i 从 0 开始 + * * @param i * @param length */ - public void remove(int i, int 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){ + public int[] getElements(LinkedList list) { return null; } /** * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 * 从当前链表中中删除在 listB 中出现的元素 + * * @param list */ - public void subtract(LinkedList list){ + public void subtract(LinkedList list) { } @@ -100,26 +158,47 @@ public void subtract(LinkedList list){ * 已知当前链表中的元素以值递增有序排列,并以单链表作存储结构。 * 删除表中所有值相同的多余元素(使得操作后的线性表中所有元素的值均不相同) */ - public void removeDuplicateValues(){ + public void removeDuplicateValues() { } /** * 已知链表中的元素以值递增有序排列,并以单链表作存储结构。 * 试写一高效的算法,删除表中所有值大于 min 且小于 max 的元素(若表中存在这样的元素) + * * @param min * @param max */ - public void removeRange(int min, int max){ + public void removeRange(int min, int max) { } /** * 假设当前链表和参数 list 指定的链表均以元素依值递增有序排列(同一表中的元素值各不相同) * 现要求生成新链表 C,其元素为当前链表和 list 中元素的交集,且表 C 中的元素有依值递增有序排列 + * * @param list */ - public LinkedList intersection( LinkedList list){ + public LinkedList intersection(LinkedList list) { return null; } + + + private static class Node { + T data; + Node next; + Node previous; + + public Node(T data) { + this.data = data; + this.next = this; + this.previous = this; + } + + public Node(T data, Node next, Node previous) { + this.data = data; + this.next = next; + this.previous = previous; + } + } } From d2e8c31cbda81910e9af574d670edf90e3bc893a Mon Sep 17 00:00:00 2001 From: SJsunshine Date: Sat, 1 Apr 2017 18:36:33 +0800 Subject: [PATCH 16/20] =?UTF-8?q?=E5=89=8D=E4=B8=89=E5=91=A8=E5=85=A8?= =?UTF-8?q?=E9=83=A8=E5=AE=9E=E7=8E=B0=E4=B8=80=E9=81=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- group26/1515345281/src/Collection/blog | 1 + .../src/week3/download/test/FileDownloaderTest.java | 6 ++++-- 2 files changed, 5 insertions(+), 2 deletions(-) create mode 100644 group26/1515345281/src/Collection/blog diff --git a/group26/1515345281/src/Collection/blog b/group26/1515345281/src/Collection/blog new file mode 100644 index 0000000000..87966e2eba --- /dev/null +++ b/group26/1515345281/src/Collection/blog @@ -0,0 +1 @@ +浅谈CPU,内存,硬盘,指令之间的关系http://blog.csdn.net/sjshenjian/article/details/68946823 \ No newline at end of file diff --git a/group26/1515345281/src/week3/download/test/FileDownloaderTest.java b/group26/1515345281/src/week3/download/test/FileDownloaderTest.java index 3c1d25f742..7da91ce6c6 100644 --- a/group26/1515345281/src/week3/download/test/FileDownloaderTest.java +++ b/group26/1515345281/src/week3/download/test/FileDownloaderTest.java @@ -12,8 +12,10 @@ public class FileDownloaderTest { @Test public void testFileDownloader() { - String url = "http://210.43.133.109:9999/dldir1.qq.com/qqfile/qq/QQ8.9.1/20437/QQ8.9.1.exe"; - String localFile = "e://qq8.exe"; + /*String url = "http://210.43.133.109:9999/dldir1.qq.com/qqfile/qq/QQ8.9.1/20437/QQ8.9.1.exe"; + String localFile = "e://qq8.exe";*/ + String url="http://www.iqiyi.com/common/flashplayer/20170331/036801ea7a2e24.swf"; + String localFile="e:\\036801ea7a2e24.swf"; long begin=System.currentTimeMillis(); FileDownloader downloader = new FileDownloader(url, localFile); downloader.setListener(new DownloadListener() { From d7db7bac51b76ec0992d2655bd522461a7fd2041 Mon Sep 17 00:00:00 2001 From: SJsunshine Date: Sun, 2 Apr 2017 10:39:22 +0800 Subject: [PATCH 17/20] week4 homework and blog --- .../origin/jvm/loader/ClassFileLoader.java | 72 ++++++++++++ .../week4/origin/jvm/loader/LRUPageFrame.java | 105 ++++++++++++++++++ .../src/week4/origin/jvm/loader/blog | 1 + .../jvm/loader/test/ClassFileLoaderTest.java | 55 +++++++++ .../origin/jvm/loader/test/EmployeeV1.java | 28 +++++ .../jvm/loader/test/LRUPageFrameTest.java | 32 ++++++ 6 files changed, 293 insertions(+) create mode 100644 group26/1515345281/src/week4/origin/jvm/loader/ClassFileLoader.java create mode 100644 group26/1515345281/src/week4/origin/jvm/loader/LRUPageFrame.java create mode 100644 group26/1515345281/src/week4/origin/jvm/loader/blog create mode 100644 group26/1515345281/src/week4/origin/jvm/loader/test/ClassFileLoaderTest.java create mode 100644 group26/1515345281/src/week4/origin/jvm/loader/test/EmployeeV1.java create mode 100644 group26/1515345281/src/week4/origin/jvm/loader/test/LRUPageFrameTest.java diff --git a/group26/1515345281/src/week4/origin/jvm/loader/ClassFileLoader.java b/group26/1515345281/src/week4/origin/jvm/loader/ClassFileLoader.java new file mode 100644 index 0000000000..601aab6aad --- /dev/null +++ b/group26/1515345281/src/week4/origin/jvm/loader/ClassFileLoader.java @@ -0,0 +1,72 @@ +package week4.origin.jvm.loader; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class ClassFileLoader { + + static final int BUFFER_SIZE = 1024; + private List clzPaths = new ArrayList(); + + private String path; + + public byte[] readBinaryCode(String className) { + // "week4.origin.jvm.loader.test.EmployeeV1" + String fileName = path+File.separator+className.replace(".", File.separator) + ".class"; + + FileInputStream in=null; + BufferedInputStream bis=null; + ByteArrayOutputStream baos=null; + + try { + in = new FileInputStream(fileName); + + bis = new BufferedInputStream(in, BUFFER_SIZE); + + // 缓冲区会因为数据的不断写入而自动增长 + baos = new ByteArrayOutputStream(); + + byte[] buffer = new byte[BUFFER_SIZE]; + + int len = 0; + + while ((len = bis.read(buffer)) != -1) { + baos.write(buffer, 0, len); + } + + } catch (IOException e) { + e.printStackTrace(); + }finally{ + if(bis!=null){ + try { + bis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if(in!=null){ + try { + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + return baos.toByteArray(); + } + + public void addClassPath(String path) { + this.path=path; + } + + public String getClassPath() { + return path; + } +} \ No newline at end of file diff --git a/group26/1515345281/src/week4/origin/jvm/loader/LRUPageFrame.java b/group26/1515345281/src/week4/origin/jvm/loader/LRUPageFrame.java new file mode 100644 index 0000000000..104f3b8690 --- /dev/null +++ b/group26/1515345281/src/week4/origin/jvm/loader/LRUPageFrame.java @@ -0,0 +1,105 @@ +package week4.origin.jvm.loader; + +/** + * 用双向链表实现LRU算法 + * @author liuxin + * + */ +public class LRUPageFrame { + + private int capacity; + private int curSize;//记录当前缓存大小 + + private Node first;// 链表头 + private Node last;// 链表尾 + + + public LRUPageFrame(int capacity) { + + this.capacity = capacity; + curSize=0; + } + + /** + * 获取缓存中对象 + * + * @param key + * @return + */ + public void access(int pageNum) { + + if(capacity <=0 ){ + throw new IndexOutOfBoundsException(); + } + + if(curSize == 0){ + Node node=new Node(null,null,pageNum); + curSize++; + first=node; + last=node; + return ; + } + + if(first.pageNum == pageNum){ + return ; + } + + //不管是否需要置换头指针均需要改变 + Node node=new Node(null,first,pageNum); + first.prev=node; + first=node; + + if(curSize == 1){ + last.prev=node; + } + + if(curSize < capacity){ + curSize++; + return ; + } + + if(curSize == capacity){//容量不足,开始置换 + + //首先判断里面是否存在值相同元素 + Node curNode=first.next; + while(curNode.next!=null){ + if(curNode.pageNum == pageNum){//如果找到 + curNode.prev.next=curNode.next; + curNode.next.prev=curNode.prev; + return ; + } + curNode=curNode.next; + } + Node tempNode=last.prev; + last=tempNode; + last.next=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(); + } + + private static class Node { + Node prev; + Node next; + int pageNum; + public Node(Node prev,Node next,int pageNum){ + this.prev=prev; + this.next=next; + this.pageNum=pageNum; + } + } +} \ No newline at end of file diff --git a/group26/1515345281/src/week4/origin/jvm/loader/blog b/group26/1515345281/src/week4/origin/jvm/loader/blog new file mode 100644 index 0000000000..010f9cb473 --- /dev/null +++ b/group26/1515345281/src/week4/origin/jvm/loader/blog @@ -0,0 +1 @@ +SAX解析Xml实战 http://blog.csdn.net/sjshenjian/article/details/68950978 \ No newline at end of file diff --git a/group26/1515345281/src/week4/origin/jvm/loader/test/ClassFileLoaderTest.java b/group26/1515345281/src/week4/origin/jvm/loader/test/ClassFileLoaderTest.java new file mode 100644 index 0000000000..69836b7c04 --- /dev/null +++ b/group26/1515345281/src/week4/origin/jvm/loader/test/ClassFileLoaderTest.java @@ -0,0 +1,55 @@ +package week4.origin.jvm.loader.test; + +import org.junit.Assert; +import org.junit.Test; + +import week4.origin.jvm.loader.ClassFileLoader; + + +public class ClassFileLoaderTest { + + + static String path1="E:\\JAVA\\liuxin\\coding2017\\group26\\1515345281\\bin"; + + @Test + public void testClassFileLength() { + + ClassFileLoader loader = new ClassFileLoader(); + loader.addClassPath(path1); + + String className = "week4.origin.jvm.loader.test.EmployeeV1"; + + byte[] byteCodes = loader.readBinaryCode(className); + + // 注意:这个字节数可能和你的JVM版本有关系, 你可以看看编译好的类到底有多大 + Assert.assertEquals(1066, byteCodes.length); + + } + + + @Test + public void testMagicNumber(){ + ClassFileLoader loader = new ClassFileLoader(); + loader.addClassPath(path1); + String className = "week4.origin.jvm.loader.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 ){ + StringBuffer buffer=new StringBuffer(); + for(int i=0;i Date: Sun, 2 Apr 2017 17:52:53 +0800 Subject: [PATCH 18/20] litestruts --- .../src/com/litestruts/LoginAction.java | 39 ++++++++ .../723161901/src/com/litestruts/Struts.java | 91 +++++++++++++++++++ .../src/com/litestruts/StrutsTest.java | 41 +++++++++ .../src/com/litestruts/StrutsXmlReader.java | 59 ++++++++++++ .../723161901/src/com/litestruts/View.java | 23 +++++ .../723161901/src/com/litestruts/struts.xml | 11 +++ .../src/com/litestruts/strutsBean/Action.java | 46 ++++++++++ 7 files changed, 310 insertions(+) create mode 100644 group26/723161901/src/com/litestruts/LoginAction.java create mode 100644 group26/723161901/src/com/litestruts/Struts.java create mode 100644 group26/723161901/src/com/litestruts/StrutsTest.java create mode 100644 group26/723161901/src/com/litestruts/StrutsXmlReader.java create mode 100644 group26/723161901/src/com/litestruts/View.java create mode 100644 group26/723161901/src/com/litestruts/struts.xml create mode 100644 group26/723161901/src/com/litestruts/strutsBean/Action.java diff --git a/group26/723161901/src/com/litestruts/LoginAction.java b/group26/723161901/src/com/litestruts/LoginAction.java new file mode 100644 index 0000000000..de60ce339d --- /dev/null +++ b/group26/723161901/src/com/litestruts/LoginAction.java @@ -0,0 +1,39 @@ +package com.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/group26/723161901/src/com/litestruts/Struts.java b/group26/723161901/src/com/litestruts/Struts.java new file mode 100644 index 0000000000..b633c0c767 --- /dev/null +++ b/group26/723161901/src/com/litestruts/Struts.java @@ -0,0 +1,91 @@ +package com.litestruts; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +import com.litestruts.strutsBean.Action; + + + +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字段中。 + + */ + StrutsXmlReader strutsXml = new StrutsXmlReader(new File("src/com/litestruts/struts.xml")); + View view = new View(); + try { + HashMap actMap = (HashMap) strutsXml.loadXml(); + Action act = (Action) actMap.get(actionName); + Class clazz = Class.forName(act.getClazz()); + Object obj = clazz.newInstance(); + HashMap paraMap = act.getParameters(); + Iterator> iteraPara = parameters.entrySet().iterator(); + + while(iteraPara.hasNext()){ + Entry itera = iteraPara.next(); + Field field = clazz.getDeclaredField(itera.getKey()); + field.setAccessible(true); + field.set(obj, itera.getValue()); + } + + Method method = clazz.getMethod("execute", null); + String results = (String)method.invoke(obj, null); + Field[] getFields = clazz.getDeclaredFields(); + HashMap getMapPara = new HashMap(); + for (Field field : getFields) { + field.setAccessible(true); + String getFiledName = field.getName(); + Object objValue = field.get(obj); + getMapPara.put(getFiledName, objValue); + } + + view.setParameters(getMapPara); + view.setJsp((String)paraMap.get(results)); + + } catch (Exception e) { + e.printStackTrace(); + } + + return view; + } + + +} diff --git a/group26/723161901/src/com/litestruts/StrutsTest.java b/group26/723161901/src/com/litestruts/StrutsTest.java new file mode 100644 index 0000000000..07953fc013 --- /dev/null +++ b/group26/723161901/src/com/litestruts/StrutsTest.java @@ -0,0 +1,41 @@ +package com.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(); + + 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/group26/723161901/src/com/litestruts/StrutsXmlReader.java b/group26/723161901/src/com/litestruts/StrutsXmlReader.java new file mode 100644 index 0000000000..6470bc1d96 --- /dev/null +++ b/group26/723161901/src/com/litestruts/StrutsXmlReader.java @@ -0,0 +1,59 @@ +package com.litestruts; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +import com.litestruts.strutsBean.Action; + +public class StrutsXmlReader { + private File file; + private HashMap actMap = new HashMap(); + + public StrutsXmlReader(File file) { + super(); + this.file = file; + } + + + public Map loadXml() throws ParserConfigurationException, SAXException, IOException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document doc = builder.parse(file); + NodeList nl = doc.getElementsByTagName("action"); + for (int i = 0; i < nl.getLength(); i++) { + Element book = (Element) nl.item(i); + String name = book.getAttribute("name"); + String claz = book.getAttribute("class"); + Action act = new Action(name, claz); + System.out.println(name); + System.out.println(claz); + NodeList bookNode = book.getChildNodes(); + HashMap paraMap = new HashMap(); + for (int j = 0; j < bookNode.getLength(); j++) { + Node bookCh = bookNode.item(j); + if (bookCh.getNodeType() == Node.ELEMENT_NODE) { + String valTag = bookCh.getTextContent(); + NamedNodeMap attrs = bookCh.getAttributes(); + String resultsValue = attrs.getNamedItem("name").getNodeValue(); + paraMap.put(resultsValue, valTag); + } + act.setParameters(paraMap); + } + actMap.put(act.getName(), act); + } + return actMap; + } +} diff --git a/group26/723161901/src/com/litestruts/View.java b/group26/723161901/src/com/litestruts/View.java new file mode 100644 index 0000000000..a7494563ef --- /dev/null +++ b/group26/723161901/src/com/litestruts/View.java @@ -0,0 +1,23 @@ +package com.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/group26/723161901/src/com/litestruts/struts.xml b/group26/723161901/src/com/litestruts/struts.xml new file mode 100644 index 0000000000..84c494845f --- /dev/null +++ b/group26/723161901/src/com/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/group26/723161901/src/com/litestruts/strutsBean/Action.java b/group26/723161901/src/com/litestruts/strutsBean/Action.java new file mode 100644 index 0000000000..37435653f2 --- /dev/null +++ b/group26/723161901/src/com/litestruts/strutsBean/Action.java @@ -0,0 +1,46 @@ +package com.litestruts.strutsBean; + +import java.util.HashMap; + +public class Action { + private String name; + private String clazz; + private HashMap parameters; + + public Action() { + super(); + } + + public Action(String name, String clazz) { + super(); + this.name = name; + this.clazz = clazz; + } + + public Action(String name, String clazz, HashMap parameters) { + super(); + this.name = name; + this.clazz = clazz; + this.parameters = parameters; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getClazz() { + return clazz; + } + public void setClazz(String clazz) { + this.clazz = clazz; + } + public HashMap getParameters() { + return parameters; + } + public void setParameters(HashMap parameters) { + this.parameters = parameters; + } + + +} From 5685e91b5cc1501f52dcb7f49ef6e271a9e8a000 Mon Sep 17 00:00:00 2001 From: Macx Date: Mon, 3 Apr 2017 02:25:43 +0800 Subject: [PATCH 19/20] download --- .../com/download/download/DownloadThread.java | 39 ++++++ .../com/download/download/FileDownloader.java | 116 ++++++++++++++++++ .../download/download/FileDownloaderTest.java | 59 +++++++++ .../com/download/download/api/Connection.java | 23 ++++ .../download/api/ConnectionException.java | 5 + .../download/api/ConnectionManager.java | 10 ++ .../download/api/DownloadListener.java | 5 + .../download/impl/ConnectionImpl.java | 69 +++++++++++ .../download/impl/ConnectionManagerImpl.java | 15 +++ 9 files changed, 341 insertions(+) create mode 100644 group26/723161901/src/com/download/download/DownloadThread.java create mode 100644 group26/723161901/src/com/download/download/FileDownloader.java create mode 100644 group26/723161901/src/com/download/download/FileDownloaderTest.java create mode 100644 group26/723161901/src/com/download/download/api/Connection.java create mode 100644 group26/723161901/src/com/download/download/api/ConnectionException.java create mode 100644 group26/723161901/src/com/download/download/api/ConnectionManager.java create mode 100644 group26/723161901/src/com/download/download/api/DownloadListener.java create mode 100644 group26/723161901/src/com/download/download/impl/ConnectionImpl.java create mode 100644 group26/723161901/src/com/download/download/impl/ConnectionManagerImpl.java diff --git a/group26/723161901/src/com/download/download/DownloadThread.java b/group26/723161901/src/com/download/download/DownloadThread.java new file mode 100644 index 0000000000..a74390ef50 --- /dev/null +++ b/group26/723161901/src/com/download/download/DownloadThread.java @@ -0,0 +1,39 @@ +package com; + +import java.io.RandomAccessFile; +import java.util.concurrent.CyclicBarrier; + +import com.api.Connection; + +public class DownloadThread extends Thread{ + + private Connection conn; + private int startPos; + private int endPos; + private String localFile; + private CyclicBarrier barrier; + + public DownloadThread( Connection conn, int startPos, int endPos, String localFile, CyclicBarrier barrier){ + this.conn = conn; + this.startPos = startPos; + this.endPos = endPos; + this.localFile = localFile; + this.barrier = barrier; + } + + public void run(){ + try { + + byte[] data =conn.read(startPos, endPos); + + RandomAccessFile file = new RandomAccessFile(localFile,"rw"); + file.seek(startPos); + file.write(data); + file.close(); + conn.close(); + barrier.await(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/group26/723161901/src/com/download/download/FileDownloader.java b/group26/723161901/src/com/download/download/FileDownloader.java new file mode 100644 index 0000000000..5199de1ed5 --- /dev/null +++ b/group26/723161901/src/com/download/download/FileDownloader.java @@ -0,0 +1,116 @@ +package com; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.util.concurrent.CyclicBarrier; + +import com.api.Connection; +import com.api.ConnectionException; +import com.api.ConnectionManager; +import com.api.DownloadListener; + + +public class FileDownloader { + + private String url; + private String localFile; + + DownloadListener listener; + + ConnectionManager cm; + private static final int DOWNLOAD_THREAD_NUM = 3; + + + public FileDownloader(String _url, String localFile) { + this.url = _url; + this.localFile = localFile; + } + + 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方法 + + // 下面的代码是示例代码, 也就是说只有一个线程, 你需要改造成多线程的。 + + CyclicBarrier barrier = new CyclicBarrier(DOWNLOAD_THREAD_NUM, new Runnable(){ + @Override + public void run() { + listener.notifyFinished(); + } + }); + Connection conn = null; + try { + + conn = cm.open(this.url); + + int length = conn.getContentLength(); + createPlaceHolderFile(this.localFile, length); + int[][] ranges = allocateDownloadRange(DOWNLOAD_THREAD_NUM, length); + for(int i=0; i totalLen){ + byte[] data = baos.toByteArray(); + return Arrays.copyOf(data, totalLen); + } + return baos.toByteArray(); + } + + @Override + public int getContentLength() { + try { + URLConnection con = url.openConnection(); + return con.getContentLength(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return -1; + } + + @Override + public void close() { + + + } + +} diff --git a/group26/723161901/src/com/download/download/impl/ConnectionManagerImpl.java b/group26/723161901/src/com/download/download/impl/ConnectionManagerImpl.java new file mode 100644 index 0000000000..4903af944f --- /dev/null +++ b/group26/723161901/src/com/download/download/impl/ConnectionManagerImpl.java @@ -0,0 +1,15 @@ +package com.impl; + +import com.api.Connection; +import com.api.ConnectionException; +import com.api.ConnectionManager; + +public class ConnectionManagerImpl implements ConnectionManager { + + @Override + public Connection open(String urlStr) throws ConnectionException { + + return new ConnectionImpl(urlStr); + } + +} From 6c40fef63df460d894557ad45eb05ca1358d7543 Mon Sep 17 00:00:00 2001 From: AndroidLinkLinked Date: Thu, 6 Apr 2017 11:29:35 +0800 Subject: [PATCH 20/20] =?UTF-8?q?Update=2026=E7=BB=84=E6=83=85=E5=86=B5?= =?UTF-8?q?=E7=BB=9F=E8=AE=A1.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...\273\204\346\203\205\345\206\265\347\273\237\350\256\241.md" | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git "a/group26/26\347\273\204\346\203\205\345\206\265\347\273\237\350\256\241.md" "b/group26/26\347\273\204\346\203\205\345\206\265\347\273\237\350\256\241.md" index 165922cc87..463477e992 100644 --- "a/group26/26\347\273\204\346\203\205\345\206\265\347\273\237\350\256\241.md" +++ "b/group26/26\347\273\204\346\203\205\345\206\265\347\273\237\350\256\241.md" @@ -11,7 +11,7 @@ | | | | | | | | 2070509107 | 已完成 | | | | | | | | | | | | -| lizhy2017 | 部分完成 | 已完成 | | | | +| lizhy2017           |                   已完成                   |   已完成 |     |  已完成   |     | | | | | | | | | JEE-逆水百川 | 部分完成 | | | | | | | http://blog.csdn.net/u012759397/article/details/61618612 | | | | |