---
# System prepended metadata

title: CTBC TC Day1

---

# CTBC TC Day1

# 重要!!
* # JAVA的路徑
    * # 避免中文檔名
    * # 避免空白
    * # 避免特殊符號(+,-,*,/,\,&)
    * # 建議 d:\java\jdk17, d:\java\jdk11_1...



## 快速檢查環境

```
set JAVA
java -version
javac -version

```
# LTS

```
Object x1 = new Object();
```

![](https://i.imgur.com/kXctQJF.png)

![](https://i.imgur.com/DEx2Q1v.png)

![](https://i.imgur.com/ahxHvbs.png)

![](https://i.imgur.com/qUmD1sG.png)

## content assist
```
alt+'/'
```
# `lab1\Demo1.java`
```java
package lab1;

public class Demo1 {

	public static void main(String[] args) {
		System.out.println("Hi, my code is in here");

	}

}

```

![](https://i.imgur.com/6pOC9p1.png)

![](https://i.imgur.com/0XcdveK.png)

![](https://i.imgur.com/NYYwjZu.png)

![](https://i.imgur.com/CGZuwY1.png)


![](https://i.imgur.com/HuNdwHq.png)

# Demo1.java (cont'd)
```java

package lab1;

public class Demo1 {

	public static void main(String[] args) {
		// 宣告三個變數
		int x1 = 5;
		int x2 = 6;
		int x3 = 7;
		x1 = x1+1;
		x2 = x2+2;
		x3 = x3+3;
		int x4 = x1+x2+x3;
		System.out.println("Hi, my code is in here, 中文");

	}

}

```

### code generate
### auto format
```
alt+/
ctrl+shift+F
```
# Demo2
```java
package lab1;

public class Demo2 {
	public static void main(String[] args) {
		char x1 = 'a';
		String x2 = "a";
		char x3 = 'b';
		String x4 = "ab";
		int x5 = x3 - x1;
		int x6 = x3 + x1;
		String x7 = x2+x4;
		String x8 = x4-x2;
		System.out.println("比較不同");

	}
}


```

# Demo3
```java
package lab1;

public class Demo3 {
	public static void main(String[] args) {
		String x1 = "hello world";
		String x2 = "hello\tworld";
		String x3 = "hello\rworld";
		System.out.println("第1個是:"+x1);
		System.out.println("第2個是:"+x2);
		System.out.println("第3個是:"+x3);
	}
}

```

### toggle comment
### `ctrl+/`

# Demo4
```java
package lab1;

public class Demo4 {
	public static void main(String[] args) {
		int x1 = 5;
		Integer x2 = 5;
		float x3 = 2.5f;
		Float x4 = 2.5f;
		double x5 = 2.5;
		Double x6 = 2.5;
		char x7 = 'a';
		Character x8 = 'a';
		System.out.println("x2物件與x1非物件的不同");
	}
}



```


## Demo5
```java
package lab1;

public class Demo5 {
	public static void main(String[] args) {
		Byte x1 = 3;
		Character x2 = 5;
		byte x3 = 3;
		char x4 = 5;
		int x5 = x1.MIN_VALUE;
		int x6 = x1.MAX_VALUE;
		// int x7 = x3.MIN_VALUE;
		int x7 = x2.MIN_VALUE;
		int x8 = x2.MAX_VALUE;
		Short x9 = 20;
		int x10 = x9.MIN_VALUE;
		int x11 = x9.MAX_VALUE;
		System.out.printf("byte的最大是%d最小%d是\n", x6, x5);
		System.out.printf("char的最大是%d,最小是%d\n", x8, x7);
		System.out.printf("short的最大是%d,最小是%d\n", x11, x10);
	}
}


```

# string formatter
```
System.out.printf("byte的最大最小");

```

# Demo6
```java
package lab1;

public class Demo6 {
	public static void main(String[] args) {
		String[] dayOfWeek = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
		for (int i = 0; i < 7; i++) {
			switch (dayOfWeek[i]) {
			case "Sunday":
				System.out.println("周日");
				break;
			case "Monday":
				System.out.println("周一");
				break;
			case "Tuesday":
				System.out.println("周二");
				break;
			case "Wednesday":
				System.out.println("周三");
				break;
			case "Thursday":
				System.out.println("周四");
				break;
			case "Friday":
				System.out.println("周五");
				break;
			case "Saturday":
				System.out.println("周六");
				break;
			default:
				System.out.println("以上皆非");

			}
			System.out.printf("%s\n", dayOfWeek[i]);
		}
	}
}


```
# Demo6_2
```java
package lab1;

public class Demo6_2 {
	public static void main(String[] args) {
		String[] dayOfWeek = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
		for (String day : dayOfWeek) {
			switch (day) {
			case "Sunday":
				System.out.println("周日");
				break;
			case "Monday":
				System.out.println("周一");
				break;
			case "Tuesday":
				System.out.println("周二");
				break;
			case "Wednesday":
				System.out.println("周三");
				break;
			case "Thursday":
				System.out.println("周四");
				break;
			case "Friday":
				System.out.println("周五");
				break;
			case "Saturday":
				System.out.println("周六");
				break;
			default:
				System.out.println("以上皆非");

			}

		}
	}
}

```
# Demo7
```java

package lab1;

public class Demo7 {
	public static void main(String[] args) {
		// 001, 010, 1010
		String x0 = "10101100";
		int x1 = Integer.parseInt(x0, 2);
		System.out.printf("%s is %d\n", x0, x1);
		int x2 = 0b10101100;
		System.out.printf("直接用 0b%s==>%d\n", x0, x2);
		long x3 = 1000000000;
		long x4 = 1_000_000_000;
		long x5 = 10_0000_0000;
		System.out.printf("x3-x4=%d\n", x3 - x4);
		System.out.printf("x3-x5=%d\n", x3 - x5);
	}
}

```

![](https://i.imgur.com/Qjl9WWO.png)

# Employee.java
```java
package lab2;

public class Employee {
	String name;
	int salary;
	void work(){
		
	}
	String status() {
		return "normal";
	}
}

```

![](https://i.imgur.com/8MbqKSt.png)

![](https://i.imgur.com/jHzX4zZ.png)

```java

package lab2;

public class Employee {
	private String name;
	private int salary;

	public Employee(String name, int salary) {
		super();
		this.name = name;
		this.salary = salary;
	}

	public void work() {
		System.out.printf("%s的月薪是:%d\n", this.name, this.salary);
	}

	public String status() {
		return "normal";
	}
}

```
# Lab2Main
```java
package lab2;

public class Lab2Main {
	public static void main(String[] args) {
		Employee e1 = new Employee("Mark", 30);
		Employee e2 = new Employee("John", 50);
		Employee e3 = new Employee("Mark", 30);
		Employee e4 = e1;
	}
}

```

# Lab2Main2

```java
package lab2;

public class Lab2Main2 {
	public static void main(String[] args) {
		Employee e1 = new Employee("Mark",30);
		Employee e2 = new Employee("Mark",30);
		Employee e3 = e1;
		System.out.printf("two reference to same object, result is:%b\n",e1==e3);
		System.out.printf("create two object with same property, result is:%b\n",e1==e2);
		System.out.printf("e1 equal to e2? %b\n", e1.equals(e2));
		System.out.printf("e1 equal to e3? %b\n", e1.equals(e3));
	}
}

```

## Lab2Main3
```java
package lab2;

public class Lab2Main3 {
	public static void main(String[] args) {
		int x = 5;
		int y = x;
		System.out.printf("x=%d,y=%d\n", x, y);
		y = y + 5;
		System.out.printf("x=%d,y=%d\n", x, y);
		Employee e1 = new Employee("Mark",50);
		Employee e2 = e1;
		e1.work();
		e2.work();
		e1.addSalary(50);
		e1.work();
		e2.work();
	}
}


```

![](https://i.imgur.com/Mi3Ju7Y.png)


![](https://i.imgur.com/MhyzgNH.png)

# Lab5
```java
package lab5;

public class Course {
	private String id;
	private String name;
	private int duration;
	public Course(String id, String name, int duration) {
		super();
		this.id = id;
		this.name = name;
		this.duration = duration;
	}
	@Override
	public boolean equals(Object obj) {
		Course anotherCourse = (Course) obj;
		return this.id==anotherCourse.id &&
				this.name == anotherCourse.name &&
				this.duration == anotherCourse.duration;
	}
	
	

}


```

# Lab5Main
```java
package lab5;

public class Lab5Main {
	public static void main(String[] args) {
		Course c1 = new Course("001","POOP",35);
		Course c2 = new Course("001","POOP",35);
		System.out.println(c1==c2);
		System.out.printf("c1跟c2視為相等嗎?%b\n",c1.equals(c2));
		Course c3 = c1;
		System.out.printf("c1跟c3視為相等嗎?%b\n",c1.equals(c3));
		Course c4 = new Course("002","POOP",35);
		System.out.printf("c1跟c4視為相等嗎?%b\n",c1.equals(c4));

	}
}

```

# Lab6Main
```java

package lab6;

public class Lab6Main {
	private static final String key1 = "eybjfksdhfjsdhfjksdhjk";
	private static final String cypher1 = "emmxxxyyyzzz123456";
	public void doSomething(String key) {
		if (key==key1) {
			System.out.println("great!");
		}
	}
}

```

# http://java-decompiler.github.io/

# https://github.com/java-decompiler/jd-gui/releases/download/v1.6.6/jd-gui-1.6.6.jar

```
java -jar jd-gui-1.6.6.jar
```

# Lab7Main
```java
package lab7;
class Employee {
	private String name;
	public Employee(String name) {
		super();
		this.name = name;
	}
}
public class Lab7Main {
	public static void main(String[] args) {
		Employee e1 = new Employee("Mark");
		Employee e2 = new Employee("John");
		e2 = e1;
	}
}


```

# Day2

![](https://i.imgur.com/VWQnMTw.png)

```
dir *.class /s
```

```
java lab1.Demo1
```
```
java -version
javac -version
C:\jdk11\bin\java.exe lab1.Demo1
```

# `start.spring.io`

![](https://i.imgur.com/sxiNCqf.png)

![](https://i.imgur.com/V9jsLK5.png)

# 要找的library
```
lombok
devtools
web
thymeleaf
h2
jpa
validation
actuator
```

File/Import
![](https://i.imgur.com/Y6mIGAn.png)

![](https://i.imgur.com/GlFhOAn.png)

![](https://i.imgur.com/ywI7Pli.png)

![](https://i.imgur.com/tCqT31v.png)

```
spring-boot:run
```

# http://localhost:8080/actuator

## `mvnw --version`
## `mvnw dependency:tree`

## explain again about lombok
```
-javaagent:C:\Users\Admin\eclipse\java-2022-12\eclipse\lombok.jar
```

## check env
```
node --version
npm --version
```

![](https://i.imgur.com/VT5Hl0P.png)

![](https://i.imgur.com/LjDUlsS.png)
```
npm install -g @angular/cli
npm list -g
ng version
npm config ls
npm install -g npm
npm list -g
```

![](https://i.imgur.com/Pqkh3xO.png)

![](https://i.imgur.com/cKDzu3x.png)

![](https://i.imgur.com/OYHVCJh.png)

![](https://i.imgur.com/M1ptkmR.png)

```java
package com.ctbcbank.training.demo0;

public class Employee {
	private String lastName;
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	private String firstName;
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public Employee() {
		super();
	}
	public Employee(String lastName, String firstName) {
		super();
		this.lastName = lastName;
		this.firstName = firstName;
	}
	@Override
	public String toString() {
		return String.format("(firstname=%s,lastname=%s)",
				firstName,lastName);
	}
	

}

```

![](https://i.imgur.com/Vm6ltv1.png)

# MyFirstTest.java
```java
package com.ctbcbank.training.demo0;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class MyFirstTest {
	@Test
	public void doTest1() {
		System.out.println("來作點測試吧");
		Assertions.fail("哈哈, 出錯了");
	}
	@Test
	public void doTest2() {
		System.out.println("作更多的測試");
	}

}

```
# Employee.java
```java
package com.ctbcbank.training.demo0;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
	@Getter
	@Setter
	private String lastName;
	@Getter
	@Setter
	private String firstName;
	@Override
	public String toString() {
		return String.format("(firstname=%s,lastname=%s)",
				firstName,lastName);
	}
	

}

```

\![](https://i.imgur.com/VvnX1LE.png

# https://projectlombok.org/
# https://projectlombok.org/features/
# https://projectlombok.org/api/lombok/extern/slf4j/Slf4j

# Lab8Main
```java
package lab8;
class Employee {
	private static int counter=0;
	public Employee() {
		super();
		System.out.printf("生成一個Employee, couter=%d\n",counter);
		counter++;
	}
	public int getCounter() {
		return counter;
	}
}
public class Lab8Main {
	public static void main(String[] args) {
		Employee e1 = new Employee();
		Employee e2 = new Employee();
		Employee e3 = new Employee();

	}
}

```
# Lab11Main
```java
package lab11;

abstract class Employee {
	public int getSalary() {
		return 0;
	}
	abstract void working();
}
class Engineer extends Employee {
	@Override
	void working() {
		System.out.println("R&D");
	}
}
class Manager extends Employee {
	@Override
	void working() {
		System.out.println("managing...");
	}
}
public class Lab11Main {
	public static void main(String[] args) {
		Employee e1 = new Engineer();
		Employee e2 = new Manager();
		Employee[] aiEmployees = {new Manager(),
				new Manager(),
				new Engineer(),
				new Engineer(),
				new Engineer()};
		for (Employee employee : aiEmployees) {			
			employee.working();
		}
		//e2.working();
	}
}


```

# Lab13Main
```java

package lab13;
class Employee {
	public final int gradeLevel;
	Employee() {
		gradeLevel=5;
	}
	Employee(int grade) {
		gradeLevel=grade;
	}
	void increase() {
		//gradeLevel+=1;
	}
}
public class Lab13Main {
	public static void main(String[] args) {
		Employee e1 = new Employee();
		System.out.printf("%d\n",e1.gradeLevel);
		//e1.gradeLevel += 1;
	}
}


```

# Lab14Main
```java

package Lab14;

class Car {
	private String id;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

}

class Driver {
	final Car car;

	public Driver() {
		car = new Car();
	}
}

public class Lab14Main {
	public static void main(String[] args) {
		Driver d1 = new Driver();
		d1.car.setId("ABC-1234");
		System.out.println("車子的id是"+d1.car.getId());
	}
}

```
# Lab15Main
```java
package lab15;
class Car {
	private String id;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
}
class Employee {
	public void doWork() {
		final Car c1 = new Car();
		new Thread(()->{
			c1.setId("hihi");
			//c1 = new Car();
		}).start();
	}
}
public class Lab15Main {
	public static void main(String[] args) {

	}
}



```

# Lab16Main
```java
package lab16;
class Employee {
	private static int count=100;
	static {
		count = 200;
		System.out.println("Employee的static block");
	}
	public Employee() {
		System.out.printf("Employee生成,counter=%d\n",count);
		count++;
	}
}
public class Lab16Main {
	public static void main(String[] args) {
		Employee e1 = new Employee();
		Employee e2 = new Employee();
		Employee e3 = new Employee();
	}
}


```

# Lab17
```java

package lab17;

enum OSType {
	IOS, ANDROID, WINPHONE, BLACKBERRY
};

class OSDetail {
	private OSType type;

	public OSDetail(OSType type) {
		this.type = type;
	}

	public void vendor() {
		switch (type) {
		case WINPHONE:
			System.out.println("Microsoft");
			break;
		case IOS:
			System.out.println("Apple");
			break;
		}
	}
}
public class Lab17Main {
	public static void main(String[] args) {
		OSDetail detail = new OSDetail(OSType.WINPHONE);
		detail.vendor();
		OSDetail detail2 = new OSDetail(OSType.IOS);
		detail2.vendor();
	}
}

```

# Day3
```
cd %JAVA_HOME%
cd bin
dir jconsole*
```
## find your eclipse.ini
![](https://i.imgur.com/qFrXdTQ.png)

## https://visualvm.github.io/download.html
```
-Xms1024m
-Xmx2048m
```

## https://gatling.io/

![](https://i.imgur.com/Dfzi1WT.png)

# Lab17Main.java
```java

package lab17;

enum OSType {
	IOS(10), ANDROID(20), WINPHONE(30), BLACKBERRY(40);
	private int id;

	private OSType(int id) {
		this.id = id;
	}

	public int getId() {
		return id;
	}
	
	
};

class OSDetail {
	private OSType type;

	public OSDetail(OSType type) {
		this.type = type;
		System.out.println("type="+this.type);
	}

	public void vendor() {
		switch (type) {
		case WINPHONE:
			System.out.println("Microsoft, id="+type.getId());
			break;
		case IOS:
			System.out.println("Apple, id="+type.getId());
			break;
		}
	}
}
public class Lab17Main {
	public static void main(String[] args) {
		OSDetail detail = new OSDetail(OSType.WINPHONE);
		detail.vendor();
		OSDetail detail2 = new OSDetail(OSType.IOS);
		detail2.vendor();
	}
}

```

# Lab18Main
```java
package lab18;

interface Racing {
	void run();
}

class Dog implements Racing {
	@Override
	public void run() {
		System.out.println("500m/minute");
	}
}

class Cat implements Racing {
	@Override
	public void run() {
		System.out.println("450m/minute");
	}
}

public class Lab18Main {
	public static void main(String[] args) {
		Dog dog1 = new Dog();
		Dog dog2 = new Dog();
		Cat cat1 = new Cat();
		Cat cat2 = new Cat();
		Cat cat3 = new Cat();
		Racing[] members = { dog1, dog2, cat1, cat2, cat3 };
		for (Racing r : members) {
			r.run();
		}
	}
}

```

# Lab19Main
```java
package lab19;

interface Racing {
	void run();
}

public class Lab19Main {
	public static void main(String[] args) {
		// Racing r1 = new Racing();
		Racing r1 = new Racing() {
			@Override
			public void run() {
				System.out.println("999m/minute");
			}
		};
		r1.run();
		Racing r2 = () -> {
			System.out.println("???m/minute");
		};
		r2.run();
		Racing r3 = () -> System.out.println("200m/minute");
		r3.run();
	}
}

```

# https://martinfowler.com/books/uml.html

# lab20Main
```java
package lab20;

public class Lab20Main {
	public static void main(String[] args) {
		// Object o1 = new Object();
		String x1 = "hello world";
		String y1 = "hello ";
		String y2 = "world";
		//String x2 = y1 + y2;
		String x2 = "hello world";
		System.out.printf("x1 equal to x2? %b\n", x1.equals(x2));
		System.out.printf("x1 is identical to x2?%b\n", x1 == x2);
		String x3 = new String("hello world");
		String x4 = new String("hello world");
		System.out.printf("x3 equal to x4? %b\n", x3.equals(x4));
		System.out.printf("x3 is identical to x4?%b\n", x3 == x4);

	}
}

```
# Lab21Main
```java
package lab21;

public class Lab21Main {
	public static void main(String[] args) {
		String x1 = "hello";
		String x2 = " world";
		for (int i=0; i<5; i++) {			
			x1 = x1+x2;
		}
		System.out.println(x1);
		StringBuilder builder = new StringBuilder("hello");
		for (int i=0; i<5; i++) {
			builder.append(" world");
		}
		System.out.println(builder.toString());
	}

}

```

# Lab22Main
```java
package lab22;

public class Lab22Main {
	public static void main(String[] args) {
		String key = "day";
		String weekDay = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday";
		System.out.printf("第一個day出現在%d\n", weekDay.indexOf(key));
		System.out.printf("最後一個day出現在%d\n", weekDay.lastIndexOf(key));
		int index = 0;
		while (weekDay.indexOf(key, index) > -1) {
			index = weekDay.indexOf(key, index);
			System.out.printf("找到的索引是%d\n", index);
			index += key.length();
		}
	}
}


```

# Lab23
```java
package lab23;

public class Lab23 {
	public static void main(String[] args) {
		String prolog = "Prolog is a logic programming language associated with artificial intelligence and computational linguistics.";
		String matching1 = "FIND:Pro";
		String matching2 = "FIND:is";
		String matching3 = "FIND:IS";
		Boolean result1 = prolog.regionMatches(0, matching1, 5, 3);
		Boolean result2 = prolog.regionMatches(7, matching2, 5, 2);
		Boolean result3 = prolog.regionMatches(true, 7, matching3, 5, 2);
		System.out.printf("result1=%b,result2=%b,result3=%b\n",result1,result2,result3);
	}
}

```

# Lab24
```java
package lab24;

public class Lab24Main {
	public static void main(String[] args) {
		boolean x1 = false;
		int x2 = 123;
		float x3 = 4.5f;
		double x4 = 5.678;
		System.out.printf("x1=%s,x2=%s,x3=%s,x4=%s\n",
				String.valueOf(x1),String.valueOf(x2),String.valueOf(x3),String.valueOf(x4));
		System.out.printf("x1=%b,x2=%d,x3=%.1f,x4=%.3f\n", x1,x2,x3,x4);

	}
}


```
# lab25
```java
package lab25;

public class Lab25Main {
	public static void main(String[] args) {
		String s1 = "hello world java";
		String s2 = "hello_world_java";
		String s3 = "hello\\world\\java";
		String s4 = "hello/world/java";
		for(String s:s1.split(" ")) {
			System.out.printf("[%s]", s);
		}
		System.out.println();
		for(String s:s2.split("_")) {
			System.out.printf("[%s]",s);
		}
		System.out.println();
		for(String s:s4.split("/")) {
			System.out.printf("[%s]",s);
		}
		System.out.println();
		for (String s:s3.split("\\\\")) {
			System.out.printf("[%s]",s);
		}
		System.out.println();
	}
}

```
# Lab26Main
```java
package lab26;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Lab26Main {
	public static void main(String[] args) {
		String s1 = "hello world  java   programming";
		for(String s:s1.split(" ")) {
			System.out.printf("[%s]", s);
		}
		System.out.println();
		Pattern pattern = Pattern.compile("\\w+");
		Matcher matcher = pattern.matcher(s1);
		while(matcher.find()) {
			System.out.printf("找到一筆[%s]\n",matcher.group());
		}
	}
}

```

# Lab28Main
```java
package lab28;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Lab28Main {
	public static void main(String[] args) {
		String s1 = "信義區:11081 11077 11093 11024 段號 0 4 7 9";
		Pattern p1 = Pattern.compile("\\d{5}");
		Matcher m1 = p1.matcher(s1);
		while(m1.find()) {
			System.out.printf("[%s]", m1.group());
		}
	}
}

```
# Lab29Main
```java
package lab29;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Lab29Main {
	public static void main(String[] args) {
		String s1 = "MarkHo:A123456789:0912-345-678, John:K987654321:0911-222-333";
		Pattern p1 = Pattern.compile("[A-Z]\\d{9}");
		Matcher m1 = p1.matcher(s1);
		while(m1.find()) {
			System.out.printf("[%s]",m1.group());
		}
		System.out.println();
		Pattern p2 = Pattern.compile("\\d{4}-\\d{3}-\\d{3}");
		Matcher m2 = p2.matcher(s1);
		while(m2.find()) {
			System.out.printf("[%s]",m2.group());
		}
		System.out.println();
		
	}
}

```

# Lab30Main
```java
package lab30;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Lab30Main {
	public static void main(String[] args) {
		String s1 = "+886-911-222-333, +886-987-654-321";
		Pattern p1 = Pattern.compile("\\+(\\d{3})-(\\d{3})-(\\d{3})-(\\d{3})");
		Matcher m1 = p1.matcher(s1);
		String s2 = m1.replaceAll("0$2-$3-$4");
		System.out.printf("更換過的是:%s\n",s2);
	}
}

```
# Lab31Main
```java
package lab31;

public class Lab31Main {
	public static void main(String[] args) {
		Double pi = 3.1415926879 * 100;
		System.out.printf("%e,%f\n", pi, pi);
		Double ln2 = 6.9314718e-01;
		System.out.printf("%.2e,%.3f\n", ln2, ln2);
	}
}

```

# Lab32Main
```java
package lab32;

import java.io.Console;

public class Lab32Main {
	public static void main(String[] args) {
		System.out.println("輸入些什麼:");
		Console c1 = System.console();
		if (c1 == null) {
			System.err.println("can not get console");
			System.exit(-1);
		}
		c1.printf("你剛才輸入的是:%s\n",c1.readLine());
	}
}

```

# Lab33Main
```java
package lab33;

import java.io.FileReader;
import java.io.IOException;

public class Lab33Main {
	public static void main(String[] args) throws IOException {
		FileReader reader = new FileReader("README");
		// in between
		int c;
		while((c = reader.read())!=-1) {
			System.out.printf("(%d)%c, ", c,c);
		}
		reader.close();
	}
}

```

# Lab35Main
```java
package lab35;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class Lab35Main {
	public static void main(String[] args) throws IOException {
		BufferedWriter writer = new BufferedWriter(new FileWriter("Lab35.output"));
		for (int i = 0; i < 20; i++) {
			String line = String.format("%d,%.4f,%.4f\n", 
					(i + 1), Math.pow(i + 1, 2), Math.sqrt((double) (i + 1)));
			writer.write(line);
		}
		writer.close();
	}
}

```

# Lab36Main
```java
package lab36;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class Lab36Main {
	public static void main(String[] args) throws FileNotFoundException {
		Set<String> words = new TreeSet<>();
		try (Scanner tokenScanner = new Scanner(new FileReader("README"))) {
			tokenScanner.useDelimiter("\\W");
			while (tokenScanner.hasNext()) {
				String w = tokenScanner.next();
				words.add(w);
			}
			for (String w : words) {
				System.out.printf("[%s]", w);
			}
		}
	}
}

```

# Lab37Main
```java
package lab37;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;

public class Lab37Main {
	public static void main(String[] args) {
		Path p1 = Paths.get("C:\\Users\\Admin\\eclipse-workspace\\java_lab1\\README");
		System.out.printf("檔名是:%s\n", p1.getFileName());
		System.out.printf("根路徑是:%s\n", p1.getRoot());
		System.out.printf("上層路徑是:%s\n", p1.getParent());
		for (Path p : p1) {
			System.out.println("sub element:" + p);
		}
	}
}

```

# Lab38Main
```java
package lab38;

import java.nio.file.Path;
import java.nio.file.Paths;

public class Lab38Main {
	public static void main(String[] args) {
		Path p1 = Paths.get("C:\\Users\\Admin\\eclipse-workspace\\java_lab1\\README");
		Path p2 = Paths.get("README");
		System.out.printf("p1 and p2 is equal?%b\n",p1.equals(p2));
		System.out.println(p1.toAbsolutePath());
		System.out.println(p2.toAbsolutePath());
		System.out.println(p1.toAbsolutePath().normalize());
		System.out.println(p2.toAbsolutePath().normalize());
		System.out.printf("absolute path?%b\n",
				p1.toAbsolutePath().normalize().equals(p2.toAbsolutePath().normalize()));
	}
}

```

# Lab39
```java
package lab39;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Lab39Main {
	public static void main(String[] args) throws IOException {
		Path p1 = Paths.get("C:\\Users\\Admin\\eclipse-workspace\\java_lab1\\..\\java_lab1\\README");
		Path p2 = Paths.get("README");
		boolean isSameFile = Files.isSameFile(p1, p2);
		System.out.printf("p1 and p2 are the same? %b\n", isSameFile);
	}
}

```

# Lab41
```java
package lab41;

class TagMaker {
	private Object object;

	public TagMaker(Object object) {
		super();
		this.object = object;
	}

	public Object getObject() {
		return object;
	}

	public void setObject(Object object) {
		this.object = object;
	}

	@Override
	public String toString() {
		return String.format("[**%s**]", object);
	}
}

public class Lab41Main {
	public static void main(String[] args) {
		TagMaker t1 = new TagMaker(100);
		TagMaker t2 = new TagMaker("二百");
		System.out.println(t1);
		System.out.println(t2);
		Integer i1 = (Integer) t1.getObject();
		System.out.println(i1+i1);
		Integer i2 = (Integer)t2.getObject();
	}
}


```

# link for code, env setup
## `https://drive.google.com/drive/folders/1SCGml4Rc0zc6tMj_U8bNgoz_Pg2cUsvB?usp=share_link`

# Day4
![](https://i.imgur.com/uneh59x.png)

### Lab42Main.java
```java
package lab42;

class TagMaker<T> {
	private T object;

	public TagMaker(T object) {
		super();
		this.object = object;
	}

	public T getObject() {
		return object;
	}

	public void setObject(T object) {
		this.object = object;
	}

	@Override
	public String toString() {
		return String.format("[**%s**]", object);
	}
}

public class Lab42Main {
	public static void main(String[] args) {
		TagMaker<Integer> t1 = new TagMaker<Integer>(123);
		TagMaker<Integer> t2 = new TagMaker<Integer>(456);
		TagMaker<String> t3 = new TagMaker<String>("伍百");
		TagMaker<Float> t4 = new TagMaker<Float>(2.34f);
		TagMaker<Double> t5 = new TagMaker<Double>(2.34);
		System.out.println("**" + t1 + t2 + t3 + t4 + t5);
		Integer x1 = t1.getObject();
		int x2 = t1.getObject();
		System.out.printf("x1+x2=%d\f", x1 + x2);
		String x3 = t3.getObject();
		System.out.printf("x3+x3=%s \f", x3 + x3);
	}
}

```

### Lab43
```java
package lab43;

import java.util.ArrayList;
import java.util.List;

public class Lab43Main {
	// 把value填進list裡, 但value可能是....型態
	public static <T> void fill(List<T> list, T value) {
		for (int i = 0; i < list.size(); i++) {
			list.set(i, value);
		}
	}

	public static void main(String[] args) {
		List<Integer> l1 = new ArrayList<Integer>();
		// List<Integer> l2 = new List<Integer>();
		// ArrayList<Integer> l3 = new ArrayList<Integer>();
		l1.add(100);
		l1.add(100);
		l1.add(200);
		l1.add(200);
		l1.add(300);
		System.out.println("original list:" + l1);
		Integer[] a1 = { 100, 100, 200, 200, 300 };
		System.out.println("origianl array:" + a1);
		fill(l1, 777);
		System.out.println("填完後, l1=" + l1);
	}
}

```

![](https://i.imgur.com/G1fSVaG.png)

### Lab44
```java
package lab44;

import java.util.ArrayList;
import java.util.List;

public class Lab44Main {
	private static Integer handleList(List<Integer> list) {
		Integer x1 = 0;
		for (Integer x : list) {
			x1 += x;
		}
		return x1;
	}

	private static void displayList(List<?> list) {
		//Integer x1 = 0;
		for (Object i : list) {
			System.out.printf("{%s}\n", i);
			//x1 += i;
		}
	}

	public static void main(String[] args) {
			List<Number> l1 = new ArrayList<Number>();
			l1.add(123);
			l1.add(45.6);
			List<String> l2 = new ArrayList<String>();
			l2.add("123");
			l2.add("45.6");
			displayList(l1);
			displayList(l2);
	}
}


```

### Lab45
```java
package lab45;

import java.util.ArrayList;
import java.util.List;

public class Lab45Main {
	public static Double summation(List<? extends Number> numberList) {
		Double result = 0.0;
		for (Number n : numberList) {
			result += n.doubleValue();
		}
		return result;
	}

	public static void main(String[] args) {
		List<Integer> l1 = new ArrayList<>();
		List<Double> l2 = new ArrayList<>();
		for (int i = 1; i < 6; i++) {
			l1.add(i * i);
			l2.add(Math.sqrt((double) i * 100));
		}
		System.out.println("l1=" + l1);
		System.out.println("l2=" + l2);
		System.out.printf("l1的總合是%f\n", summation(l1));
		System.out.printf("l2的總合是%f\n", summation(l2));
	}
}


```

## Lab46
```java
package lab46;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Lab46Main {
	public static void main(String[] args) {
		List<Integer> items = new ArrayList<Integer>();
		for (int i = 0; i < 10; i++) {
			items.add(i * i);
		}
		// use a verbose way
//		Iterator<Integer> removeIterator = items.iterator();
//		while (removeIterator.hasNext()) {
//			Integer itemToRemove = removeIterator.next();
//			System.out.printf("要移的是:%d\n", itemToRemove);
//			removeIterator.remove();
//			System.out.println("留下的是:" + items);
//		}
		// link together
		for (Iterator<Integer> iterator = items.iterator(); iterator.hasNext();) {
			iterator.next();
			iterator.remove();
			System.out.println("items=" + items);

		}

	}
}

```

# Lab47Main
```java
package lab47;

import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class Lab47Main {
	public static void main(String[] args) {
		String s1 = "abcdefg1234567";
		StringBuilder b1 = new StringBuilder();
		StringBuilder b2 = new StringBuilder();
		List<Character> l1 = new LinkedList<Character>();
		for (char c1 : s1.toCharArray()) {
			l1.add(c1);
		}
		System.out.println("l1是:" + l1);
		ListIterator<Character> i1 = l1.listIterator(l1.size());
		while(i1.hasPrevious()) {
			char c = i1.previous();
			b1.append(c);
		}
		System.out.println("結果是:"+b1.toString());
		ListIterator<Character> i2 = l1.listIterator(7);
		while(i2.hasNext()) {
			char c = i2.next();
			b2.append(c);
		}
		System.out.println("i2的結果是"+b2.toString());
	}
}

```

### Lab48Main
```java
package lab48;

import java.util.HashSet;
import java.util.Set;

public class Lab48Main {
	public static void main(String[] args) {
		String logs = "ken ken mark mark john ken mark tim ken";
		Set<String> candidates = new HashSet<String>();
		for (String log : logs.split("\\W+")) {
			candidates.add(log);
		}
		System.out.println("過濾掉重複後是:"+candidates);
	}
}

```

### Lab49
```java
package lab49;

import java.util.HashSet;
import java.util.Set;

public class Lab49Main {
	public static void main(String[] args) {
		//Set<Character> s1 = new TreeSet<Character>();
		Set<Character> s1 = new HashSet<Character>();
		String string1 = "Prolog is a logic programming language associated with artificial intelligence and computational linguistics.";
		for (char c:string1.toCharArray()) {
			s1.add(c);
		}
		System.out.println("用了哪些字元?"+s1);
	}
}

```

### Lab50
```java

package lab50;

import java.util.HashMap;
import java.util.Map;

public class Lab50Main {
	public static void main(String[] args) {
		Map<String, String> phoneBook = new HashMap<String, String>();
		phoneBook.put("Mark", "111-1111");
		phoneBook.put("Ken", "222-2222");
		phoneBook.put("Tim", "333-3333");
		for (String k : phoneBook.keySet()) {
			System.out.printf("key=%s,value=%s\n", k, phoneBook.get(k));
		}
		Map<String, Integer> earning = new HashMap<>();
		earning.put("Mark", 30);
		earning.put("ken", 20);
		earning.put("Tim",50);
		for (String k:earning.keySet()) {
			System.out.printf("key=%s,earning=%d\n",k,earning.get(k));
		}
	}
}

```

### Lab51
```java

package lab51;

class Rectangle {
	private int x, y, width, height;

	public Rectangle(int x, int y, int width, int height) {
		super();
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
	}

	@Override
	public String toString() {
		return String.format("[%d,%d], width=%d, height=%d\n", this.x, this.y, this.width, this.height);
	}
}

public class Lab51Main {

}

```

### Lab51
```java
package lab51;

import java.util.HashSet;
import java.util.Set;

class Rectangle {
	private int x, y, width, height;

	public Rectangle(int x, int y, int width, int height) {
		super();
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
	}

	@Override
	public String toString() {
		return String.format("[%d,%d], width=%d, height=%d", this.x, this.y, this.width, this.height);
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == null) {
			return false;
		}
		if (obj == this) {
			return true;
		}
		if (obj instanceof Rectangle) {
			Rectangle rect2 = (Rectangle) obj;
			if ((this.x == rect2.x) && (this.y == rect2.y) && (this.width == rect2.width)
					&& (this.height == rect2.height)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public int hashCode() {
		return String.format("[%d,%d],(%d,%d)", x, y, width, height).hashCode();
		// return x | y << 8 | width << 16 | height << 24;

	}
}

public class Lab51Main {
	public static void main(String[] args) {
		Rectangle r1 = new Rectangle(1, 1, 2, 2);
		Rectangle r2 = new Rectangle(1, 1, 2, 2);
		Rectangle r3 = new Rectangle(2, 2, 3, 4);
		Rectangle r4 = r3;
		System.out.printf("r1 hash=%s\n", Integer.toHexString(r1.hashCode()).toUpperCase());
		System.out.printf("r2 hash=%s\n", Integer.toHexString(r2.hashCode()).toUpperCase());
		System.out.printf("r3 hash=%s\n", Integer.toHexString(r3.hashCode()).toUpperCase());
		System.out.printf("r4 hash=%s\n", Integer.toHexString(r4.hashCode()).toUpperCase());
		System.out.printf("==, r1==r2? %b, r1==r3? %b\n", r1 == r2, r1 == r3);
		System.out.printf("==, r3==r4? %b\n", r3 == r4);
		System.out.printf("r1 equal to r2? %b, r1 equal to r3? %b\n", r1.equals(r2), r1.equals(r3));
		System.out.printf("r3 equal to r4? %b\n", r3.equals(r4));
		Set<Rectangle> s1 = new HashSet<>();
		s1.add(r1);
		System.out.printf("[1] set1 has %s\n", s1);
		s1.add(r2);
		System.out.printf("[2] set1 has %s\n", s1);
		s1.add(r3);
		System.out.printf("[3] set1 has %s\n", s1);
		s1.add(r4);
		System.out.printf("[4] set1 has %s\n", s1);
	}
}

```

# Lab52
```java
package lab52;

public class Lab52Main {
	public static void main(String[] args) {
		if (args.length == 0) {

		} else {
			for (String argument : args) {
				System.out.println("command line parameter:" + argument);
			}
		}
	}
}

```

# Lab52
```java

package lab52;

public class Lab52Main {
	public static void main(String[] args) {
		if (args.length == 0) {
//			System.err.println("需要更多參數");
//			System.exit(1);
			// 1lI
			throw new IllegalArgumentException("需要更多參數");
		} else {
			for (String argument : args) {
				System.out.println("command line parameter:" + argument);
			}
		}
		System.out.println("依照參數進行如下的處理");
	}
}

```

### https://github.com/adobe-fonts/source-code-pro/releases/tag/2.038R-ro%2F1.058R-it%2F1.018R-VAR

## lab53
```java
package lab53;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Lab53Main {
	public static void main(String[] args) {
		System.out.println("read from input");
		Scanner scanner = new Scanner(System.in);	
		try {
			System.out.println("your input is:"+scanner.nextInt());			
		}catch(InputMismatchException ime) {
			System.out.println("格式錯誤");
			ime.printStackTrace();
		}	
		scanner.close();
		System.out.println("close scanner");
	}
}


```

# Lab55
```java
package lab55;

import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class Lab55Main {
	public static void main(String[] args) {
		// String s1 = "abc";
		String s1 = "";
		System.out.println("read from s1");
		Scanner scanner = new Scanner(s1);
		scanner.close();
		try {
			System.out.println("your input is:" + scanner.nextInt());
		} catch (InputMismatchException ime) {
			System.out.println("格式錯誤");
			ime.printStackTrace();
		} catch (NoSuchElementException|IllegalStateException e) {
			System.out.println("元件不存在, 或狀態不正常");
			e.printStackTrace();
		} 
		scanner.close();
		System.out.println("close scanner");

	}
}

```

### Lab55
```java
package lab55;

import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class Lab55Main {
	public static void main(String[] args) {
		// String s1 = "abc";
		String s1 = "";
		System.out.println("read from s1");
		Scanner scanner = new Scanner(s1);
		scanner.close();
		try {
			int p = 1/0;
			System.out.println("your input is:" + scanner.nextInt());
		} catch (InputMismatchException ime) {
			System.out.println("格式錯誤");
			ime.printStackTrace();
		} catch (NoSuchElementException|IllegalStateException e) {
			System.out.println("元件不存在, 或狀態不正常");
			e.printStackTrace();
		} catch(Exception e) {
			System.out.println("其餘沒有處理到的例外發生了");
			e.printStackTrace();
		}
		scanner.close();
		System.out.println("close scanner");

	}
}

```
### Lab57
```java
package lab57;

public class Lab57Main {
	static int factorial(int seed) {
		int result = 0;
		if (seed == 0) {
			result = 1;
			return result;
		}
		result = factorial(seed-1)*seed;
		return result;
	}
	public static void main(String[] args) {
		System.out.println("factorial 5="+factorial(5));
	}
}

```

# Lab59
```java
package lab59;

class MyRunnable implements Runnable {

	@Override
	public void run() {
		System.out.println("準備工作");
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("工作結束");
		
	}
	
}

public class Lab59Main {
	public static void main(String[] args) {

	}
}

```

# Lab60
```java
package lab60;

public class Lab60Main {
	public static void main(String[] args) {
		System.out.println("啟動五個執行緒");
		for(int i=0; i<5; i++) {
			Thread t1 = new Thread(()->{
				System.out.println("開始執行緒工作");
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("結束執行緒工作");
			});
			t1.start();
		}
		System.out.println("主執行緒結束");
	}
}

```

# Day5

### https://www.wiley.com/en-us/Expert+One+on+One+J2EE+Development+without+EJB-p-9780764573903

### https://community.pivotal.io/s/topic/0TO0P000000IKdeWAG/spring?language=en_US

```
git --version
```

## https://git-scm.com/

## https://git-scm.com/book/zh-tw/v2/%E9%96%8B%E5%A7%8B-%E5%88%9D%E6%AC%A1%E8%A8%AD%E5%AE%9A-Git

## set username,email
```
git config --global user.name "Mark Ho"
git config --global user.email "mark@patristar.com"
more .gitconfig
```

# start.spring.io

![](https://i.imgur.com/PUBoqbm.png)

![](https://i.imgur.com/1uqJJsy.png)

![](https://i.imgur.com/pdV7Nz1.png)

![](https://i.imgur.com/zj842W2.png)

![](https://i.imgur.com/svxlNMA.png)

![](https://i.imgur.com/c3s7FAR.png)

```
spring-boot:run
```

![](https://i.imgur.com/UMhMKv3.png)

![](https://i.imgur.com/2ZyiubJ.png)

![](https://i.imgur.com/S4FIeTC.png)

![](https://i.imgur.com/m97sGBK.png)

![](https://i.imgur.com/7IY0gB5.png)


![](https://i.imgur.com/1OuxDOz.png)



![](https://i.imgur.com/fClVzpW.png)

![](https://i.imgur.com/3PAmXFZ.png)

![](https://i.imgur.com/qnGanpi.png)

![](https://i.imgur.com/0zwF8BZ.png)

# RootController
```java
package com.ctbcbank.training.boot_lab3;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class RootController {
	@GetMapping("/")
	public String index() {
		return "home";
	}
}

```

# day5創建的專案

### `https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.7.8&packaging=jar&jvmVersion=11&groupId=com.ctbcbank.training&artifactId=boot_lab3&name=boot_lab3&description=Demo%20project%20for%20Spring%20Boot&packageName=com.ctbcbank.training.boot_lab3&dependencies=devtools,lombok,web,thymeleaf,data-jpa,h2,validation`

```html
<!DOCTYPE html>
<html>
<body>
<h1>Hello Spring Boot</h1>
</body>
</html>
```

![](https://i.imgur.com/ruNKScS.png)

![](https://i.imgur.com/RojlG95.png)

# 
```
http://localhost:8080/
http://localhost:8080/images/tool_owl.svg
```

```html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org">
<body>
	<h1>Hello Spring Boot</h1>
	<h2>正常html</h2>
	<img src="/images/tool_owl.svg" />
	<br/>
	<h2>thymeleaf template</h2>
	<img th:src="@{/images/tool_owl.svg}">
</body>
</html>
```

```
package
```
```
java -jar boot_lab3-0.0.1-SNAPSHOT.jar
```
```
mvnw clean
mvnw package
java -jar ....jar
```
```
java -jar target\boot_lab3-0.0.1-SNAPSHOT.jar --server.port=8088
```

```
java -jar target\boot_lab3-0.0.1-SNAPSHOT.jar --server.servlet.context-path=/ctbc
```

```
http://localhost:8080/ctbc/
```

```xml
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-surefire-plugin -->
<dependency>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.1</version>
</dependency>

```

```
mvnw --version
mvnw dependency:tree
mvnw dependency:tree -Dverbose
```
# home.html
```html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org">
<body>
	<h1>從controller接收的訊是</h1>
	<H2 th:text="${message}"></H2>
	<h1>Hello Spring Boot</h1>
	<h2>正常html</h2>
	<img src="/images/tool_owl.svg" />
	<br/>
	<h2>thymeleaf template</h2>
	<img th:src="@{/images/tool_owl.svg}">
</body>
</html>
```

![](https://i.imgur.com/NxGB2fi.png)

```java
package com.ctbcbank.training.boot_lab3;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class BootLab3ApplicationTests {
	@Autowired
	private RootController controller;

	@Test
	void contextLoads() {
		assertThat(controller).isNotNull();
		//assertThat(controller).isNull();
	}

}

```

# RootControllerTest
```java
package com.ctbcbank.training.boot_lab3;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
//import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.hamcrest.Matchers.containsString;
@SpringBootTest
@AutoConfigureMockMvc
public class RootControllerTest {
	@Autowired
	private MockMvc mockMvc;
	@Test
	public void checkCondition() {
		assertThat(mockMvc).isNotNull();
	}
	@Test
	public void testEndpoing1() throws Exception {
		mockMvc.perform(get("/"))
		.andExpect(status().isOk())
		.andExpect(view().name("home"))
		.andExpect(content().string(containsString("controllerx")));
	}
	@Test
	public void testEndpoing3() throws Exception {
		mockMvc.perform(get("/"))
		.andExpect(status().isOk())
		.andExpect(view().name("home"));
	}
	@Test
	public void testEndpoint2() throws Exception {
		mockMvc.perform(get("/admin"))
		.andExpect(status().isNotFound());
	}

}


```

# 台中week2 finish
### https://drive.google.com/file/d/1X7w9OvNciKFBjFZAC5OaoDQcmLOJoZ7S/view?usp=share_link

# 台中week3
## Day6
### commit code so far
```
新增MVC的測試
```

```
重構程式的套件
實作Service
在Controller中使用Service
使用ResponseBody作傳回
```
# RootControllerServiceTest.java
```java
package com.ctbcbank.training.boot_lab3;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;

@SpringBootTest
@AutoConfigureMockMvc
public class RootControllerServiceTest {
	//@Autowired
	private MockMvc mockMvc;
	@Test
	public void mockMvcNotNull() {
		Assertions.assertNotNull(mockMvc);
	}
}

```

# InfoController.java
```java

package com.ctbcbank.training.boot_lab3.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class InfoController {
	@GetMapping("/info")
	public @ResponseBody String getInfo() {
		return "I am healthy";
	}
}


```

# ExplainErrorFailufeTest
```java
package com.ctbcbank.training.boot_lab3;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class ExplainErrorFailureTest {
	@Test
	public void test1() {
		
	}
	@Test
	public void test2() {
		// something exception happened
		//int x = 1/0;
		throw new Error("HAHAHA");
	}
	@Test
	public void test3() {
		// assertions happened
		Assertions.fail("HoHoHo");
	}
}

```

# RootController
```java
package com.ctbcbank.training.boot_lab3;

import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import com.ctbcbank.training.boot_lab3.service.GreetingService;

@WebMvcTest
public class RootControllerServiceTest {
	@Autowired
	private MockMvc mockMvc;
	@MockBean
	private GreetingService service;
	@Test
	public void mockMvcNotNull() {
		Assertions.assertNotNull(mockMvc);
	}
	@Test
	public void validControllerWithService() throws Exception {
		when(service.greet()).thenReturn("This is called by mock testing");
		this.mockMvc.perform(get("/greet")).andDo(MockMvcResultHandlers.print());
	}
}


```

# ValidationApiTest
```java
package com.ctbcbank.training.boot_lab3;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import com.ctbcbank.training.boot_lab3.model.NormalUser1;

public class ValidationApiTest {
	private static Validator validator;
	@BeforeAll
	public static void setupValidator() {
		validator = Validation.buildDefaultValidatorFactory().getValidator();
	}
	@Test
	public void test1() {
		NormalUser1 user1 = new NormalUser1(null);
		Set<ConstraintViolation<NormalUser1>> violations = 
				validator.validate(user1);
		Assertions.assertEquals(violations.size(), 1);
	}
	@Test
	public void test2() {
		NormalUser1 user1 = new NormalUser1("");
		Set<ConstraintViolation<NormalUser1>> violations = 
				validator.validate(user1);
		Assertions.assertEquals(violations.size(), 0);
	}
	@Test
	public void test3() {
		NormalUser1 user1 = new NormalUser1("      ");
		Set<ConstraintViolation<NormalUser1>> violations = 
				validator.validate(user1);
		Assertions.assertEquals(violations.size(), 0);
	}


}


```

# NormalUser2.java
```java
package com.ctbcbank.training.boot_lab3.model;

import javax.validation.constraints.NotEmpty;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class NormalUser2 {
	@NotEmpty(message="name should not be empty")
	private String name;
}

```

# ValidationEmptyTest.java
```java

package com.ctbcbank.training.boot_lab3;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import com.ctbcbank.training.boot_lab3.model.NormalUser2;

public class ValidationEmptyTest {
	private static Validator validator;
	@BeforeAll
	public static void setupValidator() {
		validator = Validation.buildDefaultValidatorFactory().getValidator();
	}
	@Test
	public void test1() {
		NormalUser2 user = new NormalUser2(null);
		Set<ConstraintViolation<NormalUser2>> violations = validator.validate(user);
		Assertions.assertEquals(1, violations.size());
	}
	@Test
	public void test2() {
		NormalUser2 user = new NormalUser2("");
		Set<ConstraintViolation<NormalUser2>> violations = validator.validate(user);
		Assertions.assertEquals(1, violations.size());
	}
	@Test
	public void test3() {
		NormalUser2 user = new NormalUser2("       ");
		Set<ConstraintViolation<NormalUser2>> violations = validator.validate(user);
		Assertions.assertEquals(0, violations.size());
	}

}


```

# CourseForm.html

# CourseController.java
```java

package com.ctbcbank.training.boot_lab3.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import lombok.extern.slf4j.Slf4j;

@Controller
@Slf4j
public class CourseController {
	@GetMapping("/course")
	public String showHTML() {
		return "courseForm";
	}
	
}


```

# http://localhost:8080/course

```html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF8">
<title>Insert title here</title>
</head>
<body>
	<h1>課程表單(資料從controller中來)</h1>
	<form th:object="${courseForm}">
		<table>
			<tr>
				<td>CourseId</td>
				<td><input type="text" th:field=""/></td>
			</tr>
			<tr></tr>
			<tr></tr>
			<tr></tr>
		</table>
	</form>
</body>
</html>
```

# CourseForm.java
```java
package com.ctbcbank.training.boot_lab3.model;

import lombok.Data;

@Data
public class CourseForm {
private String courseId;
private String courseName;
private Integer duration;
}

```

# CourseController.java
```java
package com.ctbcbank.training.boot_lab3.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import com.ctbcbank.training.boot_lab3.model.CourseForm;

import lombok.extern.slf4j.Slf4j;

@Controller
@Slf4j
public class CourseController {
	@GetMapping("/course")
	public String showHTML(CourseForm courseForm) {
		courseForm.setCourseId("abc-1234");
		log.info("course form html will be called");
		return "courseForm";
	}
	
}

```

# CourseForm.html

```html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF8">
<title>Insert title here</title>
</head>
<body>
	<h1>課程表單(資料從controller中來)</h1>
	<form th:object="${courseForm}">
		<table>
			<tr>
				<td>CourseId</td>
				<td><input type="text" th:field="*{courseId}"/></td>
			</tr>
			<tr></tr>
			<tr></tr>
			<tr></tr>
		</table>
	</form>
</body>
</html>
```
# CourseController.java
```java
package com.ctbcbank.training.boot_lab3.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import com.ctbcbank.training.boot_lab3.model.CourseForm;

import lombok.extern.slf4j.Slf4j;

@Controller
@Slf4j
public class CourseController {
	@GetMapping("/course")
	public String showHTML(CourseForm courseForm) {
		log.info("course form html will be called");
		return "courseForm";
	}
	@PostMapping("course")
	public String checkCourseInfo(CourseForm courseForm) {
		log.info("從表單傳回controller的物件是;{}",courseForm);
		return "courseForm"; //這邊待會會改成其它網頁
	}
	
}

```
# result.html
```html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF8">
<title>新增資料成功</title>
</head>
<body>
	<h1>資料被完整的新增了</h1>
</body>
</html>
```
# CourseForm.html
```html
package com.ctbcbank.training.boot_lab3.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.ctbcbank.training.boot_lab3.model.CourseForm;

import lombok.extern.slf4j.Slf4j;

@Controller
@Slf4j
public class CourseController implements WebMvcConfigurer {
	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/result").setViewName("result");

	}
	
	@GetMapping("/course")
	public String showHTML(CourseForm courseForm) {
		log.info("course form html will be called");
		return "courseForm";
	}
	@PostMapping("course")
	public String checkCourseInfo(CourseForm courseForm) {
		log.info("from course form,controller is;{}",courseForm);
		return "redirect:/result"; //這邊待會會改成其它網頁
	}
	
}

```

# CourseForm.html
```java
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF8">
<title>Insert title here</title>
</head>
<body>
	<h1>課程表單(資料從controller中來)</h1>
	<form method="post" th:action="@{/course}" th:object="${courseForm}">
		<table>
			<tr>
				<td>CourseId</td>
				<td><input type="text" th:field="*{courseId}" /></td>
				<td th:errors="*{courseId}">Course ID Error will show here</td>
			</tr>
			<tr>
				<td>CourseName</td>
				<td><input type="text" th:field="*{courseName}" /></td>
				<td th:errors="*{courseName}">Course Name Error will show here</td>
			</tr>
			<tr>
				<td>duration</td>
				<td><input type="number" th:field="*{duration}" /></td>
				<td th:errors="*{duration}">duration error will show here</td>
			</tr>
			<tr>
				<td>
					<button type="submit">Submit</button>
				</td>
			</tr>
		</table>
	</form>
</body>
</html>
```

# build and install
```
mvnw clean
mvnw package
mvnw install
```
## generate a better maven report
```
mvnw surefire-report:report

```

## open javamelody dependency
* https://mvnrepository.com/artifact/net.bull.javamelody/javamelody-spring-boot-starter


```
<!-- https://mvnrepository.com/artifact/net.bull.javamelody/javamelody-spring-boot-starter -->
<dependency>
    <groupId>net.bull.javamelody</groupId>
    <artifactId>javamelody-spring-boot-starter</artifactId>
    <version>1.92.0</version>
</dependency>

```

# add itext support

```xml
<!-- https://mvnrepository.com/artifact/com.lowagie/itext -->
<dependency>
    <groupId>com.lowagie</groupId>
    <artifactId>itext</artifactId>
    <version>2.1.7</version>
</dependency>

```

```
https://chrome.google.com/webstore/category/extensions?hl=zh-TW
```

```
https://chrome.google.com/webstore/detail/json-viewer/gbmdgpbipfallnflgajpaliibnhdgobh?hl=zh-TW
```

```
management.endpoints.web.exposure.include=*
```
# day7
* http://localhost:8080/actuator
* http://localhost:8080/actuator/beans

* 打開jconsole

```
-Dspring.jmx.enabled=true
```

* mvnw package
* java -Dspring.jmx.enabled=true -jar boot_lab3-0.0.1-SNAPSHOT.jar

## 如果會出錯
```
<project xmlns="http://maven.apache.org/POM/4.0.0" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

```
## 加上https
```
<project xmlns="https://maven.apache.org/POM/4.0.0" 
         xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

```

### 參考的stackoverflow
* https://stackoverflow.com/questions/70692260/cvc-elt-1-a-cannot-find-the-declaration-of-element-project
* https://www.advancedrestclient.com/
* https://github.com/advanced-rest-client/arc-electron/releases/download/v17.0.9/arc-setup.exe
* https://curl.se/

![](https://i.imgur.com/rWV5vFN.png)

* https://www.postman.com/
* ApiController.java
```java
package com.ctbcbank.training.boot_lab3.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ctbcbank.training.boot_lab3.model.CourseForm;

@RestController
@RequestMapping("/api")
public class ApiController {
	@GetMapping("/")
	public String apiRoot() {
		return "api";
	}

	@GetMapping("/course1")
	public CourseForm getCourse() {
		CourseForm form = new CourseForm();
		form.setCourseId("POOP");
		form.setCourseName("Python OOP");
		form.setDuration(35);
		return form;
	}
}

```
### 目前的application.properties
```
management.endpoints.web.exposure.include=*
server.port=8880
```
### GreetingController
```java
package com.ctbcbank.training.boot_lab3.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class GreetingController {
	private static final String NAME = "name";
	private static final String PROMPT = "prompt";
	// @RequestMapping("/greeting")
	// @GetMapping("/greeting")
	@RequestMapping(path = "/greeting", method = RequestMethod.GET)
	public String greeting(
			@RequestParam(value = "greeting_name",
			required = false,
			defaultValue = "ctbc!!") String name,
			@RequestParam(value = "prompt",
			required = false, 
			defaultValue = "你好") String prompt,
			Model model) {
		model.addAttribute(NAME, name);
		model.addAttribute(PROMPT, prompt);
		return "greeting";
	}
    
}



```

# ExplainDIRunner

```java


package com.ctbcbank.training.boot_lab3.runner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class ExplainDIRunner implements CommandLineRunner {
	@Autowired
	private ApplicationContext context;

	@Override
	public void run(String... args) throws Exception {
		log.info("test DI in this runner, context={}", context);

	}

}


```

# AppConfig.java

```java
package com.ctbcbank.training.boot_lab3.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.ctbcbank.training.boot_lab3.calculator.AddCalculator;
import com.ctbcbank.training.boot_lab3.calculator.Calculator;

@Configuration
public class AppConfig {
	@Bean
	Calculator getAddCalculator() {
		return new AddCalculator();
	}

}

```

![](https://i.imgur.com/mm7aon8.png)


# Message.java
```java
package com.ctbcbank.training.boot_lab3.model;

import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@Data
public class Message {
	private int id;
	private String name;
}


```

# 三月七日完結
* https://drive.google.com/file/d/1HlCorMfBQiXxSDFESF0jpV_d9RlyU7rn/view?usp=share_link

# Day8

* https://start.spring.io/


![](https://i.imgur.com/CDePNWw.png)


* http://localhost:8080/h2-console


# JDBCRunner1
```java
package com.ctbcbank.training.boot_lab4.runner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class JDBCRunner1 implements CommandLineRunner {
	@Autowired
	private NamedParameterJdbcTemplate template;
	private static final String SQL1 = "SELECT 666+222";

	@Override
	public void run(String... args) throws Exception {
		log.info("[1]test something for jdbc");
		SqlParameterSource parameter = new MapSqlParameterSource();
		Integer result = template.queryForObject(SQL1, parameter, Integer.class);
		log.info("{} result is {}", SQL1, result);

	}

}


```
# JDBCRunner2.java
```java

package com.ctbcbank.training.boot_lab4.runner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@Order(2)
public class JDBCRunner2 implements CommandLineRunner {
	@Autowired
	private NamedParameterJdbcTemplate template;
	private static final String SQL1 = "SELECT :a + :b - :c * :d";
	@Override
	public void run(String... args) throws Exception {
		log.info("[2]test other things...");
		SqlParameterSource parameter = 
				new MapSqlParameterSource()
				.addValue("a", 100)
				.addValue("b", 200)
				.addValue("c", 300)
				.addValue("d", 400);
		Integer result = template.queryForObject(SQL1, 
				parameter, Integer.class);
		log.info("{} is {}",SQL1,result);
		
	}
	
}

```

# to version control (git)
## 
![](https://i.imgur.com/BHrdEsC.png)

![](https://i.imgur.com/QKKPt0l.png)

# JDBCRunner3.java
```java 
package com.ctbcbank.training.boot_lab4.runner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class JDBCRunner3 implements CommandLineRunner{
	private static final String U1 = "Mark password1";
	private static final String U2 = "John password2";
	private static final String U3 = "Ken password3";
	private static final String U4 = "Tim password4";
	private static final String DROP_DDL1 = "DROP TABLE users IF EXISTS";
	private static final String CREATE_DDL1 = 
	"CREATE TABLE USERS(id SERIAL, username VARCHAR(255), password VARCHAR(255))";
	@Autowired
	private JdbcTemplate template;
	@Override
	public void run(String... args) throws Exception {
		log.info("execute jdbc runner3");
		template.execute(DROP_DDL1);
		template.execute(CREATE_DDL1);
	}

}

```
# JDBCRunner3
```java 
package com.ctbcbank.training.boot_lab4.runner;

import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class JDBCRunner3 implements CommandLineRunner{
	private static final String U1 = "Mark password1";
	private static final String U2 = "John password2";
	private static final String U3 = "Ken password3";
	private static final String U4 = "Tim password4";
	private static final String DROP_DDL1 = "DROP TABLE users IF EXISTS";
	private static final String CREATE_DDL1 = 
	"CREATE TABLE USERS(id SERIAL, username VARCHAR(255), password VARCHAR(255))";
	@Autowired
	private JdbcTemplate template;
	@Override
	public void run(String... args) throws Exception {
		log.info("execute jdbc runner3");
		template.execute(DROP_DDL1);
		template.execute(CREATE_DDL1);
		List<Object[]> splitUpNamePassword = Arrays.asList(U1,U2,U3,U4).stream()
				.map(new Function<String,String[]>() {
					@Override
					public String[] apply(String t) {
						return t.split(" ");
					}})
				.collect(Collectors.toList());
		log.info("split up name and password:{}",splitUpNamePassword);
		String[][] x1 = {{"hello"},{"world"}};
		//Arrays.asList(x1);
		log.info("x1={}",Arrays.asList(x1));
		Integer[][] x2 = {{1},{2}};
		log.info("x2={}",Arrays.asList(x2));
		Integer[] x3 = {1,2,3,4,5};
		log.info("x3={}",x3);
		List<Integer> l3 = Arrays.asList(x3);
		log.info("l3={}",l3);
		Integer[][] x4 = {{1,2},{3,4}};
		log.info("x4={}",x4);
		log.info("l4={}",Arrays.asList(x4));
	}

}

```
# JDBCRunner4
```java
package com.ctbcbank.training.boot_lab4.runner;

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class JDBCRunner4 implements CommandLineRunner {
	private static final String U1 = "Mark password1";
	private static final String U2 = "John password2";
	private static final String U3 = "Ken password3";
	private static final String U4 = "Tim password4";
	private static final String DROP_DDL1 = "DROP TABLE users IF EXISTS";
	private static final String CREATE_DDL1 = "CREATE TABLE USERS(id SERIAL, username VARCHAR(255), password VARCHAR(255))";
	private static final String INSER_SQL = "INSERT INTO USERS(username, password) VALUES(?,?)";
	@Autowired
	private JdbcTemplate template;

	@Override
	public void run(String... args) throws Exception {
		log.info("execute jdbc runner3");
		template.execute(DROP_DDL1);
		template.execute(CREATE_DDL1);
		List<Object[]> splitUpNamePassword = Arrays.asList(U1, U2, U3, U4)
				.stream().map(string1 -> string1.split(" "))
				.collect(Collectors.toList());
		log.info("split up name and password:{}", splitUpNamePassword);
		splitUpNamePassword.forEach(userArray ->
		log.info("username:{},password:{}", userArray[0], userArray[1]));
		Arrays.asList(U1, U2, U3, U4).stream()
		.map(string1 -> string1.split(" "))
		.forEach(a->log.info("**{}/{}",a[0],a[1]));
		template.batchUpdate(INSER_SQL, splitUpNamePassword);
	}

}


```
# JDBCRunner5.java
```java 
package com.ctbcbank.training.boot_lab4.runner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.ctbcbank.training.boot_lab4.bean.User;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class JDBCRunner5 implements CommandLineRunner {
	@Autowired
	private JdbcTemplate template;
	private static final String SELECT_SQL1 = "SELECT * FROM users";
	private static final String SELECT_SQL2 = "SELECT id, username, password FROM users WHERE username = ?";

	@Override
	public void run(String... args) throws Exception {
		log.info("[5] query all");
		template.query(SELECT_SQL1, 
				(rs,rowNum)->{
					return new User(rs.getString("username"),rs.getString("password"));
					})
		.forEach(u->log.info("user={}",u));
		log.info("[5] conditional query ==> query only name==Mark");
		template.query(SELECT_SQL2, new Object[] {"Mark"} ,
				(rs,rowNum)->{
			return new User(rs.getString("username"),rs.getString("password"));
		}).forEach(u->log.info("only mark:==>{}",u));
		
		
	}

}



```
![](https://i.imgur.com/5HwPonX.png)

# `schema.sql`
```
CREATE TABLE USERS2(id serial PRIMARY KEY,
username VARCHAR(255), password VARCHAR(255));
```

# `data.sql`
```
INSERT INTO USERS2(username, password) VALUES ('mark','pwd1');
INSERT INTO USERS2(username, password) VALUES ('ken','pwd2');
INSERT INTO USERS2(username, password) VALUES ('tim','pwd3');
```

# delete old file
```
del lab4*.db
```

# 改成file based的h2
```
#spring.datasource.url=jdbc:h2:mem:lab4
spring.datasource.url=jdbc:h2:file:~/lab4
spring.datasource.username=sa
spring.datasource.password=ctbc
spring.datasource.driver-class-name=org.h2.Driver
spring.sql.init.mode=always
```
# BeverageRunner1.java
```java 
package com.ctbcbank.training.boot_lab5.runner;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.ctbcbank.training.boot_lab5.entity.Beverage;
import com.ctbcbank.training.boot_lab5.repository.BeverageRepository;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class BeverageRunner1 implements CommandLineRunner {

	public BeverageRunner1(BeverageRepository repository) {
		super();
		this.repository = repository;
	}

	private BeverageRepository repository;

	@Override
	public void run(String... args) throws Exception {
		log.info("repository is:{}", repository);
		log.info("add some beverage:");
		addBeverage();

	}

	private void addBeverage() {
		Beverage b1 = new Beverage();
		b1.setTitle("black tea");
		b1.setDetail("Tanning Earl Grey Tea");
		repository.save(b1);
		Beverage b2 = new Beverage();
		b2.setTitle("green tea");
		b2.setDetail("Kyoto Uchi mocha");
		repository.save(b2);
	}

}

```

# show sql
## application.properties
```
spring.jpa.show-sql=true

```

# BeverageRunner1.java
```java
package com.ctbcbank.training.boot_lab5.runner;

import java.util.Optional;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.ctbcbank.training.boot_lab5.entity.Beverage;
import com.ctbcbank.training.boot_lab5.repository.BeverageRepository;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class BeverageRunner1 implements CommandLineRunner {

	public BeverageRunner1(BeverageRepository repository) {
		super();
		this.repository = repository;
	}

	private BeverageRepository repository;

	@Override
	public void run(String... args) throws Exception {
		log.info("repository is:{}", repository);
		log.info("add some beverage:");
		addBeverage();
		log.info("get all beverage:");
		getAllBeverage();
		log.info("modify any beverage:");
		modifyBeverage();
		log.info("delete a beverage");
		deleteBeverage();
	}

	private void deleteBeverage() {
		Beverage b = repository.findById(1L).get();
		repository.delete(b);
		log.info("delete success");
		
	}

	private void modifyBeverage() {
		Optional<Beverage> optionalBeverage = repository.findById(1L);
		Beverage b = optionalBeverage.get();
		b.setDetail("India Assam Black Tea");
		repository.save(b);
		repository.findAll().forEach(beverage -> 
		log.info("after modify:{}", beverage.toString()));

	}

	private void getAllBeverage() {
		for (Beverage b : repository.findAll()) {
			log.info("currently we have:{}", b);
		}
		repository.findAll().forEach(b -> log.info("**" + b.toString()));
		;
	}

	private void addBeverage() {
		Beverage b1 = new Beverage();
		b1.setTitle("black tea");
		b1.setDetail("Tanning Earl Grey Tea");
		repository.save(b1);
		Beverage b2 = new Beverage();
		b2.setTitle("green tea");
		b2.setDetail("Kyoto Uchi mocha");
		repository.save(b2);
	}

}

```

# swagger
```xml
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

```

# BeverageServiceImplement.java
```java

package com.ctbcbank.training.boot_lab5.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ctbcbank.training.boot_lab5.entity.Beverage;
import com.ctbcbank.training.boot_lab5.repository.BeverageRepository;
@Service
public class BeverageServiceImplement implements BeverageService {
	@Autowired
	private BeverageRepository repository;
	@Override
	public List<Beverage> retrieveBeverages() {
		Iterable<Beverage> findAll = repository.findAll();
		List<Beverage> allBeverage = new ArrayList<>();
		findAll.forEach(allBeverage::add);
		return allBeverage;
	}

	@Override
	public Beverage getBeverage(Long beverageId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void saveBeverage(Beverage beverage) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void deleteBeverage(Beverage beverage) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void updateBeverage(Beverage beverage) {
		// TODO Auto-generated method stub
		
	}

}


```

# BeverageRestController.java
```java

package com.ctbcbank.training.boot_lab5.rest;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ctbcbank.training.boot_lab5.entity.Beverage;
import com.ctbcbank.training.boot_lab5.service.BeverageService;

@RestController
@RequestMapping("/api/beverages")
public class BeverageRestController {
	@Autowired
	private BeverageService service;
	@GetMapping("/")
	public List<Beverage> getAllBeverages() {
		return service.retrieveBeverages();
	}
	@GetMapping("/{beverageId}")
	public Beverage getBeverage(@PathVariable(name="beverageId")Long id) {
		return service.getBeverage(id);
	}

}


```

# Application.java
```java 


package com.ctbcbank.training.boot_lab5;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import springfox.documentation.swagger2.annotations.EnableSwagger2;





@SpringBootApplication
@EnableSwagger2
@EnableWebMvc
public class BootLab5Application {

	public static void main(String[] args) {
		SpringApplication.run(BootLab5Application.class, args);
	}

}

```

# BeverageServiceImplement
```java
package com.ctbcbank.training.boot_lab5.service;

import java.util.ArrayList;
import java.util.List;

# D
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ctbcbank.training.boot_lab5.entity.Beverage;
import com.ctbcbank.training.boot_lab5.repository.BeverageRepository;

@Service
public class BeverageServiceImplement implements BeverageService {
	@Autowired
	private BeverageRepository repository;

	@Override
	public List<Beverage> retrieveBeverages() {
		Iterable<Beverage> findAll = repository.findAll();
		List<Beverage> allBeverage = new ArrayList<>();
		findAll.forEach(allBeverage::add);
//		for (Beverage b:allBeverage) {
//			allBeverage.add(b);
//		}
		return allBeverage;
	}

	@Override
	public Beverage getBeverage(Long beverageId) {
		Beverage b = repository.findById(beverageId).get();
		return b;
	}

	@Override
	public void saveBeverage(Beverage beverage) {
		repository.save(beverage);

	}

	@Override
	public void deleteBeverage(Beverage beverage) {
		// TODO Auto-generated method stub

	}

	@Override
	public void updateBeverage(Beverage beverage) {
		// TODO Auto-generated method stub

	}

}

```

![](https://i.imgur.com/iiTTOIU.png)

```java
	@PostMapping("/")
	public void saveBeverage(@RequestBody Beverage beverage) {
		log.info("get bean:{}",beverage);
		service.saveBeverage(beverage);
		log.info("bean:{} added successfully",beverage);
	}
```
# Spring 完成的程式碼
# https://drive.google.com/file/d/1vF-gn8LKrm3FW0TStvt8isImTSE23xe7/view?usp=sharing

# Day9

## https://zh-hant.reactjs.org/
## https://vuejs.org/
## https://angular.io/

### 打開cmd
### `npm --version`
### `npm install -g npm`
### `npm list -g`
### `npm install -g @angular/cli`

```
C:\Users\Admin\AppData\Roaming\npm
+-- @angular/cli@15.2.2
`-- npm@9.6.1
```

```
ng new lab1
```

![](https://i.imgur.com/lzBOGTi.png)

![](https://i.imgur.com/Ho5ZPJ6.png)

![](https://i.imgur.com/MZXpEHr.png)

```
ng serve
```
* `ng new lab1_no_strict --strict false`


* `ng serve`
* `https://firebase.google.com/`

* `https://console.firebase.google.com/u/0/`
* https://chrome.google.com/webstore/detail/angular-devtools/ienfalfjdbdpebioblfackkekamfmbnh?hl=zh-TW
* 'Source Code Pro',Consolas, 'Courier New', monospace

* app.component.html
```htmlembedded
<div style="text-align: center">
  <h1>也可以包在div中</h1>
</div>
<h1>元件會加到這裡</h1>

```

* `ng new lab2 --strict false`


![](https://i.imgur.com/uUar6QD.png)

![](https://i.imgur.com/PmH7UvB.png)

* https://getbootstrap.com/docs/4.0/components/buttons/

# Day10


* gyms.component.html
```javascript
<label>尋找</label>
<input type="text" class="form-control" (input)="onSearchGym($event)" />
<h2>要找的條件是:{{ searchCriteria }}</h2>
<button
  class="btn btn-primary"
  [disabled]="!allowReload"
  (click)="onCheckStatus()"
>
  重新載入
</button>
<button class="btn btn-success" (click)="addCounter1()">counter1 +1</button>
<h4>允許重新載入?{{ allowReload }}</h4>
<h4>counter1={{ counter1 }}</h4>
<br />
<button class="btn btn-info" (click)="buttonCallback1($event)">說明event</button>
<input class="form-control" type="text" (input)="inputCallback1($event)"/>
<br />
<app-gym></app-gym>
<app-coach></app-coach>
<app-gym></app-gym>
<app-coach></app-coach>
<app-gym></app-gym>
<app-coach></app-coach>
<app-gym></app-gym>
<app-coach></app-coach>
<app-gym></app-gym>
<app-coach></app-coach>


```
* gyms.component.ts

```javascript


import { Component } from '@angular/core';

@Component({
  selector: 'app-gyms',
  templateUrl: './gyms.component.html',
  styleUrls: ['./gyms.component.css'],
})
export class GymsComponent {
  buttonCallback1(event) {
    console.log('按鈕被點擊了!!,事件是', event.target, event.type);
  }
  inputCallback1(event) {
    console.log('文字方塊被輸入了!!,事件是', event.target, event.data,
    event.target.value);
  }
  counter1 = 0;
  addCounter1() {
    this.counter1 += 1;
  }
  onCheckStatus() {
    console.log('沒什麼特別的');
  }
  allowReload = false;
  constructor() {
    setTimeout(() => {
      this.allowReload = true;
    }, 2000);
  }
  searchCriteria = '';
  onSearchGym(event: Event) {
    this.searchCriteria = (event.target as HTMLInputElement).value;
    console.log('search criteria=', this.searchCriteria);
  }
}

```

![](https://i.imgur.com/WpNSHwJ.png)

![](https://i.imgur.com/127UIl4.png)


# 作業2的啟始專案
* https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.7.9&packaging=jar&jvmVersion=11&groupId=com.ctbcbank.lab&artifactId=backend&name=backend&description=Create%20a%20backend%20to%20let%20forntend%20access&packageName=com.ctbcbank.lab.backend&dependencies=devtools,lombok,web,thymeleaf,h2,data-jpa,validation

* CategoryBeanRestController.java

```java
package com.ctbcbank.lab.backend.controller.rest;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
@RequestMapping("/api/category")
public class CategoryBeanRestController {
	@GetMapping("/all")
	public String getAllCategory() {
		return "傳回所有的種類列表";
	}
	@GetMapping("/{categoryId}")
	public String getCategoryById(@PathVariable String categoryId) {
		return "傳入id, 傳回一個類別:"+categoryId;
	}

}


```
![](https://i.imgur.com/t5rNl2U.png)

* https://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html/listeners.html

![](https://i.imgur.com/w645l7l.png)


* Spring Boot & JAva

### spring boot lab
* https://drive.google.com/file/d/13K_RFKQ8dQzh4433YXEczrspmu1Qk6fu/view?usp=sharing

### angular lab
* https://drive.google.com/file/d/1J3mAWvX4HtLOzgbjU6tQMtltUNaaEq2y/view?usp=sharing


# Day11
* `npm install`, `npm start`
* https://localhost:4200
* 
* gym.component.html
```javascript

<div class="container">
  <h3>{{ info.name }}店</h3>
  <div class="row">
    <div class="col" [ngStyle]="{ backgroundColor: getColor() }">
      {{ getGymStatus() }}
    </div>
    <div class="col" [ngClass]="{ busy: status === 'busy' }">
      有{{ info.count }}間教室
    </div>
  </div>
</div>

```

# array_review1.js
```javascript


acode lab31 = [11, 13, 15, 17, 19]
console.log(a1)
a1.push(21)
console.log(a1)
a1.unshift(9)
console.log(a1)
console.log(a1.pop(), a1.pop())
console.log(a1)
console.log(a1.shift(), a1.shift())
console.log(a1)

```

* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

* code lab3


```html
<div>
  <label for="username">使用者帳號</label>
  <input type="text" id="username" class="form-control" />
  <button type="button" class="btn btn-primary">建議一個</button>
  <br />
  <label for="" email>Email</label>
  <input type="text" id="email" class="form-control" />
  <br />
  <label for="password">密碼</label>
  <input type="password" id="password" class="form-control" />
  <br />
  <label for="secret">忘記密碼</label>
  <select id="secret" class="form-control">
    <option value="city">居住的城市</option>
    <option value="nickname">小時候的別名</option>
    <option value="elementary">小學的名稱</option>
  </select>
  <br />
  <button type="submit" class="btn btn-primary">提交</button>
</div>

```


* 'https://ctbcdemo2023-default-rtdb.firebaseio.com/.json'
* 

```
{
  "rules": {
    ".read": "now < 1681920000000",  // 2023-4-20
    ".write": "now < 1681920000000",  // 2023-4-20
  }
}
```
* angular all
* https://drive.google.com/file/d/1gp7tUF-w9KR5gzLJpQZEay5tI2-dcrTf/view?usp=sharing
* spring boot/java all
* https://drive.google.com/file/d/1wYUCxeLlE3ZcEagweEBNvNPxWu20DfuE/view?usp=sharing


