Check if your network status is OK and if you can access other websites.
Try a different browser or clear browser cache.
Check if the HOSTS file maps the domain name to 127.0.0.1 or an incorrect IP address. You can see what IP address the domain name is mapped to with the following command line.
ping {your_domain}
Check if you are using a HTTP proxy or if the proxy can access the website.
DNS Settings
Check that the A record of the DNS configuration points the domain name to the correct IP address.
Cloud Host
Check if the cloud host is on and accessible. You can use the following command line to check if cloud host is on.
ping {IP_address}
Check if the HTTP (80) or HTTPS (443) port is allowed in the firewall.
telnet {IP_address} 80 telnet {IP_address} 443
Check that the reverse proxy server listening on port 80 or 443 is running. You can find out what process is using 80 or 443 with the following command line.
sudo lsof -i -P -n | grep LISTEN
Check if the configuration of the reverse proxy server is correct.
Check if the actual web project is up and running. You can view all processes with the following command line.
ps -ef
Check that the cloud host operating system has sufficient resources such as CPU, memory, disk, and bandwidth. You can view the resource usage of the cloud host in the cloud platform console or view usage by command lines.
Setting your basic configurations. The following is my settings
Project: Maven
Language: Java
Spring Boot: 2.7.9
Project Metadata:
Group: com.taogen
Aritifact: chatgpt-demo
Packaging: Jar
Java: 8
You can set your own configurations according to your local environment.
After setting the project configurations, we need to add the following dependencies:
Spring Web
Lombok
Then we click the GENERATE button to download our project file.
After downloading the generated project file, we need to decompress the file and open the directory in our IDE. I prefer to use IntelliJ IDEA as my IDE.
Call the ChatGPT API in spring boot
Configuring your Open AI key in application.properties
openai.apiKey=${YOUR_OPEN_AI_KEY}
Create the RestTemplateConfig.java to build the RestTemplate bean for API calls
The ChatBotController sends an HTTP request to ChatGPT API and reads its response stream line by line. Each line of the response has a similar structure. We extract the chat content by removing the prefix data: , parsing the string to a JSON object, and retrieving the content value. This content is then written into the response of our chatbot API. The following is an example of the content of the ChatGPT API response.
curl -d 'hello' -H 'Content-Type: application/json' -X POST http://localhost:8080/chatbot/conversation
Hi there! How can I assist you today?
Note: If ChatGPT is not available in your region, you will not be able to call the ChatGPT API and the request will time out. Your application may throw the following exception:
2023-03-16 14:40:22.680 ERROR 14704 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://api.openai.com/v1/engines/davinci-codex/completions": Connection timed out: connect; nested exception is java.net.ConnectException: Connection timed out: connect] with root cause java.net.ConnectException: Connection timed out: connect
For long-running programs, you’ll need to look at the log files to check that the program is functioning correctly.
2. For the scheduled task thread or any thread other than the main thread, catch the entire code block exception.
Generally, the main thread has global exception handling, but other threads do not.
3. No empty catch blocks.
An empty catch block won’t give you any information about what exception occurred. Probably the exception doesn’t matter, but it’s still an exceptional case.
4. Separate business and functional code.
Businesses are changing and functions are shared and reusable.
5. Divide your code by domain rather than by functionality or class type.
Usually, changes in your application are related to a specific domain, you should focus on business domains when building your structures, not functionality or class type.
6. Don’t create unnecessary variables, objects in a loop block.
Be careful when creating objects in a loop block. Create objects before a loop block if possible. Don’t create a lot of unnecessary objects in a loop block. For example, java.text.SimpleDateFormat, org.apache.poi.xssf.usermodel.XSSFCellStyle objects.
7. Don’t use Java internal code. All classes in com.sun.*, sun.*, or jdk.*are notionally internal, and should not be used directly in your code. All the classes you can use are in the Java API documentation, such as java.*, javax.*, and org.*.
Data Access
1. Never execute SQL statements in a for loop.
It takes a lot of time. You should find a way to do it in bulk.
Java Web and Spring Boot
1. Scheduling tasks should run when a specific profile is activated.
If the project is deployed on multiple servers, each server will execute scheduled tasks. Even if it activates different profiles on different servers.
2. API URLs use domain names rather than IP addresses.
If you use IP-based API URLs in many projects, you need to change many projects whenever the IP address changes.
3. Use Environment Variables in spring boot configuration files.
Don’t expose your confidential information in source code.
1. Use a new git branch to develop new features. After finishing a new feature, switch to the main branch.
It’s much clearer when you’re doing multiple functions at the same time.
2. The committed code needs to push to the remote repository as soon as possible.
Code in a local environment can easily get lost. One time I deleted the entire project directory and my code was lost.
3. The test code is for testing only. Don’t use test code as your functional source code.
4. Use environment variables for configurations. Don’t hardcode configuration.
It’s safe and convenient.
5. Don’t keep uncommitted changes of code all the time. Either commit and push it to a remote branch or restore it.
First, uncommitted and unpushed changes are easily lost. Second, keep uncommitted changes makes new updates to the same file difficult. Third, It also messes up code commits.
If the changes are important and you won’t need them for a while, you can copy and save them to another place.
6. First, solve the problem. Then, write the code. Before writing code, you need to understand and organize the requirements and complete the database design, API design, and detailed design.
It makes development easier.
7. Anything that can be automated should be automated.
The problem “cannot resolve symbol” means IDEA hasn’t successfully indexed your project code and dependent libraries.
There are two common problems that cause the “cannot resolve symbol” problems:
Maven dependency configuration problems.
IDEA problems.
Maven Configuration Problems
Ensure Maven dependency resolve correctly
Your project’s Maven dependencies must be resolved correctly. Otherwise, IDEA can’t index project files successfully.
To check that Maven dependencies are resolved correctly, you can execute the following command:
mvn -Dmaven.test.skip=true clean package
If you can’t pass the above command, then there is something wrong with your Maven configuration. You can update your pom.xml and run the above command again.
After you passed the above command by updating your pom.xml, you need to reload the maven project to download missing dependencies. Right click the pom.xml in IDEA -> Maven -> Reload project. If the “cannot resolve symbol” errors are gone, the problem is solved.
If you have passed the above command and reloaded the project but there are still the “cannot resolve symbol” problems in IDEA, then it’s IDEA problems not Maven. You can go to the “Problems with IDEA” section.
Common problems and solutions with Maven
Problem 1: The dependency cannot be found
This means that the dependency cannot be found from the remote Maven repository.
Error Information:
Could not resolve dependencies for project {your_project}: Failed to collect dependencies at {groupId}:{artifactId}.jar:{version}
Solutions:
Check if the groupId, artifactId or version of the dependency is correct.
Check if there is an unofficial repository defined in the project’s pom.xml or ~/.m2/settings.xml, try using Maven central repository.
<repository> <id>central</id> <name>Maven Central Repository</name> <url>https://repo1.maven.org/maven2</url> </repository>
Problem 2: dependency conflict
This means that multiple versions of a dependency are added or indirectly added to the Maven project. A dependency can only exist in one version. The actual version used causes the referenced method or class to be unable to be found.
Error Information:
NoClassDefFoundError, ClassNotFoundException, or NoSuchMethodError
Solutions
Use the “Maven Helper” plugin to check if there is a dependency conflict. You can try excluding unwanted versions by right-clicking on the version in the Maven Helper plugin window.
If your Maven project has a parent project, you also need to check whether the version defined in the parent project is compatible with your current project.
More tips
If you pom.xml is correct, but you still can’t pass mvn clean package. You can try to force update dependencies:
# force update the dependencies mvn clean package -U
Problems with IDEA
Try to re-index your project files
Close the project or exit IDEA, then delete the .idea folder, then reopen project or restart IDEA. When there is no .idea folder in your project root path, IDEA will re-index project files automatically.
In addition to the .idea folder, if your project is a git repository, it’s recommended to delete all file ignored by git.
# delete git ignored files git clean -dfx
After you re-indexed the project (delete .idea), if the “cannot resolve symbol” errors are gone, the problem is solved.
If the “cannot resolve symbol” errors still exist, you can try rebuild project. In top menu bar, Build -> Rebuild project.
If you have re-indexed the project (delete .idea) and rebuilt the project but the “cannot resolve symbol” errors still exist, you can go to the next step “Invalidate IDEA cache”.
Invalidate IDEA cache
IDEA cache also affects IDEA index project files. If your Maven configurations are right, but there are still “cannot resolve symbol” problems. You can try to Invalidate Caches:
File -> Invalidate Caches -> checked “clear file system cache and Local History”, and then click “Invalidate and Restart”.
Re-enter IDEA and waiting for “Update indexes” to complete. After “Update indexes” is done. Then we need rebulid the project:
Build -> click “Rebuild Project”.
After invalidated IDEA cache, if the “cannot resolve symbol” errors are gone, the problem is solved. Otherwise, You can try to re-index your project files again.
In this post, I will introduce several ways to find HTML DOM elements in JavaScript.
querySelector methods
Document or Element methods
querySelectorAll(selectors)
Parameters: the selectors parameter is a valid CSS selector string.
Return Value: returns a static (not live) NodeList representing a list of the document’s elements that match the specified group of selectors, or an empty NodeList in case of no matches.
querySelector(selectors)
Parameters: the selectors parameter is a valid CSS selector string.
Return Value: return an Element object representing the first element in the document that matches the specified set of CSS selectors, or null is returned if there are no matches.
Find by id
document.querySelector("#test")
Find by HTML tag
document.querySelectorAll("p")
Find by class names
document.querySelectorAll("div.className1") // or document.querySelectorAll(".className1")
Find by attributes
// match elements contain a attribute document.querySelectorAll("elementName[attrName]") // match attribute value container.querySelectorAll("elementName[attrName='attrValue']"); // attribute value start with container.querySelectorAll("elementName[attrName^='attrValue']"); // attribute value end with container.querySelectorAll("elementName[attrName$='attrValue']"); // attribute value contains container.querySelectorAll("elementName[attrName*='attrValue']");
and
document.querySelectorAll("div.className1.className2"); // or document.querySelectorAll(".className1.className2");
document.querySelectorAll("div[attr1='value1'][attr2='value2']"); // or document.querySelectorAll("[attr1='value1'][attr2='value2']");
or
document.querySelectorAll("div.className1, div.className2"); // or document.querySelectorAll(".className1, .className2");
Find descendants, children, siblings with tag names
// descendants document.querySelectorAll("div span"); // the first span descendant document.querySelectorAll("div span:nth-of-type(1)"); // children document.querySelectorAll("div>span"); // the first child element document.querySelectorAll("div :nth-child(1)") // siblings document.querySelectorAll("div~img"); // adjacent sibling document.querySelectorAll("div+img");
nth-child(n) : Selects the nth child of a parent, regardless of the type of element.
nth-of-type(n) : Selects the nth child of a specific type within its parent.
const matchedElements = document.querySelectorAll("div"); // querySelectorAll returns a NodeList not an Array. You can convert it to an Array Array.from(matchedElements).filter((item) => item.classList.contains('note'));
Parameters: nameAttrValue the value of the name attribute of the element(s) we are looking for.
Return value: A live NodeList collection, meaning it automatically updates as new elements with the same name are added to, or removed from, the document.
getElementsByTagName(elementName)
Parameters: elementName a string representing the name of the elements. The special string * represents all elements.