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

Updated CloudSQL samples. #989

Merged
merged 4 commits into from
Jan 12, 2018
Merged
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
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Postgre SQL sample for Google App Engine J8

<a href="https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/java-docs-samples&page=editor&open_in_editor=appengine-java8/postgres/README.md">
<a href="https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/java-docs-samples&page=editor&open_in_editor=appengine-java8/cloudsql-postgres/README.md">
<img alt="Open in Cloud Shell" src ="http://gstatic.com/cloudssh/images/open-btn.png"></a>

This sample demonstrates how to use [PostgreSql](https://cloud.google.com/sql/) on Google App
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@
<!-- [END properties] -->

<dependencies>
<!-- Parent POM defines ${appengine.sdk.version} (updates frequently). -->
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-1.0-sdk</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,8 @@
package com.example.appengine.postgresql;

import com.google.common.base.Stopwatch;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
Expand All @@ -31,7 +27,6 @@
import java.sql.Timestamp;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
Expand All @@ -42,7 +37,7 @@
@SuppressWarnings("serial")
// With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required.
@WebServlet(name = "PostgreSQL",
description = "PostgreSQL: Write low order IP address to PostgreSQL",
description = "PostgreSQL: Write timestamps of visitors to PostgreSQL",
urlPatterns = "/postgresql")
public class PostgreSqlServlet extends HttpServlet {

Expand All @@ -52,11 +47,11 @@ public class PostgreSqlServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException,
ServletException {

final String createTableSql = "CREATE TABLE IF NOT EXISTS visits ( visit_id SERIAL NOT NULL, "
+ "user_ip VARCHAR(46) NOT NULL, ts timestamp NOT NULL, "
final String createTableSql = "CREATE TABLE IF NOT EXISTS visits ( "
+ "visit_id SERIAL NOT NULL, ts timestamp NOT NULL, "
+ "PRIMARY KEY (visit_id) );";
final String createVisitSql = "INSERT INTO visits (user_ip, ts) VALUES (?, ?);";
final String selectSql = "SELECT user_ip, ts FROM visits ORDER BY ts DESC "
final String createVisitSql = "INSERT INTO visits (ts) VALUES (?);";
final String selectSql = "SELECT ts FROM visits ORDER BY ts DESC "
+ "LIMIT 10;";

String path = req.getRequestURI();
Expand All @@ -67,55 +62,34 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOExc
PrintWriter out = resp.getWriter();
resp.setContentType("text/plain");

// store only the first two octets of a users ip address
String userIp = req.getRemoteAddr();
InetAddress address = InetAddress.getByName(userIp);
if (address instanceof Inet6Address) {
// nest indexOf calls to find the second occurrence of a character in a string
// an alternative is to use Apache Commons Lang: StringUtils.ordinalIndexOf()
userIp = userIp.substring(0, userIp.indexOf(":", userIp.indexOf(":") + 1)) + ":*:*:*:*:*:*";
} else if (address instanceof Inet4Address) {
userIp = userIp.substring(0, userIp.indexOf(".", userIp.indexOf(".") + 1)) + ".*.*";
}

Stopwatch stopwatch = Stopwatch.createStarted();
try (PreparedStatement statementCreateVisit = conn.prepareStatement(createVisitSql)) {
conn.createStatement().executeUpdate(createTableSql);
statementCreateVisit.setString(1, userIp);
statementCreateVisit.setTimestamp(2, new Timestamp(new Date().getTime()));
statementCreateVisit.setTimestamp(1, new Timestamp(new Date().getTime()));
statementCreateVisit.executeUpdate();

try (ResultSet rs = conn.prepareStatement(selectSql).executeQuery()) {
stopwatch.stop();
out.print("Last 10 visits:\n");
while (rs.next()) {
String savedIp = rs.getString("user_ip");
String timeStamp = rs.getString("ts");
out.println("Time: " + timeStamp + " Addr: " + savedIp);
out.println("Visited at time: " + timeStamp);
}
out.println("Elapsed: " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
}
} catch (SQLException e) {
throw new ServletException("SQL error", e);
}
out.println("Query time (ms):" + stopwatch.elapsed(TimeUnit.MILLISECONDS));
}

@Override
public void init() throws ServletException {
String url = System.getProperty("postgresql");
log("connecting to: " + url);
try {
String url = System.getProperty("postgresql");
log("connecting to: " + url);
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(url);
} catch (ClassNotFoundException e) {
throw new ServletException("Error loading JDBC Driver", e);
} catch (SQLException e) {
throw new ServletException("Unable to connect to PostGre", e);
}

} finally {
// Nothing really to do here.
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
throw new ServletException("Unable to connect to PostgreSQL", e);
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions appengine-java8/cloudsql/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@
<!-- [END properties] -->

<dependencies>
<!-- Parent POM defines ${appengine.sdk.version} (updates frequently). -->
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-1.0-sdk</artifactId>
Expand Down Expand Up @@ -78,8 +77,9 @@
</dependency>
<dependency>
<groupId>com.google.cloud.sql</groupId>
<artifactId>mysql-socket-factory</artifactId> <!-- mysql-socket-factory-connector-j-6 if using 6.x.x -->
<version>1.0.4</version>
<!-- If using MySQL 6.x driver, use mysql-socket-factory-connector-j-6 instead -->
<artifactId>mysql-socket-factory</artifactId>
<version>1.0.5</version>
</dependency>
<!-- [END dependencies] -->
</dependencies>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,20 +44,22 @@
// [START example]
@SuppressWarnings("serial")
// With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required.
@WebServlet(name = "CloudSQL", description = "CloudSQL: Write low order IP address to Cloud SQL",
@WebServlet(name = "CloudSQL",
description = "CloudSQL: Write timestamps of visitors to Cloud SQL",
urlPatterns = "/cloudsql")
public class CloudSqlServlet extends HttpServlet {
Connection conn;

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException,
ServletException {
final String createTableSql = "CREATE TABLE IF NOT EXISTS visits ( visit_id INT NOT NULL "
+ "AUTO_INCREMENT, user_ip VARCHAR(46) NOT NULL, timestamp DATETIME NOT NULL, "
+ "PRIMARY KEY (visit_id) )";
final String createVisitSql = "INSERT INTO visits (user_ip, timestamp) VALUES (?, ?)";
final String selectSql = "SELECT user_ip, timestamp FROM visits ORDER BY timestamp DESC "
+ "LIMIT 10";

final String createTableSql = "CREATE TABLE IF NOT EXISTS visits ( "
+ "visit_id SERIAL NOT NULL, ts timestamp NOT NULL, "
+ "PRIMARY KEY (visit_id) );";
final String createVisitSql = "INSERT INTO visits (ts) VALUES (?);";
final String selectSql = "SELECT ts FROM visits ORDER BY ts DESC "
+ "LIMIT 10;";

String path = req.getRequestURI();
if (path.startsWith("/favicon.ico")) {
Expand All @@ -67,37 +69,24 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOExc
PrintWriter out = resp.getWriter();
resp.setContentType("text/plain");

// store only the first two octets of a users ip address
String userIp = req.getRemoteAddr();
InetAddress address = InetAddress.getByName(userIp);
if (address instanceof Inet6Address) {
// nest indexOf calls to find the second occurrence of a character in a string
// an alternative is to use Apache Commons Lang: StringUtils.ordinalIndexOf()
userIp = userIp.substring(0, userIp.indexOf(":", userIp.indexOf(":") + 1)) + ":*:*:*:*:*:*";
} else if (address instanceof Inet4Address) {
userIp = userIp.substring(0, userIp.indexOf(".", userIp.indexOf(".") + 1)) + ".*.*";
}

Stopwatch stopwatch = Stopwatch.createStarted();
try (PreparedStatement statementCreateVisit = conn.prepareStatement(createVisitSql)) {
conn.createStatement().executeUpdate(createTableSql);
statementCreateVisit.setString(1, userIp);
statementCreateVisit.setTimestamp(2, new Timestamp(new Date().getTime()));
statementCreateVisit.setTimestamp(1, new Timestamp(new Date().getTime()));
statementCreateVisit.executeUpdate();

try (ResultSet rs = conn.prepareStatement(selectSql).executeQuery()) {
stopwatch.stop();
out.print("Last 10 visits:\n");
while (rs.next()) {
String savedIp = rs.getString("user_ip");
String timeStamp = rs.getString("timestamp");
out.print("Time: " + timeStamp + " Addr: " + savedIp + "\n");
String timeStamp = rs.getString("ts");
out.println("Visited at time: " + timeStamp);
}
out.println("Elapsed: " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
}
} catch (SQLException e) {
throw new ServletException("SQL error", e);
}
out.println("Query time (ms):" + stopwatch.elapsed(TimeUnit.MILLISECONDS));
}

@Override
Expand Down
2 changes: 1 addition & 1 deletion appengine-java8/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
<module>appidentity</module>
<module>bigtable</module>
<module>cloudsql</module>
<module>cloudsql-postgres</module>
<module>datastore</module>
<module>datastore-indexes</module>
<module>datastore-indexes-exploding</module>
Expand All @@ -62,7 +63,6 @@
<module>metadata</module>
<module>multitenancy</module>
<module>oauth2</module>
<module>postgres</module>
<module>pubsub</module>
<module>requests</module>
<module>remote-client</module>
Expand Down