Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial Database files created. Schema | Tables. Functionality not finished: DO NOT MERGE #18

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ hs_err_pid*
.*DS_Store

# IntelliJ, Eclipse and Maven files
/BIN/
/bin/
/target/
/.idea/
.project
*.iml
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ limitations under the License.
</properties>

<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-language</artifactId>
<version>1.55.0</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
Expand Down
11 changes: 11 additions & 0 deletions src/main/java/com/google/codeu/data/Datastore.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
Expand All @@ -42,8 +43,18 @@ public void storeMessage(Message message) {
messageEntity.setProperty("user", message.getUser());
messageEntity.setProperty("text", message.getText());
messageEntity.setProperty("timestamp", message.getTimestamp());
System.out.println("Data store testing sentiment: " + message.getSentiment());
messageEntity.setProperty("sentiment", message.getSentiment());

datastore.put(messageEntity);
System.out.println("Testing message entity: " + messageEntity);
}

/** Inserted Code * */
public int getTotalMessageCount() {
Query query = new Query("Message");
PreparedQuery results = datastore.prepare(query);
return results.countEntities(FetchOptions.Builder.withLimit(1000));
}

/**
Expand Down
15 changes: 15 additions & 0 deletions src/main/java/com/google/codeu/data/Message.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public class Message {
private String user;
private String text;
private long timestamp;
private float sentiment = -2; // default value to indicate not assigned

/**
* Constructs a new {@link Message} posted by {@code user} with {@code text} content. Generates a
Expand All @@ -34,6 +35,16 @@ public Message(String user, String text) {
this(UUID.randomUUID(), user, text, System.currentTimeMillis());
}

public Message(String user, String text, float sentiment) {
this.id = UUID.randomUUID();
this.user = user;
this.text = text;
this.timestamp = System.currentTimeMillis();
this.sentiment = sentiment;

System.out.println("Message data test item 'this': " + this);
}

public Message(UUID id, String user, String text, long timestamp) {
this.id = id;
this.user = user;
Expand All @@ -56,4 +67,8 @@ public String getText() {
public long getTimestamp() {
return timestamp;
}

public float getSentiment() {
return sentiment;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// Import required packages

import java.sql.*;

public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";

// Database credentials
static final String USER = "username";
static final String PASS = "password";

public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

// Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");

// Creating a database schema
Statement sta = con.createStatement();
int count = sta.executeUpdate("CREATE SCHEMA T_Overflow");
System.out.println("Schema created.");
sta.close();

// Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();

// need to create array of postID to keep track of answered questions
String sql =
"CREATE TABLE PROFILE "
+ "(profileId INTEGER not NULL, "
+ " first VARCHAR, "
+ " last VARCHAR, "
+ " isCPA BIT not NULL, "
+ " PRIMARY KEY ( profileId ))";

stmt.executeUpdate(sql);
System.out.println("Created table in given database...");

// Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();

// need to create array of responses, per postId
String sql =
"CREATE TABLE POST "
+ "(postId INTEGER not NULL UNIQUE, "
+ " memberId INTEGER not NULL, "
+ " header VARCHAR(255), "
+
// " response VARCHAR(255), " +
" pointTotal INTEGER, "
+ " FOREIGN KEY ( memberId ) REFERENCES PROFILE.profileId"
+ " PRIMARY KEY ( postId ))";

stmt.executeUpdate(sql);
System.out.println("Created table in given database...");

} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// finally block used to close resources
try {
if (stmt != null) conn.close();
} catch (SQLException se) {
} // do nothing
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
} // end finally try
} // end try
System.out.println("Goodbye!");
} // end main
} // end JDBCExample
23 changes: 22 additions & 1 deletion src/main/java/com/google/codeu/servlets/MessageServlet.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.cloud.language.v1.Document;
import com.google.cloud.language.v1.Document.Type;
import com.google.cloud.language.v1.LanguageServiceClient;
import com.google.cloud.language.v1.Sentiment;
import com.google.codeu.data.Datastore;
import com.google.codeu.data.Message;
import com.google.gson.Gson;
Expand Down Expand Up @@ -65,6 +69,18 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) thro
response.getWriter().println(json);
}

private float getSentimentScore(String text) throws IOException {
Document doc = Document.newBuilder().setContent(text).setType(Type.PLAIN_TEXT).build();

LanguageServiceClient languageService = LanguageServiceClient.create();
Sentiment sentiment = languageService.analyzeSentiment(doc).getDocumentSentiment();
languageService.close();

// System.out.println(sentiment);

return sentiment.getScore();
}

/** Stores a new {@link Message}. */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
Expand All @@ -78,7 +94,12 @@ public void doPost(HttpServletRequest request, HttpServletResponse response) thr
String user = userService.getCurrentUser().getEmail();
String text = Jsoup.clean(request.getParameter("text"), Whitelist.none());

Message message = new Message(user, text);
float sentimentScore = getSentimentScore(text);
// System.out.println(sentimentScore);

Message message = new Message(user, text, sentimentScore);
System.out.println("Message testing sentiment: " + message.getSentiment());
// Message message = new Message(user, text);
datastore.storeMessage(message);

response.sendRedirect("/user-page.html?user=" + user);
Expand Down
34 changes: 34 additions & 0 deletions src/main/java/com/google/codeu/servlets/StatsPageServlet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.google.codeu.servlets;

import com.google.codeu.data.Datastore;
import com.google.gson.JsonObject;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Responds with a hard-coded message for testing purposes. */
@WebServlet("/stats")
public class StatsPageServlet extends HttpServlet {

private Datastore datastore;

@Override
public void init() {
datastore = new Datastore();
}

/** Responds with site statistics in JSON. */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

response.setContentType("application/json");

int messageCount = datastore.getTotalMessageCount();

JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("messageCount", messageCount);
response.getOutputStream().println(jsonObject.toString());
}
}
13 changes: 13 additions & 0 deletions src/main/webapp/css/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,16 @@ nav li {
display: inline-block;
margin-right: 10px
}

#card-header{
/*
margin-left: 1 px;
margin-right: 1 px;
/*width: 8em;*/
}

#card-inner-p{
}

#card-footer{
}
31 changes: 24 additions & 7 deletions src/main/webapp/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,36 @@
<meta charset="UTF-8">
<title>CodeU 2019 Starter Project</title>
<link rel="stylesheet" href="/css/main.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="/js/navigation-loader.js"></script>
</head>
<body onload="addLoginOrLogoutLinkToNavigation();">
<nav>
<ul id="navigation">
<li><a href="/">Home</a></li>
<a href="/" class="btn btn-link">Home</a>
<!--<li><a href="/">Home</a></li>-->
</ul>
</nav>
<h1>CodeU Starter Project</h1>
<p>This is the CodeU starter project. Click the links above to login and visit your page.
You can post messages on your page, and you can visit other user pages if you have
their URL.</p>
<p>This is your code now! Feel free to make changes, and don't be afraid to get creative!
You could start by modifying this page to tell the world more about your team.</p>
<div class="w3-card-4">

<header class="w3-container w3-blue" id="card-header">
<h1>CodeU Starter Project</h1>
</header>

<div class="w3-container" id="card-inner-p">
<p>This is the CodeU starter project. Click the links above to login and visit your page.
You can post messages on your page, and you can visit other user pages if you have
their URL.</p>
<hr />
<p>This is your code now! Feel free to make changes, and don't be afraid to get creative!
You could start by modifying this page to tell the world more about your team.</p>
</div>

<footer class="w3-container w3-blue" id="card-footer">
<h5><i>Team Code Busters</i></h5>
</footer>

</div>
</body>
</html>
4 changes: 3 additions & 1 deletion src/main/webapp/js/user-page-loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ function fetchMessages() {
messagesContainer.innerHTML = '';
}
messages.forEach((message) => {
console.log(message);
const messageDiv = buildMessageDiv(message);
messagesContainer.appendChild(messageDiv);
});
Expand All @@ -75,8 +76,9 @@ function fetchMessages() {
function buildMessageDiv(message) {
const headerDiv = document.createElement('div');
headerDiv.classList.add('message-header');
console.log("Test within buildMessageDive. Message contents: " + message);
headerDiv.appendChild(document.createTextNode(
message.user + ' - ' + new Date(message.timestamp)));
message.user + ' - ' + new Date(message.timestamp) + ' [' + message.sentiment + ']'));

const bodyDiv = document.createElement('div');
bodyDiv.classList.add('message-body');
Expand Down
41 changes: 41 additions & 0 deletions src/main/webapp/stats.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<!DOCTYPE html>
<html>
<head>
<title>Stats</title>
<link rel="stylesheet" href="/css/main.css">

<script>
// Fetch stats and display them in the page.
function fetchStats(){
const url = '/stats';
fetch(url).then((response) => {
return response.json();
}).then((stats) => {
const statsContainer = document.getElementById('stats-container');
statsContainer.innerHTML = '';

const messageCountElement = buildStatElement('Message count: ' + stats.messageCount);
statsContainer.appendChild(messageCountElement);
});
}

function buildStatElement(statString){
const statElement = document.createElement('p');
statElement.appendChild(document.createTextNode(statString));
return statElement;
}

// Fetch data and populate the UI of the page.
function buildUI(){
fetchStats();
}
</script>
</head>
<body onload="buildUI()">
<div id="content">
<h1>Site Statistics</h1>
<hr/>
<div id="stats-container">Loading...</div>
</div>
</body>
</html>
6 changes: 3 additions & 3 deletions src/main/webapp/user-page.html
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,17 @@
<body onload="buildUI();">
<nav>
<ul id="navigation">
<li><a href="/">Home</a></li>
<li><a href="/" class="btn btn-link">Home</a></li>
</ul>
</nav>
<h1 id="page-title">User Page</h1>

<form id="message-form" action="/messages" method="POST" class="hidden">
Enter a new message:
<br/>
<textarea name="text" id="message-input"></textarea>
<textarea name="text" id="message-input" class="form-control" rows="3"></textarea>
<br/>
<input type="submit" value="Submit">
<input class="btn btn-primary" type="submit" value="Submit">
</form>
<hr/>

Expand Down