Arrays
In order to solve this issue, a number of array-related tasks had to be completed. In particular, summing elements and determining if sums in a two-dimensional array context are unique required attention. Arrays are shown through how it deals with JSON objects and arrays, which are often used to represent structured data received from APIs. This Java code snippet is a part of an application that communicates with a server via HTTP requests to retrieve and process JSON data. It includes methods for sending HTTP GET and POST requests (sendHttpGet and sendHttpPost). The sendHttpGet method sends an HTTP GET request to a specified URL and returns the JSON response received from the server. The response is then parsed to extract relevant information, such as the first_id and data array containing messages from a specific thread. The code iterates through the data array to find and extract the text value of messages sent by an assistant. These messages are appended to a StringBuilder named chatResponse, which holds the response generated by the model for the given thread.
String getResponseUrl = "https://api.openai.com/v1/threads/" + threadId + "/messages";
JSONObject rObj = sendHttpGet(getResponseUrl, contentType, auth, openAiBeta, org);
System.out.println(rObj.toJSONString());
// the response will match the first id
String firstId = (String)rObj.get("first_id");
// get data array from json
JSONArray dataArray = (JSONArray)rObj.get("data");
// to create the response string
StringBuilder chatReponse = new StringBuilder();
for (int i = 0; i < dataArray.size(); i++) {
JSONObject anObj = (JSONObject)dataArray.get(i);
// the role must be assistant to hold the value and id must match firstId
if (anObj.get("role").equals("assistant") && anObj.get("id").equals(firstId)) {
JSONArray contentArray = (JSONArray)anObj.get("content");
for (int j = 0; j < contentArray.size(); j++) {
JSONObject contentObj = (JSONObject)contentArray.get(j);
JSONObject textObj = (JSONObject)contentObj.get("text");
// this contains the chat gpt's response
chatReponse.append((String)textObj.get("value"));
break;
}
}
}
return chatReponse.toString();
}
// send http post and return JSON response
public static JSONObject sendHttpPost(String url, String body, Header... headers) throws Exception {
JSONObject json = null;
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(body));
httpPost.setHeaders(headers);
json = httpClient.execute(httpPost, new JSONResponseHandler());
}
return json;
}
// send http get and return JSON response
public static JSONObject sendHttpGet(String url, Header... headers) throws Exception {
JSONObject json = null;
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet(url);
httpGet.setHeaders(headers);
json = httpClient.execute(httpGet, new JSONResponseHandler());
}
return json;
Classes
For this FRQ, I had to create the HiddenWord class, which is essential to a word-guessing game in which the player tries to guess a concealed word. I had to create a coherent class structure that contained both data and logic for this project. The class design was extremely impotant for the entire project because it represented the POJO which works which both the JPA repository and the Controller.
package com.nighthawk.spring_portfolio.mvc.chathistory;
import java.sql.Date;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import org.json.simple.JSONObject;
https://github.com/entity
public class Chat {
// automatic unique identifier for Person record
@id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
public Long getId() {
return id;
}
private String chatMessage;
private String chatReponse;
private Date timestamp;
private Long personId;
public Long getPersonId() {
return personId;
}
public String getChatMessage() {
return chatMessage;
}
public String getChatReponse() {
return chatReponse;
}
public Date getTimestamp() {
return timestamp;
}
public Chat(String chatMessage, String chatReponse, Date timestamp, Long personId) {
super();
this.chatMessage = chatMessage;
this.chatReponse = chatReponse;
this.timestamp = timestamp;
this.personId = personId;
}
public Chat() {
}
// todo add person id foreign key
@Override
public String toString() {
JSONObject obj = new JSONObject();
obj.put(idStr, id);
obj.put(chat_message, chatMessage);
obj.put(chat_response, chatReponse);
obj.put(timestamp_str, timestamp.toString());
obj.put(person_id, personId);
return obj.toString();
}
public JSONObject toJSON() {
JSONObject obj = new JSONObject();
obj.put(idStr, id);
obj.put(chat_message, chatMessage);
obj.put(chat_response, chatReponse);
obj.put(timestamp_str, timestamp.toString());
obj.put(person_id, personId);
return obj;
}
private static final String chat_message="chat_message";
private static final String idStr="id";
private static final String chat_response="chat_response";
private static final String timestamp_str="timestamp";
private static final String person_id="person_id";
2D arrays
The goal of the task was to have me come up with an effective representation and manipulation technique for a sparse array, which is a two-dimensional array where the majority of its members are zeros. The major goals were to change the array by eliminating columns and obtain certain element values from this sparse structure while preserving the array's structural integrity.
The Chat class serves as a representation of a chat message entity within a Spring Boot application. Annotated with https://github.com/entity, it indicates that instances of this class can be mapped to a database table. The class encapsulates various attributes of a chat message, such as its unique identifier (id), the actual message content (chatMessage), the response to the message (chatResponse), the timestamp of the message (timestamp), and the associated person's identifier (personId). The inclusion of JPA annotations like @id and @GeneratedValue ensures proper database mapping, with automatic generation of unique IDs for new records. The class also provides methods to convert instances to JSON format, facilitating data transfer and persistence tasks. Following the POJO pattern, the Chat class is a simple Java object focused solely on data representation, making it suitable for various data manipulation tasks within the application.
@GetMapping("/chat/history/all")
// get all chats and return as a two dimensional string array
public String[][] getAllChats() {
// get all chats
List chats = chatJpaRepository.findAll();
// initialize the two dimensional array
// array size is same as number of chats in the list above
// the other dimension of the two dimensional array is fixed at 4 to hold:
// person id; chat message; chat response; and time stamp
String[][] allChats = new String[chats.size()][4];
// initialize the counter
int counter = 0;
// iterate over the list of chats
for (Chat c : chats) {
// retrieve values
long personId = c.getPersonId();
String chatMsg = c.getChatMessage();
String response = c.getChatReponse();
Date timeStamp = c.getTimestamp();
// set values in the two dimensional array
// counter is incremented at the end
allChats[counter][0] = String.valueOf(personId);
allChats[counter][1] = chatMsg;
allChats[counter][2] = response;
allChats[counter][3] = timeStamp.toString();
// increment counter
counter++;
}
// return the chats for all users
return allChats;
}
method and control structures.
My job in this project was to create a database which could both delete chat history as well as get chat history. I had to employ a variety of techniques and control structures to create a flexible and dynamic framework for this task. This required developing techniques that made sure that loops would not run indefinitely if the specific utterance is not found so that caused me to utilize different conditional and complex statements.
@DeleteMapping("/chat/history/clear")
public String clearCharHistory() {
List chats = chatJpaRepository.deleteByPersonId(1l);
JSONObject obj = new JSONObject();
JSONArray list = new JSONArray();
for (Chat c : chats) {
System.out.println(c.getId());
list.add(c.toJSON());
}
obj.put("chats", list);
return obj.toJSONString();
}
@GetMapping("/chat/history")
public String getAllChats() {
List<Chat> chats = chatJpaRepository.findByPersonId(1l);
JSONObject obj = new JSONObject();
JSONArray list = new JSONArray();
for (Chat c : chats) {
System.out.println(c.getId());
list.add(c.toJSON());
}
obj.put("chats", list);
return obj.toString();
}
There are two controller methods in a RESTful API for managing chat history. The clearCharHistory() method, triggered by a DELETE request to "/chat/history/clear", utilizes the deleteByPersonId() method of the chatJpaRepository to remove all chats associated with a person ID of 1. The method then constructs a JSON response containing details of the deleted chats. Similarly, the getAllChats() method, triggered by a GET request to "/chat/history", retrieves all chats associated with the same person ID from the database using the findByPersonId() method. It constructs a JSON response containing details of these chats. Both methods iterate through the retrieved or deleted chats, printing their IDs to the console and adding their JSON representations to a JSONArray, which is then added to a JSONObject as part of the response.
Arrays
In order to solve this issue, a number of array-related tasks had to be completed. In particular, summing elements and determining if sums in a two-dimensional array context are unique required attention. Arrays are shown through how it deals with JSON objects and arrays, which are often used to represent structured data received from APIs. This Java code snippet is a part of an application that communicates with a server via HTTP requests to retrieve and process JSON data. It includes methods for sending HTTP GET and POST requests (sendHttpGet and sendHttpPost). The sendHttpGet method sends an HTTP GET request to a specified URL and returns the JSON response received from the server. The response is then parsed to extract relevant information, such as the first_id and data array containing messages from a specific thread. The code iterates through the data array to find and extract the text value of messages sent by an assistant. These messages are appended to a StringBuilder named chatResponse, which holds the response generated by the model for the given thread.
Classes
For this FRQ, I had to create the HiddenWord class, which is essential to a word-guessing game in which the player tries to guess a concealed word. I had to create a coherent class structure that contained both data and logic for this project. The class design was extremely impotant for the entire project because it represented the POJO which works which both the JPA repository and the Controller.
2D arrays
The goal of the task was to have me come up with an effective representation and manipulation technique for a sparse array, which is a two-dimensional array where the majority of its members are zeros. The major goals were to change the array by eliminating columns and obtain certain element values from this sparse structure while preserving the array's structural integrity.
The Chat class serves as a representation of a chat message entity within a Spring Boot application. Annotated with https://github.com/entity, it indicates that instances of this class can be mapped to a database table. The class encapsulates various attributes of a chat message, such as its unique identifier (id), the actual message content (chatMessage), the response to the message (chatResponse), the timestamp of the message (timestamp), and the associated person's identifier (personId). The inclusion of JPA annotations like @id and @GeneratedValue ensures proper database mapping, with automatic generation of unique IDs for new records. The class also provides methods to convert instances to JSON format, facilitating data transfer and persistence tasks. Following the POJO pattern, the Chat class is a simple Java object focused solely on data representation, making it suitable for various data manipulation tasks within the application.
method and control structures.
My job in this project was to create a database which could both delete chat history as well as get chat history. I had to employ a variety of techniques and control structures to create a flexible and dynamic framework for this task. This required developing techniques that made sure that loops would not run indefinitely if the specific utterance is not found so that caused me to utilize different conditional and complex statements.
There are two controller methods in a RESTful API for managing chat history. The clearCharHistory() method, triggered by a DELETE request to "/chat/history/clear", utilizes the deleteByPersonId() method of the chatJpaRepository to remove all chats associated with a person ID of 1. The method then constructs a JSON response containing details of the deleted chats. Similarly, the getAllChats() method, triggered by a GET request to "/chat/history", retrieves all chats associated with the same person ID from the database using the findByPersonId() method. It constructs a JSON response containing details of these chats. Both methods iterate through the retrieved or deleted chats, printing their IDs to the console and adding their JSON representations to a JSONArray, which is then added to a JSONObject as part of the response.