Skip to content

Commit

Permalink
Merge pull request #157 from GoogleCloudPlatform/cloudsql
Browse files Browse the repository at this point in the history
Add cloudsql gen1 sample for app engine
  • Loading branch information
lesv committed Apr 11, 2016
2 parents f4d5d66 + cc0c034 commit db10bd9
Show file tree
Hide file tree
Showing 6 changed files with 250 additions and 0 deletions.
12 changes: 12 additions & 0 deletions appengine/cloudsql/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Cloud SQL sample for Google App Enginge
This sample demonstrates how to use [Cloud SQL](https://cloud.google.com/sql/) on Google App Engine
## Setup
Before you can run or deploy the sample, you will need to create a [Cloud SQL instance](https://cloud.google.com/sql/docs/create-instance)
1. Create a new user and database for the application. The easiest way to do this is via the [Google Developers Console](https://console.developers.google.com/project/_/sql/instances/example-instance2/access-control/users). Alternatively, you can use MySQL tools such as the command line client or workbench.
## Running locally
1. You will need to be running a local instance of MySQL.
1. Update the connection string in ``appengine-web.xml`` with your local MySQL instance values.
$ mvn clean appengine:devserver
## Deploying
1. Update the connection string in ``appengine-web.xml`` with your Cloud SQL instance values.
$ mvn clean appengine:update
67 changes: 67 additions & 0 deletions appengine/cloudsql/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<!--
Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<groupId>com.example.appengine</groupId>
<artifactId>appengine-cloudsql</artifactId>

<parent>
<artifactId>doc-samples</artifactId>
<groupId>com.google.cloud</groupId>
<version>1.0.0</version>
<relativePath>../..</relativePath>
</parent>

<dependencies>
<dependency>
<groupId>com.google.cloud.sql</groupId>
<artifactId>mysql-socket-factory</artifactId>
<version>1.0.0-beta1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<!-- [START dependencies] -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- Parent POM defines ${appengine.sdk.version} (updates frequently). -->
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-1.0-sdk</artifactId>
</dependency>
<!-- [END dependencies] -->
</dependencies>
<build>
<!-- for hot reload of the web application -->
<outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes</outputDirectory>
<plugins>
<plugin>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-maven-plugin</artifactId>
<version>${appengine.sdk.version}</version>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/**
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.appengine.cloudsql;

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;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// [START example]
@SuppressWarnings("serial")
public class CloudSqlServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException,
ServletException {
String path = req.getRequestURI();
if (path.startsWith("/favicon.ico")) {
return; // ignore the request for favicon.ico
}
// 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)) + ".*.*";
}

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";
PrintWriter out = resp.getWriter();
resp.setContentType("text/plain");
String url;
if (System
.getProperty("com.google.appengine.runtime.version").startsWith("Google App Engine/")) {
// Check the System properties to determine if we are running on appengine or not
// Google App Engine sets a few system properties that will reliably be present on a remote
// instance.
url = System.getProperty("ae-cloudsql.cloudsql-database-url");
try {
// Load the class that provides the new "jdbc:google:mysql://" prefix.
Class.forName("com.mysql.jdbc.GoogleDriver");
} catch (ClassNotFoundException e) {
throw new ServletException("Error loading Google JDBC Driver", e);
}
} else {
// Set the url with the local MySQL database connection url when running locally
url = System.getProperty("ae-cloudsql.local-database-url");
}
try (Connection conn = DriverManager.getConnection(url);
PreparedStatement statementCreateVisit = conn.prepareStatement(createVisitSql)) {
conn.createStatement().executeUpdate(createTableSql);
statementCreateVisit.setString(1, userIp);
statementCreateVisit.setTimestamp(2, new Timestamp(new Date().getTime()));
statementCreateVisit.executeUpdate();

try (ResultSet rs = conn.prepareStatement(selectSql).executeQuery()) {
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");
}
}
} catch (SQLException e) {
throw new ServletException("SQL error", e);
}
}
}
// [END example]
25 changes: 25 additions & 0 deletions appengine/cloudsql/src/main/webapp/WEB-INF/appengine-web.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- [START_EXCLUDE] -->
<!--
Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- [END_EXCLUDE] -->
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<application>YOUR-PROJECT-ID</application>
<version>YOUR-VERSION-ID</version>
<threadsafe>true</threadsafe>
<use-google-connector-j>true</use-google-connector-j>
<system-properties>
<property name="ae-cloudsql.cloudsql-database-url" value="jdbc:google:mysql://YOUR-PROJECT-NAME:YOUR-CLOUDSQL-INSTANCE-NAME/DATABASE-NAME?user=USERNAME&amp;password=PASSWORD" />
<property name="ae-cloudsql.local-database-url" value="jdbc:mysql://localhost/DATABASE-NAME?user=USERNAME&amp;PASSWORD=password&amp;useSSL=false" />
</system-properties>
</appengine-web-app>
28 changes: 28 additions & 0 deletions appengine/cloudsql/src/main/webapp/WEB-INF/web.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- [START_EXCLUDE] -->
<!--
Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- [END_EXCLUDE] -->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>cloudsql</servlet-name>
<servlet-class>com.example.appengine.cloudsql.CloudSqlServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>cloudsql</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
14 changes: 14 additions & 0 deletions appengine/helloworld/src/main/webapp/WEB-INF/appengine-web.xml
Original file line number Diff line number Diff line change
@@ -1,4 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- [START_EXCLUDE] -->
<!--
Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- [END_EXCLUDE] -->
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<application>YOUR-PROJECT-ID</application>
<version>YOUR-VERSION-ID</version>
Expand Down

0 comments on commit db10bd9

Please sign in to comment.