import java.lang.StringBuilder;
public class AdRequestGenerator {
    public static String generateAdRequestParams(String adUnitType, String adUnitID, int adUnitPrice) {
        StringBuilder params = new StringBuilder();
        params.append("packageName=yourPackageName");
        params.append("&deviceID=yourDeviceID");
        params.append("&googleAID=yourGoogleAID");
        params.append("&networkType=yourNetworkType");
        params.append("&adType=").append(adUnitType);
        params.append("&adID=").append(adUnitID);
        params.append("&priceLevel=").append(adUnitPrice);
        return params.toString();
    }
    public static void main(String[] args) {
        String adUnitType = "video";
        String adUnitID = "ad123";
        int adUnitPrice = 5;
        String requestParams = generateAdRequestParams(adUnitType, adUnitID, adUnitPrice);
        System.out.println(requestParams);
    }
}

Please write a Java method to generate and return a specific format string. This string is based on incoming ad unit information (including ad unit type, ad unit ID, and ad unit price) and some fixed parameters. This string is primarily used for network request parameters. Ensure your solution meets the following requirements:

- The method name should be `generateAdRequestParams`.
- The method takes three parameters: `adUnitType` (ad unit type, of type `String`), `adUnitID` (ad unit ID, of type `String`), and `adUnitPrice` (ad unit price, of type `int`).
- The string format is as follows: `"packageName=yourPackageName&deviceID=yourDeviceID&googleAID=yourGoogleAID&networkType=yourNetworkType&adType=adUnitType&adID=adUnitID&priceLevel=adUnitPrice"`. Where `yourPackageName`, `yourDeviceID`, `yourGoogleAID`, and `yourNetworkType` are fixed string values, while `adUnitType`, `adUnitID`, and `adUnitPrice` are dynamically generated based on the method parameters.
- Use the `&` symbol to connect each parameter.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.lang.StringBuilder;
public class AdRequestGenerator {
    public static String generateAdRequestParams(String adUnitType, String adUnitID, int adUnitPrice) {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class AdRequestGeneratorTest {
    @Test
    public void testGenerateAdRequestParams_ValidInput() {
        String adUnitType = "banner";
        String adUnitID = "123abc";
        int adUnitPrice = 10;
        String expected = "packageName=yourPackageName&deviceID=yourDeviceID&googleAID=yourGoogleAID&networkType=yourNetworkType&adType=banner&adID=123abc&priceLevel=10";
        String actual = AdRequestGenerator.generateAdRequestParams(adUnitType, adUnitID, adUnitPrice);
        assertEquals(expected, actual);
    }
    @Test
    public void testGenerateAdRequestParams_EmptyAdType() {
        String adUnitType = "";
        String adUnitID = "123abc";
        int adUnitPrice = 10;
        String expected = "packageName=yourPackageName&deviceID=yourDeviceID&googleAID=yourGoogleAID&networkType=yourNetworkType&adType=&adID=123abc&priceLevel=10";
        String actual = AdRequestGenerator.generateAdRequestParams(adUnitType, adUnitID, adUnitPrice);
        assertEquals(expected, actual);
    }
    @Test
    public void testGenerateAdRequestParams_EmptyAdID() {
        String adUnitType = "video";
        String adUnitID = "";
        int adUnitPrice = 5;
        String expected = "packageName=yourPackageName&deviceID=yourDeviceID&googleAID=yourGoogleAID&networkType=yourNetworkType&adType=video&adID=&priceLevel=5";
        String actual = AdRequestGenerator.generateAdRequestParams(adUnitType, adUnitID, adUnitPrice);
        assertEquals(expected, actual);
    }
    @Test
    public void testGenerateAdRequestParams_NegativePrice() {
        String adUnitType = "native";
        String adUnitID = "ad123";
        int adUnitPrice = -1;
        String expected = "packageName=yourPackageName&deviceID=yourDeviceID&googleAID=yourGoogleAID&networkType=yourNetworkType&adType=native&adID=ad123&priceLevel=-1";
        String actual = AdRequestGenerator.generateAdRequestParams(adUnitType, adUnitID, adUnitPrice);
        assertEquals(expected, actual);
    }
    @Test
    public void testGenerateAdRequestParams_ZeroPrice() {
        String adUnitType = "interstitial";
        String adUnitID = "ad456";
        int adUnitPrice = 0;
        String expected = "packageName=yourPackageName&deviceID=yourDeviceID&googleAID=yourGoogleAID&networkType=yourNetworkType&adType=interstitial&adID=ad456&priceLevel=0";
        String actual = AdRequestGenerator.generateAdRequestParams(adUnitType, adUnitID, adUnitPrice);
        assertEquals(expected, actual);
    }
}


import java.util.List;
import java.util.ArrayList;
public class StringListProcessor {
    public String getStringAtIndex(List<String> stringList, String indexStr) {
        try {
            int index = Integer.parseInt(indexStr);
            return stringList.get(index);
        } catch (NumberFormatException e) {
            return "错误：索引不是有效的数字。";
        } catch (IndexOutOfBoundsException e) {
            return "错误：索引超出范围。";
        }
    }
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
        list.add("C++");
        StringListProcessor processor = new StringListProcessor();
        System.out.println(processor.getStringAtIndex(list, "1"));
        System.out.println(processor.getStringAtIndex(list, "5"));
        System.out.println(processor.getStringAtIndex(list, "abc"));
    }
}

Please write a Java method that accepts a list of strings and a string index, then returns the corresponding string at the index in the list. If the index is invalid (e.g., out of range or not a number), the method should catch the exception and return a specific error message. Ensure that your method gracefully handles these potential exceptional cases.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.List;
import java.util.ArrayList;
public class StringListProcessor {
    public String getStringAtIndex(List<String> stringList, String indexStr) {
    }
}
```

Question: Write a piece of python code to achieve the following function.
Find the maximum perfect square number that is less than the nth Fibonacci number.
The function's name is max_square_number, and the input is an integer n.

Answer:
```python
def max_square_number(n):
 if n <= 2:
 return 0 # For the first two numbers in the Fibonacci sequence, no complete square numbers can be used.

 fibs = [0, 1] # Store the first two numbers of the Fibonacci sequence
 squares = [] # Store the list of perfect square numbers

 max_square = 0
 i = 2

 while i <= n:
 fibs.append(fibs[i-1] + fibs[i-2]) # Calculate the next Fibonacci number
 i += 1

 fib = fibs[-1]
 perfect_squares = [i**2 for i in range(1, int(math.sqrt(fib)) + 1)]
 max_square = max(filter(lambda x: x < fib, perfect_squares))
 return max_square
```

----------------

import org.junit.Test;
import static org.junit.Assert.*;
import java.util.List;
import java.util.ArrayList;
public class StringListProcessorTest {
    @Test
    public void testGetStringAtIndex_validIndex() {
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
        list.add("C++");
        StringListProcessor processor = new StringListProcessor();
        assertEquals("Python", processor.getStringAtIndex(list, "1"));
    }
    @Test
    public void testGetStringAtIndex_indexOutOfBound() {
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
        list.add("C++");
        StringListProcessor processor = new StringListProcessor();
        assertEquals("错误：索引超出范围。", processor.getStringAtIndex(list, "5"));
    }
    @Test
    public void testGetStringAtIndex_invalidIndex() {
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
        list.add("C++");
        StringListProcessor processor = new StringListProcessor();
        assertEquals("错误：索引不是有效的数字。", processor.getStringAtIndex(list, "abc"));
    }
    @Test
    public void testGetStringAtIndex_zeroIndex() {
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
        list.add("C++");
        StringListProcessor processor = new StringListProcessor();
        assertEquals("Java", processor.getStringAtIndex(list, "0"));
    }
    @Test
    public void testGetStringAtIndex_emptyList() {
        List<String> list = new ArrayList<>();
        StringListProcessor processor = new StringListProcessor();
        assertEquals("错误：索引超出范围。", processor.getStringAtIndex(list, "0"));
    }
}


import java.util.ArrayList;
import java.util.List;
public class LibraryManager {
    private List<Book> books;
    public LibraryManager() {
        this.books = new ArrayList<>();
    }
    public String addBook(String title, String author) {
        for (Book book : books) {
            if (book.getTitle().equals(title) && book.getAuthor().equals(author)) {
                return "书籍已存在。";
            }
        }
        books.add(new Book(title, author));
        return "书籍添加成功。";
    }
    private static class Book {
        private String title;
        private String author;
        public Book(String title, String author) {
            this.title = title;
            this.author = author;
        }
        public String getTitle() {
            return title;
        }
        public String getAuthor() {
            return author;
        }
    }
    public static void main(String[] args) {
        LibraryManager libraryManager = new LibraryManager();
        System.out.println(libraryManager.addBook("Java编程思想", "Bruce Eckel"));
        System.out.println(libraryManager.addBook("Effective Java", "Joshua Bloch"));
        System.out.println(libraryManager.addBook("Java编程思想", "Bruce Eckel"));
    }
}

Please design a simple Java program to manage the book information of a library. Each book contains a title and an author's name. You need to implement a method that accepts the title and the author's name as parameters. If the book already exists in the library, return a message indicating that the book already exists; if not, add the book to the library and return a message indicating that the addition was successful.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.ArrayList;
import java.util.List;
public class LibraryManager {
    private List<Book> books;
    public LibraryManager() {
    }
    public String addBook(String title, String author) {
    }
    private static class Book {
        private String title;
        private String author;
        public Book(String title, String author) {
        }
        public String getTitle() {
        }
        public String getAuthor() {
        }
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class LibraryManagerTest {
    @Test
    void testAddBookOnce() {
        LibraryManager libraryManager = new LibraryManager();
        String result = libraryManager.addBook("Java编程思想", "Bruce Eckel");
        assertEquals("书籍添加成功。", result);
    }
    @Test
    void testAddBookTwiceDifferent() {
        LibraryManager libraryManager = new LibraryManager();
        libraryManager.addBook("Java编程思想", "Bruce Eckel");
        String result = libraryManager.addBook("Effective Java", "Joshua Bloch");
        assertEquals("书籍添加成功。", result);
    }
    @Test
    void testAddDuplicateBook() {
        LibraryManager libraryManager = new LibraryManager();
        libraryManager.addBook("Java编程思想", "Bruce Eckel");
        String result = libraryManager.addBook("Java编程思想", "Bruce Eckel");
        assertEquals("书籍已存在。", result);
    }
    @Test
    void testAddBookWithDifferentAuthor() {
        LibraryManager libraryManager = new LibraryManager();
        libraryManager.addBook("Java编程思想", "Bruce Eckel");
        String result = libraryManager.addBook("Java编程思想", "Another Author");
        assertEquals("书籍添加成功。", result);
    }
    @Test
    void testAddBookWithoutTitle() {
        LibraryManager libraryManager = new LibraryManager();
        String result = libraryManager.addBook("", "Some Author");
        assertEquals("书籍添加成功。", result);
    }
}


public class StringEditor {
    private StringBuilder content;
    public StringEditor() {
        this.content = new StringBuilder();
    }
    public void addText(String text) {
        content.append(text);
    }
    public void replaceChar(int index, char newChar) {
        if (index >= 0 && index < content.length()) {
            content.setCharAt(index, newChar);
        }
    }
    public void deleteChar(int index) {
        if (index >= 0 && index < content.length()) {
            content.deleteCharAt(index);
        }
    }
    @Override
    public String toString() {
        return content.toString();
    }
    public static void main(String[] args) {
        StringEditor editor = new StringEditor();
        editor.addText("hello");
        System.out.println(editor);
        editor.replaceChar(1, 'a');
        System.out.println(editor);
        editor.deleteChar(4);
        System.out.println(editor);
    }
}

Please write a Java program to implement a simple text editor that can perform text addition, replacement, and deletion operations. The specific requirements are as follows:

1. Use the `StringEditor` class to implement this text editor.
2. In the `StringEditor` class, use `StringBuilder` to store and manipulate the text string.
3. Implement the `addText` method, which accepts a string parameter and appends it to the end of the current text.
4. Implement the `replaceChar` method, which accepts two parameters: the position of the character to be replaced (starting from 0) and the new character, then replaces the character at the specified position.
5. Implement the `deleteChar` method, which accepts one parameter: the position of the character to be deleted (starting from 0), then deletes the character at that position.

Please note that all operations should be as efficient as possible.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
public class StringEditor {
    private StringBuilder content;
    public StringEditor() {
    }
    public void addText(String text) {
    }
    public void replaceChar(int index, char newChar) {
    }
    public void deleteChar(int index) {
    }
    @Override
    public String toString() {
    }
}
```

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class StringEditorTest {
    @Test
    void testAddText() {
        StringEditor editor = new StringEditor();
        editor.addText("hello");
        assertEquals("hello", editor.toString());
    }
    @Test
    void testReplaceChar() {
        StringEditor editor = new StringEditor();
        editor.addText("hello");
        editor.replaceChar(1, 'a');
        assertEquals("hallo", editor.toString());
    }
    @Test
    void testReplaceCharOutOfBounds() {
        StringEditor editor = new StringEditor();
        editor.addText("hello");
        editor.replaceChar(5, 'a');
        assertEquals("hello", editor.toString());
    }
    @Test
    void testDeleteChar() {
        StringEditor editor = new StringEditor();
        editor.addText("hello");
        editor.deleteChar(4);
        assertEquals("hell", editor.toString());
    }
    @Test
    void testDeleteCharOutOfBounds() {
        StringEditor editor = new StringEditor();
        editor.addText("hello");
        editor.deleteChar(5);
        assertEquals("hello", editor.toString());
    }
}


import java.util.Objects;
public class CsvUtil {
    public static String prepareForCsv(String input) {
        if (input == null) {
            return "";
        }
        String escapedInput = input.replace("\"", "\"\"");
        return "\"" + escapedInput + "\"";
    }
    public static void main(String[] args) {
        System.out.println(checkPrepareForCsv(null, ""));
        System.out.println(checkPrepareForCsv("", "\"\""));
        System.out.println(checkPrepareForCsv("Hello", "\"Hello\""));
        System.out.println(checkPrepareForCsv("Hello\"World", "\"Hello\"\"World\""));
    }
    private static boolean checkPrepareForCsv(String input, String expected) {
        return Objects.equals(prepareForCsv(input), expected);
    }
}

Please write a Java method to process a string so that it is suitable for a CSV file format. Specifically, if the string contains special characters (such as double quotes), these characters need to be escaped. Additionally, the string should be enclosed in double quotes regardless of whether it contains special characters. Please follow these rules:

1. If the input string is null, return an empty string.
2. If the input string is empty, return two double quotes ("").
3. If the input string contains double quotes ("), replace each double quote with two double quotes ("").
4. After applying the above rules, enclose the entire string with a pair of double quotes.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Objects;
public class CsvUtil {
    public static String prepareForCsv(String input) {
    }
}
```

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class CsvUtilTest {
    @Test
    public void testPrepareForCsv_NullInput() {
        String result = CsvUtil.prepareForCsv(null);
        assertEquals("", result);
    }
    @Test
    public void testPrepareForCsv_EmptyString() {
        String result = CsvUtil.prepareForCsv("");
        assertEquals("\"\"", result);
    }
    @Test
    public void testPrepareForCsv_SimpleString() {
        String result = CsvUtil.prepareForCsv("Hello");
        assertEquals("\"Hello\"", result);
    }
    @Test
    public void testPrepareForCsv_StringWithQuote() {
        String result = CsvUtil.prepareForCsv("Hello\"World");
        assertEquals("\"Hello\"\"World\"", result);
    }
    @Test
    public void testPrepareForCsv_OnlyQuotes() {
        String result = CsvUtil.prepareForCsv("\"\"");
        assertEquals("\"\"\"\"\"\"", result);
    }
}


import java.util.Scanner;
public class SimpleCalculator {
    public static int calculate(int num1, int num2, char operator) {
        switch (operator) {
            case '+':
                return num1 + num2;
            case '-':
                return num1 - num2;
            case '*':
                return num1 * num2;
            case '/':
                if (num2 == 0) {
                    throw new IllegalArgumentException("除数不能为0");
                }
                return num1 / num2;
            default:
                throw new IllegalArgumentException("无效的运算符: " + operator);
        }
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入第一个整数:");
        int num1 = scanner.nextInt();
        System.out.println("请输入第二个整数:");
        int num2 = scanner.nextInt();
        System.out.println("请输入运算符('+', '-', '*', '/'):");
        char operator = scanner.next().charAt(0);
        try {
            int result = calculate(num1, num2, operator);
            System.out.println("运算结果是: " + result);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

Please write a Java program to implement a simple calculator class `SimpleCalculator`. This calculator should include a method `calculate` that takes three parameters: two integers `num1` and `num2`, and a character `operator`. Based on the `operator` specified ('+', '-', '*', '/'), it performs the corresponding arithmetic operation on `num1` and `num2`, and returns the result. If `operator` is an invalid operator, the method should throw an `IllegalArgumentException`.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Scanner;
public class SimpleCalculator {
    public static int calculate(int num1, int num2, char operator) {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class SimpleCalculatorTest {
    @Test
    public void testAddition() {
        int result = SimpleCalculator.calculate(3, 5, '+');
        assertEquals(8, result);
    }
    @Test
    public void testSubtraction() {
        int result = SimpleCalculator.calculate(10, 4, '-');
        assertEquals(6, result);
    }
    @Test
    public void testMultiplication() {
        int result = SimpleCalculator.calculate(6, 7, '*');
        assertEquals(42, result);
    }
    @Test
    public void testDivision() {
        int result = SimpleCalculator.calculate(20, 4, '/');
        assertEquals(5, result);
    }
    @Test
    public void testDivisionByZero() {
        Exception exception = assertThrows(IllegalArgumentException.class, () -> {
            SimpleCalculator.calculate(10, 0, '/');
        });
        assertEquals("除数不能为0", exception.getMessage());
    }
    @Test
    public void testInvalidOperator() {
        Exception exception = assertThrows(IllegalArgumentException.class, () -> {
            SimpleCalculator.calculate(10, 5, '%');
        });
        assertEquals("无效的运算符: %", exception.getMessage());
    }
}


import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class FileReaderUtil {
    public static String readUntilChar(String filePath, char[] stopChars) throws IOException {
        StringBuilder content = new StringBuilder();
        FileReader reader = null;
        try {
            reader = new FileReader(filePath);
            int c;
            while ((c = reader.read()) != -1) {
                if (Arrays.binarySearch(stopChars, (char) c) >= 0) {
                    break;
                }
                content.append((char) c);
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        return content.toString();
    }
    public static void checkFunction() {
        String testFilePath = "testFile.txt";
        char[] stopChars = {'a', 'e', 'i', 'o', 'u'};
        try {
            String result = readUntilChar(testFilePath, stopChars);
            System.out.println("读取的内容（直到遇到指定字符）: " + result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        checkFunction();
    }
}

Please write a Java method that reads characters from a text file until one of the specified characters is encountered. The method should return a string containing all the characters from the start of the file up to (but not including) the first occurrence of any of the specified characters. If none of the specified characters are found in the file, the method should return the entire content of the file.

Please follow these guidelines:
- The method should accept two parameters: one is a string representing the file path, and the other is a character array containing the specified stopping characters.
- Use exception handling to deal with potential file reading errors.
- Ensure the file is closed after reading is completed.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class FileReaderUtil {
    public static String readUntilChar(String filePath, char[] stopChars) throws IOException {
    }
    public static void checkFunction() {
    }
}
```

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.io.*;
public class FileReaderUtilTest {
    @Test
    public void testReadUntilCharStopCharFound() throws IOException {
        String content = "hello world";
        File tempFile = File.createTempFile("testFile", ".txt");
        tempFile.deleteOnExit();
        try (FileWriter writer = new FileWriter(tempFile)) {
            writer.write(content);
        }
        char[] stopChars = {'a', 'e', 'i', 'o', 'u'};
        String result = FileReaderUtil.readUntilChar(tempFile.getAbsolutePath(), stopChars);
        assertEquals("h", result);
    }
    @Test
    public void testReadUntilCharNoStopChar() throws IOException {
        String content = "bcdfg";
        File tempFile = File.createTempFile("testFile", ".txt");
        tempFile.deleteOnExit();
        try (FileWriter writer = new FileWriter(tempFile)) {
            writer.write(content);
        }
        char[] stopChars = {'a', 'e', 'i', 'o', 'u'};
        String result = FileReaderUtil.readUntilChar(tempFile.getAbsolutePath(), stopChars);
        assertEquals(content, result);
    }
    @Test
    public void testReadUntilCharEmptyFile() throws IOException {
        File tempFile = File.createTempFile("testFile", ".txt");
        tempFile.deleteOnExit();
        char[] stopChars = {'a', 'e', 'i', 'o', 'u'};
        String result = FileReaderUtil.readUntilChar(tempFile.getAbsolutePath(), stopChars);
        assertEquals("", result);
    }
    @Test
    public void testReadUntilCharImmediateStopChar() throws IOException {
        String content = "ahello world";
        File tempFile = File.createTempFile("testFile", ".txt");
        tempFile.deleteOnExit();
        try (FileWriter writer = new FileWriter(tempFile)) {
            writer.write(content);
        }
        char[] stopChars = {'a', 'e', 'i', 'o', 'u'};
        String result = FileReaderUtil.readUntilChar(tempFile.getAbsolutePath(), stopChars);
        assertEquals("", result);
    }
    @Test
    public void testReadUntilCharIOException() {
        String filePath = "nonexistentfile.txt";
        char[] stopChars = {'a', 'e', 'i', 'o', 'u'};
        assertThrows(IOException.class, () -> {
            FileReaderUtil.readUntilChar(filePath, stopChars);
        });
    }
}


import java.util.ArrayList;
import java.util.List;
public class BookSearchManager {
    private List<String> allBooks;
    private List<String> filteredBooks;
    public BookSearchManager() {
        allBooks = new ArrayList<>();
        allBooks.add("Java编程思想");
        allBooks.add("深入理解Java虚拟机");
        allBooks.add("Effective Java");
        allBooks.add("Python编程从入门到实践");
        allBooks.add("算法导论");
    }
    public List<String> searchBooks(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return allBooks;
        } else {
            filteredBooks = new ArrayList<>();
            for (String book : allBooks) {
                if (book.toLowerCase().contains(keyword.toLowerCase())) {
                    filteredBooks.add(book);
                }
            }
            return filteredBooks;
        }
    }
    public static void main(String[] args) {
        BookSearchManager manager = new BookSearchManager();
        System.out.println("搜索 'Java': " + manager.searchBooks("Java"));
        System.out.println("搜索空字符串: " + manager.searchBooks(""));
    }
}

Please design a Java program to manage a book search function for a library. When the user enters a search keyword, the program should return all book titles that contain that keyword. If the user does not enter anything (i.e., the input is an empty string), it should return all books. Ensure that your solution is self-contained and includes all necessary import statements.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.ArrayList;
import java.util.List;
public class BookSearchManager {
    private List<String> allBooks;
    private List<String> filteredBooks;
    public BookSearchManager() {}
    public List<String> searchBooks(String keyword) {}
}
```

import org.junit.Assert;
import org.junit.Test;
import java.util.List;
public class BookSearchManagerTest {
    @Test
    public void testSearchBooksWithKeyword() {
        BookSearchManager manager = new BookSearchManager();
        List<String> result = manager.searchBooks("Java");
        Assert.assertEquals(3, result.size());
        Assert.assertTrue(result.contains("Java编程思想"));
        Assert.assertTrue(result.contains("深入理解Java虚拟机"));
        Assert.assertTrue(result.contains("Effective Java"));
    }
    @Test
    public void testSearchBooksWithEmptyString() {
        BookSearchManager manager = new BookSearchManager();
        List<String> result = manager.searchBooks("");
        Assert.assertEquals(5, result.size());
    }
    @Test
    public void testSearchBooksWithNull() {
        BookSearchManager manager = new BookSearchManager();
        List<String> result = manager.searchBooks(null);
        Assert.assertEquals(5, result.size());
    }
    @Test
    public void testSearchBooksWithNonExistingKeyword() {
        BookSearchManager manager = new BookSearchManager();
        List<String> result = manager.searchBooks("C++");
        Assert.assertTrue(result.isEmpty());
    }
    @Test
    public void testSearchBooksCaseInsensitiveKeyword() {
        BookSearchManager manager = new BookSearchManager();
        List<String> result = manager.searchBooks("java");
        Assert.assertEquals(3, result.size());
        Assert.assertTrue(result.contains("Java编程思想"));
        Assert.assertTrue(result.contains("深入理解Java虚拟机"));
        Assert.assertTrue(result.contains("Effective Java"));
    }
}


import java.util.Scanner;
public class TextEditor {
    private String fontSize = "12";
    public void changeFontSize() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("------------------------");
        System.out.print("请输入新的字体大小: ");
        String newFontSize = scanner.nextLine();
        if (newFontSize.equals(fontSize)) {
            System.out.println("------------------------");
            System.out.println("字体大小未改变。");
            System.out.println("========================");
        } else {
            fontSize = newFontSize;
            System.out.println("------------------------");
            System.out.println("字体大小已更新为: " + fontSize);
            System.out.println("========================");
        }
    }
    public static void main(String[] args) {
        TextEditor editor = new TextEditor();
        editor.changeFontSize();
    }
}

Please implement a simple text editor feature that allows users to set the font size. Users can change the font size of the text by entering the desired size. If the user's input matches the current font size, inform the user that no change has occurred. Otherwise, update the font size and notify the user that the font size has been changed. Ensure the program handles user inputs and provides clear prompt information before and after changing the font size.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Scanner;
public class TextEditor {
    private String fontSize = "12";
    public void changeFontSize() {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
public class TextEditorTest {
    @Test
    public void testChangeFontSizeNoChange() {
        String simulatedInput = "12\n";
        InputStream originalIn = System.in;
        System.setIn(new ByteArrayInputStream(simulatedInput.getBytes()));
        TextEditor editor = new TextEditor();
        editor.changeFontSize();
        System.setIn(originalIn);
    }
    @Test
    public void testChangeFontSizeChange() {
        String simulatedInput = "14\n";
        InputStream originalIn = System.in;
        System.setIn(new ByteArrayInputStream(simulatedInput.getBytes()));
        TextEditor editor = new TextEditor();
        editor.changeFontSize();
        System.setIn(originalIn);
    }
    @Test
    public void testChangeFontSizeInvalidInput() {
        String simulatedInput = "abc\n";
        InputStream originalIn = System.in;
        System.setIn(new ByteArrayInputStream(simulatedInput.getBytes()));
        TextEditor editor = new TextEditor();
        editor.changeFontSize();
        System.setIn(originalIn);
    }
    @Test
    public void testChangeFontSizeEmptyInput() {
        String simulatedInput = "\n";
        InputStream originalIn = System.in;
        System.setIn(new ByteArrayInputStream(simulatedInput.getBytes()));
        TextEditor editor = new TextEditor();
        editor.changeFontSize();
        System.setIn(originalIn);
    }
    @Test
    public void testChangeFontSizeLargeInput() {
        String simulatedInput = "1000\n";
        InputStream originalIn = System.in;
        System.setIn(new ByteArrayInputStream(simulatedInput.getBytes()));
        TextEditor editor = new TextEditor();
        editor.changeFontSize();
        System.setIn(originalIn);
    }
}


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
class Book {
    private Date addedDate;
    public Book(Date addedDate) {
        this.addedDate = addedDate;
    }
    public Date getAddedDate() {
        return addedDate;
    }
}
public class Library {
    private List<Book> books = new ArrayList<>();
    public void addBook(Book book) {
        books.add(book);
    }
    public int countBooksAddedBetween(Date start, Date end) {
        int count = 0;
        for (Book book : books) {
            Date addedDate = book.getAddedDate();
            if (!addedDate.before(start) && !addedDate.after(end)) {
                count++;
            }
        }
        return count;
    }
    public static void main(String[] args) {
        Library library = new Library();
        library.addBook(new Book(new Date(122, 4, 15)));
        library.addBook(new Book(new Date(122, 5, 10)));
        library.addBook(new Book(new Date(122, 6, 20)));
        Date start = new Date(122, 4, 1);
        Date end = new Date(122, 5, 30);
        int count = library.countBooksAddedBetween(start, end);
        System.out.println("新增图书数量: " + count);
    }
}

Please determine the number of new books added to an online library in a specific time period. Each book in the library has an entry date, and you need to determine whether the book was added during the given period based on this date. Ensure that the solution can accept two dates as input (start date and end date), and return the number of new books added during that period. Note that the start date and end date are inclusive, meaning if the book's entry date is equal to the start date or end date, it should also be counted.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
class Book {
    private Date addedDate;
    public Book(Date addedDate) {
    }
    public Date getAddedDate() {
        return null;
    }
}
public class Library {
    private List<Book> books = new ArrayList<>();
    public void addBook(Book book) {
    }
    public int countBooksAddedBetween(Date start, Date end) {
        return 0;
    }
}
```

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.util.Date;
public class LibraryTest {
    @Test
    public void testAddBook() {
        Library library = new Library();
        library.addBook(new Book(new Date()));
        assertEquals(1, library.countBooksAddedBetween(new Date(Long.MIN_VALUE), new Date()));
    }
    @Test
    public void testCountBooksAddedBetween() {
        Library library = new Library();
        library.addBook(new Book(new Date(122, 4, 15)));
        library.addBook(new Book(new Date(122, 5, 10)));
        library.addBook(new Book(new Date(122, 6, 20)));
        Date start = new Date(122, 4, 1);
        Date end = new Date(122, 5, 30);
        int count = library.countBooksAddedBetween(start, end);
        assertEquals(2, count);
    }
    @Test
    public void testCountBooksAddedBetweenNoBooks() {
        Library library = new Library();
        Date start = new Date(122, 4, 1);
        Date end = new Date(122, 5, 30);
        int count = library.countBooksAddedBetween(start, end);
        assertEquals(0, count);
    }
    @Test
    public void testCountBooksAddedBetweenAllBooks() {
        Library library = new Library();
        library.addBook(new Book(new Date(122, 4, 15)));
        library.addBook(new Book(new Date(122, 5, 10)));
        library.addBook(new Book(new Date(122, 6, 20)));
        Date start = new Date(122, 4, 1);
        Date end = new Date(122, 6, 30);
        int count = library.countBooksAddedBetween(start, end);
        assertEquals(3, count);
    }
    @Test
    public void testCountBooksAddedBetweenEdgeCases() {
        Library library = new Library();
        library.addBook(new Book(new Date(122, 4, 15)));
        library.addBook(new Book(new Date(122, 5, 10)));
        library.addBook(new Book(new Date(122, 6, 20)));
        Date start = new Date(122, 5, 10);
        Date end = new Date(122, 6, 20);
        int count = library.countBooksAddedBetween(start, end);
        assertEquals(2, count);
    }
}


import java.util.Arrays;
import java.util.List;
public class FileUtil {
    public static boolean isImageType(String fileName) {
        List<String> supportedTypes = Arrays.asList(".jpg", ".png", ".gif", ".bmp");
        String extension = "";
        int i = fileName.lastIndexOf('.');
        if (i > 0) {
            extension = fileName.substring(i).toLowerCase();
        }
        return supportedTypes.contains(extension);
    }
    public static void check() {
        System.out.println(isImageType("photo.jpg") == true ? "正确" : "错误");
        System.out.println(isImageType("document.pdf") == false ? "正确" : "错误");
        System.out.println(isImageType("image.png") == true ? "正确" : "错误");
        System.out.println(isImageType("animation.gif") == true ? "正确" : "错误");
        System.out.println(isImageType("archive.rar") == false ? "正确" : "错误");
    }
    public static void main(String[] args) {
        check();
    }
}

Please write a Java method to check if a given file extension represents an image file. The supported image file types include `.jpg`, `.png`, `.gif`, and `.bmp`. If the file extension matches one of these types, the method should return `true`, otherwise it should return `false`.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Arrays;
import java.util.List;
public class FileUtil {
    public static boolean isImageType(String fileName) {
    }
    public static void check() {
    }
}
```

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class FileUtilTest {
    @Test
    public void testIsImageType_WithJpgExtension_ShouldReturnTrue() {
        assertTrue(FileUtil.isImageType("photo.jpg"));
    }
    @Test
    public void testIsImageType_WithPngExtension_ShouldReturnTrue() {
        assertTrue(FileUtil.isImageType("image.png"));
    }
    @Test
    public void testIsImageType_WithGifExtension_ShouldReturnTrue() {
        assertTrue(FileUtil.isImageType("animation.gif"));
    }
    @Test
    public void testIsImageType_WithPdfExtension_ShouldReturnFalse() {
        assertFalse(FileUtil.isImageType("document.pdf"));
    }
    @Test
    public void testIsImageType_WithRarExtension_ShouldReturnFalse() {
        assertFalse(FileUtil.isImageType("archive.rar"));
    }
}


import java.util.Calendar;
import java.util.TimeZone;
public class DateManager {
    public static long[] resetTimeMarkers() {
        Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        long todayStart = calendar.getTimeInMillis();
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        long yesterdayStart = calendar.getTimeInMillis();
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        long yearStart = calendar.getTimeInMillis();
        return new long[]{todayStart, yesterdayStart, yearStart};
    }
    public static void checkTimeMarkers(long[] timeMarkers) {
        Calendar calendar = Calendar.getInstance();
        for (long timeMarker : timeMarkers) {
            calendar.setTimeInMillis(timeMarker);
            System.out.println(calendar.getTime());
        }
    }
    public static void main(String[] args) {
        long[] timeMarkers = resetTimeMarkers();
        checkTimeMarkers(timeMarkers);
    }
}

Please write a Java program which includes a class named `DateManager` that contains a static method `resetTimeMarkers`. This method is used to calculate and return an array of type `long` containing three time points: the start of today, the start of yesterday, and the start of this year. These three time points are represented as timestamps in milliseconds, corresponding to 0:00 of the current day, 0:00 of the previous day, and 0:00 on January 1st of the current year, respectively. Ensure that the returned timestamps are accurate and take timezone effects into account.

Please implement the code according to the following requirements:

1. Use the `java.util.Calendar` class to get and set the time.
2. In the array returned by the method, the first element should be the timestamp for the start of today, the second element should be the timestamp for the start of yesterday, and the third element should be the timestamp for the start of this year.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Calendar;
import java.util.TimeZone;
public class DateManager {
    public static long[] resetTimeMarkers() {
    }
    public static void checkTimeMarkers(long[] timeMarkers) {
    }
}
```

import org.junit.jupiter.api.Test;
import java.util.Calendar;
import java.util.TimeZone;
import static org.junit.jupiter.api.Assertions.*;
public class DateManagerTest {
    @Test
    public void testResetTimeMarkersTodayStart() {
        long[] timeMarkers = DateManager.resetTimeMarkers();
        Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        assertEquals(calendar.getTimeInMillis(), timeMarkers[0]);
    }
    @Test
    public void testResetTimeMarkersYesterdayStart() {
        long[] timeMarkers = DateManager.resetTimeMarkers();
        Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        assertEquals(calendar.getTimeInMillis(), timeMarkers[1]);
    }
    @Test
    public void testResetTimeMarkersYearStart() {
        long[] timeMarkers = DateManager.resetTimeMarkers();
        Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        assertEquals(calendar.getTimeInMillis(), timeMarkers[2]);
    }
    @Test
    public void testCheckTimeMarkers() {
        long[] timeMarkers = DateManager.resetTimeMarkers();
        Calendar calendar = Calendar.getInstance();
        for (long timeMarker : timeMarkers) {
            calendar.setTimeInMillis(timeMarker);
            assertNotNull(calendar.getTime());
        }
    }
}


import java.io.UnsupportedEncodingException;
public class StringEncoder {
    public String convertEncoding(String originalString, String desiredEncoding) throws UnsupportedEncodingException {
        byte[] bytes = originalString.getBytes(desiredEncoding);
        return new String(bytes, desiredEncoding);
    }
    public static void main(String[] args) {
        StringEncoder encoder = new StringEncoder();
        try {
            String originalString = "这是一个测试字符串";
            String desiredEncoding = "ISO-8859-1";
            String convertedString = encoder.convertEncoding(originalString, desiredEncoding);
            System.out.println("转换后的字符串: " + convertedString);
        } catch (UnsupportedEncodingException e) {
            System.err.println("不支持的编码格式: " + e.getMessage());
        }
    }
}

Please write a Java program to handle specific encoding conversions in a string. Specifically, you need to implement a class named `StringEncoder` which contains a method named `convertEncoding`. This method accepts two string parameters: the first parameter `originalString` represents the original string, and the second parameter `desiredEncoding` represents the desired encoding format (such as "UTF-8", "ISO-8859-1", etc.). If the conversion is successful, the method should return the converted string; if the conversion fails, it should throw an `UnsupportedEncodingException`.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.io.UnsupportedEncodingException;
public class StringEncoder {
    public String convertEncoding(String originalString, String desiredEncoding) throws UnsupportedEncodingException {
    }
}
```

import java.io.UnsupportedEncodingException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class StringEncoderTest {
    @Test
    public void testConvertEncoding_validEncoding() throws UnsupportedEncodingException {
        StringEncoder encoder = new StringEncoder();
        String originalString = "这是一个测试字符串";
        String desiredEncoding = "UTF-8";
        String encodedString = encoder.convertEncoding(originalString, desiredEncoding);
        assertNotNull(encodedString);
    }
    @Test
    public void testConvertEncoding_invalidEncoding() {
        StringEncoder encoder = new StringEncoder();
        String originalString = "这是一个测试字符串";
        String desiredEncoding = "INVALID_ENCODING";
        assertThrows(UnsupportedEncodingException.class, () -> {
            encoder.convertEncoding(originalString, desiredEncoding);
        });
    }
    @Test
    public void testConvertEncoding_emptyString() throws UnsupportedEncodingException {
        StringEncoder encoder = new StringEncoder();
        String originalString = "";
        String desiredEncoding = "UTF-8";
        String encodedString = encoder.convertEncoding(originalString, desiredEncoding);
        assertEquals("", encodedString);
    }
    @Test
    public void testConvertEncoding_differentEncodings() throws UnsupportedEncodingException {
        StringEncoder encoder = new StringEncoder();
        String originalString = "这是一个测试字符串";
        String utf8Encoded = encoder.convertEncoding(originalString, "UTF-8");
        String isoEncoded = encoder.convertEncoding(utf8Encoded, "ISO-8859-1");
        assertNotNull(isoEncoded);
    }
    @Test
    public void testConvertEncoding_nullString() {
        StringEncoder encoder = new StringEncoder();
        String desiredEncoding = "UTF-8";
        Exception exception = assertThrows(NullPointerException.class, () -> {
            encoder.convertEncoding(null, desiredEncoding);
        });
    }
}


import java.lang.UnsupportedOperationException;
public class ImageProcessor {
    public void initializePorts() {
        throw new UnsupportedOperationException("该方法尚未实现。");
    }
    public static void checkFunction() {
        ImageProcessor processor = new ImageProcessor();
        try {
            processor.initializePorts();
        } catch (UnsupportedOperationException e) {
            System.out.println("方法抛出了预期的异常：" + e.getMessage());
        }
    }
    public static void main(String[] args) {
        checkFunction();
    }
}

Please write a Java method that sets the input and output ports in an image processing filter. The method should be in a class named `ImageProcessor`, and this class should have a public method named `initializePorts`. The method does not need to accept any parameters, and it should throw an `UnsupportedOperationException` to indicate that the functionality is not yet implemented. Be sure to include all necessary import statements.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.lang.UnsupportedOperationException;
public class ImageProcessor {
    public void initializePorts() {
    }
}
```

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.lang.UnsupportedOperationException;
public class ImageProcessorTest {
    @Test
    public void testInitializePortsThrowsException() {
        ImageProcessor processor = new ImageProcessor();
        Assertions.assertThrows(UnsupportedOperationException.class, processor::initializePorts);
    }
    @Test
    public void testInitializePortsThrowsExceptionWithMessage() {
        ImageProcessor processor = new ImageProcessor();
        UnsupportedOperationException exception = Assertions.assertThrows(UnsupportedOperationException.class, processor::initializePorts);
        Assertions.assertEquals("该方法尚未实现。", exception.getMessage());
    }
    @Test
    public void testCheckFunctionCatchesException() {
        try {
            ImageProcessor.checkFunction();
        } catch (Exception e) {
            Assertions.fail("checkFunction方法不应抛出任何异常，但抛出了: " + e);
        }
    }
    @Test
    public void testNewInstance() {
        ImageProcessor processor = new ImageProcessor();
        Assertions.assertNotNull(processor, "创建的ImageProcessor实例不应为null");
    }
}


import java.util.Locale;
interface Metric {}
interface Counting extends Metric {
    long getCount();
}
interface Gauge<T> extends Metric {
    T getValue();
}
interface Sampling extends Metric {
    double getSampleRate();
}
class Counter implements Counting {
    private long count;
    public Counter(long count) { this.count = count; }
    public long getCount() { return count; }
}
class GaugeDouble implements Gauge<Double> {
    private double value;
    public GaugeDouble(double value) { this.value = value; }
    public Double getValue() { return value; }
}
class Sample implements Sampling {
    private double sampleRate;
    public Sample(double sampleRate) { this.sampleRate = sampleRate; }
    public double getSampleRate() { return sampleRate; }
}
public class PerformanceSummary {
    public static void displayMetricInfo(StringBuilder sb, Metric[] metrics) {
        for (Metric metric : metrics) {
            if (metric instanceof Counting) {
                sb.append(String.format(Locale.US, "Count: %d\n", ((Counting) metric).getCount()));
            }
            if (metric instanceof Gauge) {
                sb.append(String.format(Locale.US, "Value: %.2f\n", ((Gauge<?>) metric).getValue()));
            }
            if (metric instanceof Sampling) {
                sb.append(String.format(Locale.US, "Sample Rate: %.2f%%\n", ((Sampling) metric).getSampleRate() * 100));
            }
        }
    }
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        Metric[] metrics = new Metric[] {
            new Counter(150),
            new GaugeDouble(99.99),
            new Sample(0.85)
        };
        displayMetricInfo(sb, metrics);
        System.out.println(sb.toString());
    }
}

Please define a class named `PerformanceSummary`, which contains a method called `displayMetricInfo`. This method accepts a `StringBuilder` object and an array of objects implementing the `Metric` interface. You need to add corresponding information to the `StringBuilder` based on different metric types (count, measurement, sample rate). Make sure your implementation can handle different types of metrics, and is neatly formatted and easy to read.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Locale;
interface Metric {}
interface Counting extends Metric {
    long getCount();
}
interface Gauge<T> extends Metric {
    T getValue();
}
interface Sampling extends Metric {
    double getSampleRate();
}
class Counter implements Counting {
    private long count;
    public Counter(long count) {}
    public long getCount() {}
}
class GaugeDouble implements Gauge<Double> {
    private double value;
    public GaugeDouble(double value) {}
    public Double getValue() {}
}
class Sample implements Sampling {
    private double sampleRate;
    public Sample(double sampleRate) {}
    public double getSampleRate() {}
}
public class PerformanceSummary {
    public static void displayMetricInfo(StringBuilder sb, Metric[] metrics) {}
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class PerformanceSummaryTest {
    @Test
    public void testDisplayMetricInfo_withCounter() {
        StringBuilder sb = new StringBuilder();
        Metric[] metrics = new Metric[] { new Counter(150) };
        PerformanceSummary.displayMetricInfo(sb, metrics);
        assertEquals("Count: 150\n", sb.toString());
    }
    @Test
    public void testDisplayMetricInfo_withGaugeDouble() {
        StringBuilder sb = new StringBuilder();
        Metric[] metrics = new Metric[] { new GaugeDouble(99.99) };
        PerformanceSummary.displayMetricInfo(sb, metrics);
        assertEquals("Value: 99.99\n", sb.toString());
    }
    @Test
    public void testDisplayMetricInfo_withSample() {
        StringBuilder sb = new StringBuilder();
        Metric[] metrics = new Metric[] { new Sample(0.85) };
        PerformanceSummary.displayMetricInfo(sb, metrics);
        assertEquals("Sample Rate: 85.00%\n", sb.toString());
    }
    @Test
    public void testDisplayMetricInfo_withMixedMetrics() {
        StringBuilder sb = new StringBuilder();
        Metric[] metrics = new Metric[] {
            new Counter(150),
            new GaugeDouble(99.99),
            new Sample(0.85)
        };
        PerformanceSummary.displayMetricInfo(sb, metrics);
        assertEquals("Count: 150\nValue: 99.99\nSample Rate: 85.00%\n", sb.toString());
    }
    @Test
    public void testDisplayMetricInfo_withEmptyMetrics() {
        StringBuilder sb = new StringBuilder();
        Metric[] metrics = new Metric[] {};
        PerformanceSummary.displayMetricInfo(sb, metrics);
        assertEquals("", sb.toString());
    }
}


import java.util.regex.Pattern;
public class PasswordStrengthValidator {
    public static boolean validatePasswordStrength(String password) {
        if (password.length() < 8) {
            return false;
        }
        if (!Pattern.compile("[a-z]").matcher(password).find()) {
            return false;
        }
        if (!Pattern.compile("[A-Z]").matcher(password).find()) {
            return false;
        }
        if (!Pattern.compile("[0-9]").matcher(password).find()) {
            return false;
        }
        if (!Pattern.compile("[^a-zA-Z0-9]").matcher(password).find()) {
            return false;
        }
        return true;
    }
    public static void main(String[] args) {
        checkPasswordStrength("WeakPass", false);
        checkPasswordStrength("StrongPass1!", true);
        checkPasswordStrength("NoSpecialChar1", false);
        checkPasswordStrength("Short1!", false);
        checkPasswordStrength("ValidPassword1@", true);
    }
    private static void checkPasswordStrength(String password, boolean expected) {
        boolean isValid = validatePasswordStrength(password);
        assert isValid == expected : "Password validation for \"" + password + "\" failed. Expected: " + expected + ", but got: " + isValid;
        System.out.println("Password \"" + password + "\" is " + (isValid ? "strong" : "weak") + ".");
    }
}

Please write a Java program to verify the strength of a user password. The password must meet the following criteria to be considered valid:
- Must contain at least 8 characters.
- Must contain at least one lowercase letter.
- Must contain at least one uppercase letter.
- Must contain at least one digit.
- Must contain at least one special character (non-alphanumeric).
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.regex.Pattern;
public class PasswordStrengthValidator {
    public static boolean validatePasswordStrength(String password) {
    }
}
```

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class PasswordStrengthValidatorTest {
    @Test
    public void testShortPassword() {
        assertEquals(false, PasswordStrengthValidator.validatePasswordStrength("Short1!"));
    }
    @Test
    public void testNoSpecialCharacterPassword() {
        assertEquals(false, PasswordStrengthValidator.validatePasswordStrength("NoSpecialChar1"));
    }
    @Test
    public void testWeakPassword() {
        assertEquals(false, PasswordStrengthValidator.validatePasswordStrength("WeakPass"));
    }
    @Test
    public void testStrongPassword() {
        assertEquals(true, PasswordStrengthValidator.validatePasswordStrength("StrongPass1!"));
    }
    @Test
    public void testValidPasswordWithSpecialCharacter() {
        assertEquals(true, PasswordStrengthValidator.validatePasswordStrength("ValidPassword1@"));
    }
}


import java.util.HashMap;
import java.util.Map;
public class ErrorInfoProvider {
    public static String getErrorMessage(int errorCode) {
        Map<Integer, String> errorMap = new HashMap<>();
        errorMap.put(1, "网络连接失败");
        errorMap.put(2, "用户认证失败");
        errorMap.put(3, "数据格式错误");
        errorMap.put(4, "权限不足");
        errorMap.put(5, "服务器内部错误");
        errorMap.put(6, "数据更新失败");
        errorMap.put(7, "资源未找到");
        return errorMap.getOrDefault(errorCode, "未知错误");
    }
    public static void check() {
        assert "网络连接失败".equals(getErrorMessage(1));
        assert "用户认证失败".equals(getErrorMessage(2));
        assert "数据格式错误".equals(getErrorMessage(3));
        assert "权限不足".equals(getErrorMessage(4));
        assert "服务器内部错误".equals(getErrorMessage(5));
        assert "数据更新失败".equals(getErrorMessage(6));
        assert "资源未找到".equals(getErrorMessage(7));
        assert "未知错误".equals(getErrorMessage(8));
    }
    public static void main(String[] args) {
        check();
    }
}

Please design a Java method that receives an integer parameter `errorCode` and returns the corresponding error message based on different error codes. The error codes and corresponding error messages are as follows:

- 1: "Network connection failed"
- 2: "User authentication failed"
- 3: "Data format error"
- 4: "Insufficient permissions"
- 5: "Internal server error"
- 6: "Data update failed"
- 7: "Resource not found"

If the input error code is not in the above list, please return "Unknown error".
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.HashMap;
import java.util.Map;
public class ErrorInfoProvider {
    public static String getErrorMessage(int errorCode) {
    }
    public static void check() {
    }
}
```

import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ErrorInfoProviderTest {
    @Test
    public void testGetErrorMessageForKnownErrorCodes() {
        assertEquals("网络连接失败", ErrorInfoProvider.getErrorMessage(1));
        assertEquals("用户认证失败", ErrorInfoProvider.getErrorMessage(2));
        assertEquals("数据格式错误", ErrorInfoProvider.getErrorMessage(3));
        assertEquals("权限不足", ErrorInfoProvider.getErrorMessage(4));
        assertEquals("服务器内部错误", ErrorInfoProvider.getErrorMessage(5));
    }
    @Test
    public void testGetErrorMessageForUnknownErrorCode() {
        assertEquals("未知错误", ErrorInfoProvider.getErrorMessage(999));
    }
    @Test
    public void testGetErrorMessageForBoundaryErrorCode() {
        assertEquals("网络连接失败", ErrorInfoProvider.getErrorMessage(1));
        assertEquals("未知错误", ErrorInfoProvider.getErrorMessage(0));
    }
    @Test
    public void testGetErrorMessageForNegativeErrorCode() {
        assertEquals("未知错误", ErrorInfoProvider.getErrorMessage(-1));
    }
    @Test
    public void testGetErrorMessageForNonMappedErrorCode() {
        assertEquals("未知错误", ErrorInfoProvider.getErrorMessage(10));
    }
}


import java.util.HashMap;
import java.util.Map;
public class WeChatPaymentService {
    public static void initiatePayment(String userOpenId, String serverIp, String orderAmount, String merchantOrderNo) throws Exception {
        HashMap<String, String> paymentData = new HashMap<>();
        paymentData.put("partner_trade_no", merchantOrderNo);
        paymentData.put("openid", userOpenId);
        paymentData.put("check_name", "NO_CHECK");
        paymentData.put("amount", orderAmount);
        paymentData.put("desc", "提现");
        paymentData.put("spbill_create_ip", serverIp);
    }
    public static boolean checkPaymentData(Map<String, String> data) {
        return data.containsKey("partner_trade_no") &&
               data.containsKey("openid") &&
               data.containsKey("check_name") &&
               data.containsKey("amount") &&
               data.containsKey("desc") &&
               data.containsKey("spbill_create_ip");
    }
    public static void main(String[] args) {
        try {
            String openId = "oLVPpjqs9BhvzwPj5A-vTYAX3GLc";
            String ip = "192.168.0.1";
            String amount = "200";
            String orderNo = "123456789";
            initiatePayment(openId, ip, amount, orderNo);
            HashMap<String, String> paymentData = new HashMap<>();
            paymentData.put("partner_trade_no", orderNo);
            paymentData.put("openid", openId);
            paymentData.put("check_name", "NO_CHECK");
            paymentData.put("amount", amount);
            paymentData.put("desc", "提现");
            paymentData.put("spbill_create_ip", ip);
            boolean isDataValid = checkPaymentData(paymentData);
            System.out.println("Payment data is valid: " + isDataValid);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Please write a Java method to handle a request for initiating a WeChat corporate payment to a user. The method should receive the user's OpenID and the server's IP address as parameters, and construct a data set with the necessary information to initiate the payment. Note that the payment amount and merchant order number should be passed to the method as parameters, rather than hardcoded in the code. Additionally, a validation function needs to be implemented to verify whether the payment request contains all necessary information.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.HashMap;
import java.util.Map;
public class WeChatPaymentService {
    public static void initiatePayment(String userOpenId, String serverIp, String orderAmount, String merchantOrderNo) throws Exception {
    }
    public static boolean checkPaymentData(Map<String, String> data) {
        return false;
    }
}
```

import org.junit.Test;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.Map;
public class WeChatPaymentServiceTest {
    @Test
    public void testInitiatePaymentWithValidData() throws Exception {
        String openId = "oLVPpjqs9BhvzwPj5A-vTYAX3GLc";
        String ip = "192.168.0.1";
        String amount = "200";
        String orderNo = "123456789";
        WeChatPaymentService.initiatePayment(openId, ip, amount, orderNo);
        Map<String, String> expectedData = new HashMap<>();
        expectedData.put("partner_trade_no", orderNo);
        expectedData.put("openid", openId);
        expectedData.put("check_name", "NO_CHECK");
        expectedData.put("amount", amount);
        expectedData.put("desc", "提现");
        expectedData.put("spbill_create_ip", ip);
        assertTrue(WeChatPaymentService.checkPaymentData(expectedData));
    }
    @Test
    public void testCheckPaymentDataWithValidData() {
        Map<String, String> validData = new HashMap<>();
        validData.put("partner_trade_no", "123456789");
        validData.put("openid", "oLVPpjqs9BhvzwPj5A-vTYAX3GLc");
        validData.put("check_name", "NO_CHECK");
        validData.put("amount", "200");
        validData.put("desc", "提现");
        validData.put("spbill_create_ip", "192.168.0.1");
        assertTrue(WeChatPaymentService.checkPaymentData(validData));
    }
    @Test
    public void testCheckPaymentDataWithMissingField() {
        Map<String, String> invalidData = new HashMap<>();
        invalidData.put("partner_trade_no", "123456789");
        invalidData.put("openid", "oLVPpjqs9BhvzwPj5A-vTYAX3GLc");
        invalidData.put("check_name", "NO_CHECK");
        invalidData.put("amount", "200");
        invalidData.put("spbill_create_ip", "192.168.0.1");
        assertFalse(WeChatPaymentService.checkPaymentData(invalidData));
    }
    @Test
    public void testCheckPaymentDataWithEmptyMap() {
        Map<String, String> emptyData = new HashMap<>();
        assertFalse(WeChatPaymentService.checkPaymentData(emptyData));
    }
    @Test
    public void testCheckPaymentDataWithInvalidField() {
        Map<String, String> invalidFieldData = new HashMap<>();
        invalidFieldData.put("partner_trade_no", "123456789");
        invalidFieldData.put("openid", "oLVPpjqs9BhvzwPj5A-vTYAX3GLc");
        invalidFieldData.put("check_name", "NO_CHECK");
        invalidFieldData.put("amount", "200");
        invalidFieldData.put("desc", "提现");
        invalidFieldData.put("invalid_field", "invalid_value");
        assertFalse(WeChatPaymentService.checkPaymentData(invalidFieldData));
    }
}


import java.lang.Exception;
class InvalidIntegerException extends Exception {
    public InvalidIntegerException(String message) {
        super(message);
    }
}
public class StringToIntConverter {
    public static int convertStringToInt(String str) throws InvalidIntegerException {
        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException e) {
            throw new InvalidIntegerException("无效的整数: " + str);
        }
    }
    public static void main(String[] args) {
        try {
            System.out.println(convertStringToInt("123"));
            System.out.println(convertStringToInt("abc"));
        } catch (InvalidIntegerException e) {
            System.out.println(e.getMessage());
        }
    }
}

Please write a Java method that takes a string parameter representing an integer. The purpose of the method is to convert this string to an integer and return it. If the input string is not a valid integer, the method should throw a custom exception with the message "Invalid integer: " followed by the original input string. Make sure your code can handle exceptions, and explicitly declare the exceptions that might be thrown in the method signature.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.lang.Exception;
class InvalidIntegerException extends Exception {
    public InvalidIntegerException(String message) {
        super(message);
    }
}
public class StringToIntConverter {
    public static int convertStringToInt(String str) throws InvalidIntegerException {

    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class StringToIntConverterTest {
    @Test
    void testConvertStringToIntValid() {
        try {
            assertEquals(123, StringToIntConverter.convertStringToInt("123"));
            assertEquals(-456, StringToIntConverter.convertStringToInt("-456"));
        } catch (InvalidIntegerException e) {
            fail("Exception should not have been thrown");
        }
    }
    @Test
    void testConvertStringToIntInvalid() {
        assertThrows(InvalidIntegerException.class, () -> {
            StringToIntConverter.convertStringToInt("abc");
        });
    }
    @Test
    void testConvertStringToIntEmptyString() {
        assertThrows(InvalidIntegerException.class, () -> {
            StringToIntConverter.convertStringToInt("");
        });
    }
    @Test
    void testConvertStringToIntNull() {
        assertThrows(InvalidIntegerException.class, () -> {
            StringToIntConverter.convertStringToInt(null);
        });
    }
    @Test
    void testConvertStringToIntWhiteSpace() {
        assertThrows(InvalidIntegerException.class, () -> {
            StringToIntConverter.convertStringToInt(" ");
        });
    }
}


import java.util.function.BiFunction;
public class SimpleCalculator {
    public int add(int a, int b) {
        return a + b;
    }
    public int subtract(int a, int b) {
        return a - b;
    }
    public static void main(String[] args) {
        SimpleCalculator calculator = new SimpleCalculator();
        check("加法", 5, 3, 8, calculator::add);
        check("减法", 5, 3, 2, calculator::subtract);
    }
    private static void check(String testName, int a, int b, int expected, BiFunction<Integer, Integer, Integer> operation) {
        int result = operation.apply(a, b);
        assert result == expected : testName + "失败";
        System.out.println(testName + "成功");
    }
}

Please write a Java program to implement a simple calculator class `SimpleCalculator`. This calculator should include two methods: `add` and `subtract`, which are used to calculate the sum and difference of two integers, respectively.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.function.BiFunction;
public class SimpleCalculator {
    public int add(int a, int b) {
    }
    public int subtract(int a, int b) {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class SimpleCalculatorTest {
    @Test
    public void testAdd() {
        SimpleCalculator calculator = new SimpleCalculator();
        assertEquals(8, calculator.add(5, 3));
        assertEquals(0, calculator.add(2, -2));
        assertEquals(-10, calculator.add(-5, -5));
    }
    @Test
    public void testSubtract() {
        SimpleCalculator calculator = new SimpleCalculator();
        assertEquals(2, calculator.subtract(5, 3));
        assertEquals(4, calculator.subtract(2, -2));
        assertEquals(0, calculator.subtract(-5, -5));
    }
    @Test
    public void testAddEdgeCases() {
        SimpleCalculator calculator = new SimpleCalculator();
        assertEquals(0, calculator.add(0, 0));
        assertEquals(Integer.MAX_VALUE, calculator.add(Integer.MAX_VALUE, 0));
        assertEquals(Integer.MIN_VALUE, calculator.add(Integer.MIN_VALUE, 0));
    }
    @Test
    public void testSubtractEdgeCases() {
        SimpleCalculator calculator = new SimpleCalculator();
        assertEquals(0, calculator.subtract(0, 0));
        assertEquals(Integer.MAX_VALUE, calculator.subtract(Integer.MAX_VALUE, 0));
        assertEquals(Integer.MIN_VALUE, calculator.subtract(Integer.MIN_VALUE, 0));
    }
}


import java.util.Optional;
public class OptionalExample {
    public void processOptionalString(Optional<String> input) {
        input.ifPresentOrElse(
            value -> System.out.println(value),
            () -> System.out.println("未提供值")
        );
    }
    public static void main(String[] args) {
        OptionalExample example = new OptionalExample();
        Optional<String> nonEmptyOptional = Optional.of("Hello, World!");
        example.processOptionalString(nonEmptyOptional);
        Optional<String> emptyOptional = Optional.empty();
        example.processOptionalString(emptyOptional);
    }
}

Please write a Java program to implement a function that receives a possibly empty string and processes it. If the string exists, print the string; if the string does not exist, print "No value provided". Use the `Optional` class to implement this logic.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Optional;
public class OptionalExample {
    public void processOptionalString(Optional<String> input) {
    }
}
```

import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class OptionalExampleTest {
    private OptionalExample example;
    @BeforeEach
    public void setUp() {
        example = new OptionalExample();
    }
    @Test
    public void testProcessOptionalStringWithNonEmptyOptional() {
        Optional<String> nonEmptyOptional = Optional.of("Test String");
        example.processOptionalString(nonEmptyOptional);
    }
    @Test
    public void testProcessOptionalStringWithEmptyOptional() {
        Optional<String> emptyOptional = Optional.empty();
        example.processOptionalString(emptyOptional);
    }
    @Test
    public void testProcessOptionalStringWithNullValue() {
        Optional<String> nullOptional = Optional.ofNullable(null);
        example.processOptionalString(nullOptional);
    }
    @Test
    public void testProcessOptionalStringWithWhitespaceString() {
        Optional<String> whitespaceString = Optional.of(" ");
        example.processOptionalString(whitespaceString);
    }
    @Test
    public void testProcessOptionalStringWithSpecialCharacters() {
        Optional<String> specialCharacters = Optional.of("!@#$%^&*()");
        example.processOptionalString(specialCharacters);
    }
}


import java.util.Optional;
public class DefaultValueGetter {
    public static int getNumberOrDefault(Integer number) {
        Optional<Integer> optionalNumber = Optional.ofNullable(number);
        return optionalNumber.orElse(100);
    }
    public static void checkFunction() {
        Integer test1 = null;
        Integer test2 = 50;
        System.out.println("Test1 (Expected: 100): " + getNumberOrDefault(test1));
        System.out.println("Test2 (Expected: 50): " + getNumberOrDefault(test2));
    }
    public static void main(String[] args) {
        checkFunction();
    }
}

Please write a Java function that accepts an integer value that may be null. If the value is not null, it directly returns that value; if it is null, it returns a default value of 100. Use the `Optional` class to implement this logic to ensure code robustness.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.Optional;
public class DefaultValueGetter {
    public static int getNumberOrDefault(Integer number) {
    }
    public static void checkFunction() {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DefaultValueGetterTest {
    @Test
    public void testGetNumberOrDefault_withNull() {
        Integer testInput = null;
        int expectedOutput = 100;
        assertEquals(expectedOutput, DefaultValueGetter.getNumberOrDefault(testInput));
    }
    @Test
    public void testGetNumberOrDefault_withNonNull() {
        Integer testInput = 50;
        int expectedOutput = 50;
        assertEquals(expectedOutput, DefaultValueGetter.getNumberOrDefault(testInput));
    }
    @Test
    public void testGetNumberOrDefault_withNegativeValue() {
        Integer testInput = -10;
        int expectedOutput = -10;
        assertEquals(expectedOutput, DefaultValueGetter.getNumberOrDefault(testInput));
    }
    @Test
    public void testGetNumberOrDefault_withZero() {
        Integer testInput = 0;
        int expectedOutput = 0;
        assertEquals(expectedOutput, DefaultValueGetter.getNumberOrDefault(testInput));
    }
    @Test
    public void testGetNumberOrDefault_withPositiveValue() {
        Integer testInput = 200;
        int expectedOutput = 200;
        assertEquals(expectedOutput, DefaultValueGetter.getNumberOrDefault(testInput));
    }
}


import java.util.HashMap;
import java.util.Map;
class ProductNotFoundException extends RuntimeException {
    public ProductNotFoundException(String message) {
        super(message);
    }
}
class Product {
    private String id;
    private int status;
    public Product(String id, int status) {
        this.id = id;
        this.status = status;
    }
    public String getId() {
        return id;
    }
    public int getStatus() {
        return status;
    }
}
class ProductRepository {
    private Map<String, Product> productMap = new HashMap<>();
    public ProductRepository() {
        productMap.put("123", new Product("123", 1));
        productMap.put("456", new Product("456", 0));
    }
    public Product findById(String id) {
        return productMap.get(id);
    }
}
public class ProductFinder {
    private ProductRepository productRepo = new ProductRepository();
    public Product findActiveProductById(String id) {
        Product product = productRepo.findById(id);
        if (product != null && product.getStatus() == 1) {
            return product;
        } else {
            throw new ProductNotFoundException("Product not found or not active");
        }
    }
    public static void main(String[] args) {
        ProductFinder finder = new ProductFinder();
        try {
            Product product = finder.findActiveProductById("123");
            System.out.println("Found product: " + product.getId());
        } catch (ProductNotFoundException e) {
            System.out.println(e.getMessage());
        }
        try {
            finder.findActiveProductById("456");
        } catch (ProductNotFoundException e) {
            System.out.println(e.getMessage());
        }
    }
}

Please design a Java method that retrieves and returns the information of a product with a specific status. If the product exists and its status is active (status code is 1), return the product information; if the product does not exist or its status is not active, throw an exception.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.HashMap;
import java.util.Map;
class ProductNotFoundException extends RuntimeException {
    public ProductNotFoundException(String message) {
        super(message);
    }
}
class Product {
    private String id;
    private int status;
    public Product(String id, int status) {
        this.id = id;
        this.status = status;
    }
    public String getId() {
        return id;
    }
    public int getStatus() {
        return status;
    }
}
class ProductRepository {
    private Map<String, Product> productMap = new HashMap<>();
    public ProductRepository() {
    }
    public Product findById(String id) {
    }
}
public class ProductFinder {
    private ProductRepository productRepo = new ProductRepository();
    public Product findActiveProductById(String id) {
    }
}
```

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ProductFinderTest {
    @Test
    void testFindActiveProductById_ProductExistsAndIsActive() {
        ProductFinder finder = new ProductFinder();
        Product product = finder.findActiveProductById("123");
        assertNotNull(product);
        assertEquals("123", product.getId());
    }
    @Test
    void testFindActiveProductById_ProductExistsButNotActive() {
        ProductFinder finder = new ProductFinder();
        assertThrows(ProductNotFoundException.class, () -> {
            finder.findActiveProductById("456");
        });
    }
    @Test
    void testFindActiveProductById_ProductDoesNotExist() {
        ProductFinder finder = new ProductFinder();
        assertThrows(ProductNotFoundException.class, () -> {
            finder.findActiveProductById("789");
        });
    }
    @Test
    void testFindActiveProductById_ProductRepositoryIsInitializedCorrectly() {
        ProductFinder finder = new ProductFinder();
        Product product1 = finder.findActiveProductById("123");
        assertNotNull(product1);
        assertEquals(1, product1.getStatus());
        assertThrows(ProductNotFoundException.class, () -> {
            finder.findActiveProductById("456");
        });
    }
}


import java.util.HashMap;
import java.util.Map;
public class ProjectManagementServiceFactory {
    private Map<String, ProjectManagementService> services = new HashMap<>();
    public ProjectManagementServiceFactory() {
        services.put("jiraServer", new JiraServerService());
        services.put("jiraCloud", new JiraCloudService());
    }
    public ProjectManagementService getService(String tokenIdentifier) {
        for (String key : services.keySet()) {
            ProjectManagementService service = services.get(key);
            if (service.containsToken(tokenIdentifier)) {
                return service;
            }
        }
        return null;
    }
    public static void main(String[] args) {
        ProjectManagementServiceFactory factory = new ProjectManagementServiceFactory();
        ProjectManagementService service = factory.getService("someToken");
        if (service != null) {
            System.out.println("获取到的服务实例: " + service.getClass().getSimpleName());
        } else {
            System.out.println("没有找到匹配的服务实例");
        }
    }
}
interface ProjectManagementService {
    boolean containsToken(String token);
}
class JiraServerService implements ProjectManagementService {
    @Override
    public boolean containsToken(String token) {
        return "jiraServerToken".equals(token);
    }
}
class JiraCloudService implements ProjectManagementService {
    @Override
    public boolean containsToken(String token) {
        return "jiraCloudToken".equals(token);
    }
}

Let's assume you are developing a project management system that needs to support various project management tools, such as Jira Server and Jira Cloud. There is a feature in the system that retrieves the corresponding project management tool service based on a provided token identifier. Describe how you would design a Java method that takes a token identifier as a parameter and then returns the corresponding project management tool service instance based on that identifier. If there is no matching service in the system, it should return null. Ensure that your design can be easily extended to support more project management tools in the future.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.HashMap;
import java.util.Map;
public class ProjectManagementServiceFactory {
    private Map<String, ProjectManagementService> services = new HashMap<>();
    public ProjectManagementServiceFactory() {
    }
    public ProjectManagementService getService(String tokenIdentifier) {
        return null;
    }
}
interface ProjectManagementService {
    boolean containsToken(String token);
}
class JiraServerService implements ProjectManagementService {
    @Override
    public boolean containsToken(String token) {
        return false;
    }
}
class JiraCloudService implements ProjectManagementService {
    @Override
    public boolean containsToken(String token) {
        return false;
    }
}
```

import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class ProjectManagementServiceFactoryTest {
    private ProjectManagementServiceFactory factory;
    @Before
    public void setUp() {
        factory = new ProjectManagementServiceFactory();
    }
    @Test
    public void testGetServiceWithJiraServerToken() {
        ProjectManagementService service = factory.getService("jiraServerToken");
        assertNotNull(service);
        assertTrue(service instanceof JiraServerService);
    }
    @Test
    public void testGetServiceWithJiraCloudToken() {
        ProjectManagementService service = factory.getService("jiraCloudToken");
        assertNotNull(service);
        assertTrue(service instanceof JiraCloudService);
    }
    @Test
    public void testGetServiceWithInvalidToken() {
        ProjectManagementService service = factory.getService("invalidToken");
        assertNull(service);
    }
    @Test
    public void testGetServiceWithEmptyToken() {
        ProjectManagementService service = factory.getService("");
        assertNull(service);
    }
    @Test
    public void testGetServiceWithNullToken() {
        ProjectManagementService service = factory.getService(null);
        assertNull(service);
    }
}


import java.util.UUID;
class ResultVO {
    private boolean success;
    private String message;
    private String data;
    public ResultVO(boolean success, String message, String data) {
        this.success = success;
        this.message = message;
        this.data = data;
    }
    public static ResultVO setSuccess(String message, String data) {
        return new ResultVO(true, message, data);
    }
    public boolean isSuccess() {
        return success;
    }
    public String getMessage() {
        return message;
    }
    public String getData() {
        return data;
    }
}
class Book {
    private String bookId;
    private String title;
    public Book(String title) {
        this.bookId = UUID.randomUUID().toString();
        this.title = title;
    }
    public String getBookId() {
        return bookId;
    }
    public String getTitle() {
        return title;
    }
}
class LibrarySystem {
    public ResultVO addNewBook(Book newBook) {
        System.out.println("Adding book: " + newBook.getTitle());
        return ResultVO.setSuccess("添加成功", newBook.getBookId());
    }
}
public class Main {
    public static void main(String[] args) {
        LibrarySystem librarySystem = new LibrarySystem();
        Book newBook = new Book("Java编程思想");
        ResultVO result = librarySystem.addNewBook(newBook);
        System.out.println("操作是否成功: " + result.isSuccess());
        System.out.println("消息: " + result.getMessage());
        System.out.println("新书ID: " + result.getData());
    }
}

Please write a Java method for adding new books to a library. The method should accept a Book object as a parameter and save it to the database. If the addition is successful, the method should return a result object containing success information and the new book ID.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.UUID;
class ResultVO {
    private boolean success;
    private String message;
    private String data;
    public ResultVO(boolean success, String message, String data) {
    }
    public static ResultVO setSuccess(String message, String data) {
    }
    public boolean isSuccess() {
    }
    public String getMessage() {
    }
    public String getData() {
    }
}
class Book {
    private String bookId;
    private String title;
    public Book(String title) {
    }
    public String getBookId() {
    }
    public String getTitle() {
    }
}
class LibrarySystem {
    public ResultVO addNewBook(Book newBook) {
    }
}
```

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class ResultVOTest {
    private ResultVO resultVO;
    @BeforeEach
    void setUp() {
        resultVO = new ResultVO(true, "Test Message", "TestData");
    }
    @Test
    void testSetSuccess() {
        ResultVO result = ResultVO.setSuccess("Success", "Data");
        Assertions.assertTrue(result.isSuccess());
        Assertions.assertEquals("Success", result.getMessage());
        Assertions.assertEquals("Data", result.getData());
    }
    @Test
    void testIsSuccess() {
        Assertions.assertTrue(resultVO.isSuccess());
    }
    @Test
    void testGetMessage() {
        Assertions.assertEquals("Test Message", resultVO.getMessage());
    }
    @Test
    void testGetData() {
        Assertions.assertEquals("TestData", resultVO.getData());
    }
}
class BookTest {
    private Book book;
    @BeforeEach
    void setUp() {
        book = new Book("Test Title");
    }
    @Test
    void testGetBookId() {
        String bookId = book.getBookId();
        Assertions.assertNotNull(bookId);
    }
    @Test
    void testGetTitle() {
        Assertions.assertEquals("Test Title", book.getTitle());
    }
}
class LibrarySystemTest {
    private LibrarySystem librarySystem;
    private Book book;
    @BeforeEach
    void setUp() {
        librarySystem = new LibrarySystem();
        book = new Book("Test Book");
    }
    @Test
    void testAddNewBook() {
        ResultVO result = librarySystem.addNewBook(book);
        Assertions.assertTrue(result.isSuccess());
        Assertions.assertEquals("添加成功", result.getMessage());
        Assertions.assertEquals(book.getBookId(), result.getData());
    }
}


import java.lang.Math;
public class WeatherDataValidator {
    public boolean checkWeatherData(float temperature, float humidity, int windSpeed) {
        return checkTemperature(temperature) && checkHumidity(humidity) && checkWindSpeed(windSpeed);
    }
    private boolean checkTemperature(float temperature) {
        return Math.abs(temperature) <= 100;
    }
    private boolean checkHumidity(float humidity) {
        return humidity >= 0 && humidity <= 100;
    }
    private boolean checkWindSpeed(int windSpeed) {
        return windSpeed >= 0 && windSpeed <= 150;
    }
    public static void main(String[] args) {
        WeatherDataValidator validator = new WeatherDataValidator();
        System.out.println(validator.checkWeatherData(25.5f, 65.0f, 20));
        System.out.println(validator.checkWeatherData(-101.0f, 65.0f, 20));
        System.out.println(validator.checkWeatherData(25.5f, -1.0f, 20));
        System.out.println(validator.checkWeatherData(25.5f, 65.0f, 151));
    }
}

Please write a Java method to check if the meteorological data collected by a weather station is within a reasonable range. The method will receive three parameters: temperature (float), humidity (float), and wind speed (integer). If all parameters are within the predefined valid range, the method returns `true`; otherwise, it returns `false`. Assume you already have three auxiliary methods: `checkTemperature`, `checkHumidity`, and `checkWindSpeed`, which are used to validate the temperature, humidity, and wind speed, respectively. Ensure your code is completely self-contained and includes all necessary import statements.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.lang.Math;
public class WeatherDataValidator {
    public boolean checkWeatherData(float temperature, float humidity, int windSpeed) {
    }
    private boolean checkTemperature(float temperature) {
    }
    private boolean checkHumidity(float humidity) {
    }
    private boolean checkWindSpeed(int windSpeed) {
    }
}
```

import org.junit.Test;
import static org.junit.Assert.*;
public class WeatherDataValidatorTest {
    @Test
    public void testCheckWeatherData_ValidData() {
        WeatherDataValidator validator = new WeatherDataValidator();
        assertTrue(validator.checkWeatherData(25.5f, 65.0f, 20));
    }
    @Test
    public void testCheckWeatherData_InvalidTemperature() {
        WeatherDataValidator validator = new WeatherDataValidator();
        assertFalse(validator.checkWeatherData(-101.0f, 65.0f, 20));
    }
    @Test
    public void testCheckWeatherData_InvalidHumidity() {
        WeatherDataValidator validator = new WeatherDataValidator();
        assertFalse(validator.checkWeatherData(25.5f, -1.0f, 20));
    }
    @Test
    public void testCheckWeatherData_InvalidWindSpeed() {
        WeatherDataValidator validator = new WeatherDataValidator();
        assertFalse(validator.checkWeatherData(25.5f, 65.0f, 151));
    }
    @Test
    public void testCheckWeatherData_UpperBoundaryValues() {
        WeatherDataValidator validator = new WeatherDataValidator();
        assertTrue(validator.checkWeatherData(100.0f, 100.0f, 150));
    }
}


import java.util.LinkedList;
public class MessageQueueManager {
    private LinkedList<String> queue = new LinkedList<>();
    public synchronized void addMessage(String message) {
        queue.addLast(message);
        notifyAll();
    }
    public synchronized String getMessage() throws InterruptedException {
        while (queue.isEmpty()) {
            wait();
        }
        return queue.removeFirst();
    }
    public static void main(String[] args) throws InterruptedException {
        MessageQueueManager manager = new MessageQueueManager();
        manager.addMessage("Hello");
        manager.addMessage("World");
        System.out.println(manager.getMessage());
        System.out.println(manager.getMessage());
    }
}

Please write a Java program to implement a simple message queue management system. The system should allow users to add messages to the queue and retrieve and remove messages from the queue according to the FIFO (First-In-First-Out) principle. Ensure that your implementation is thread-safe.
Please use Java to implement the complete code without the Main function. Please follow the following type definitions:

```java
import java.util.LinkedList;
public class MessageQueueManager {
    private LinkedList<String> queue = new LinkedList<>();
    public synchronized void addMessage(String message) {
    }
    public synchronized String getMessage() throws InterruptedException {
    }
}
```

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class MessageQueueManagerTest {
    private MessageQueueManager manager;
    @BeforeEach
    public void setUp() {
        manager = new MessageQueueManager();
    }
    @Test
    public void testAddMessage() throws InterruptedException {
        manager.addMessage("TestMessage");
        assertEquals("TestMessage", manager.getMessage());
    }
    @Test
    public void testGetMessageWithMultipleMessages() throws InterruptedException {
        manager.addMessage("Message1");
        manager.addMessage("Message2");
        assertEquals("Message1", manager.getMessage());
        assertEquals("Message2", manager.getMessage());
    }
    @Test
    public void testGetMessageWhenQueueIsEmpty() {
        Thread thread = new Thread(() -> {
            try {
                manager.getMessage();
                fail("Expected InterruptedException was not thrown");
            } catch (InterruptedException e) {
            }
        });
        thread.start();
        thread.interrupt();
    }
    @Test
    public void testNotifyAllAfterAddMessage() throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                assertEquals("Message1", manager.getMessage());
            } catch (InterruptedException e) {
                fail(e.getMessage());
            }
        });
        thread.start();
        manager.addMessage("Message1");
        thread.join();
    }
    @Test
    public void testQueueOrderIsMaintained() throws InterruptedException {
        manager.addMessage("First");
        manager.addMessage("Second");
        manager.addMessage("Third");
        assertEquals("First", manager.getMessage());
        assertEquals("Second", manager.getMessage());
        assertEquals("Third", manager.getMessage());
    }
}