Skip to content

Commit

Permalink
Merge pull request #256 from GoogleCloudPlatform/cloudsql2
Browse files Browse the repository at this point in the history
Add cloudsql gen2 managed vms sample
  • Loading branch information
Shun Fan committed Jun 8, 2016
2 parents 205b50e + 067a1f2 commit 0e22377
Show file tree
Hide file tree
Showing 6 changed files with 240 additions and 0 deletions.
1 change: 1 addition & 0 deletions managed_vms/cloudsql/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/bin/
30 changes: 30 additions & 0 deletions managed_vms/cloudsql/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Cloud SQL sample for Google Managed VMs
This sample demonstrates how to use [Cloud SQL](https://cloud.google.com/sql/) on Google Managed VMs.

## Setup
Before you can run or deploy the sample, you will need to do the following:

1. Create a [Second Generation Cloud SQL](https://cloud.google.com/sql/docs/create-instance) instance. You can do this from the [Cloud Console](https://console.developers.google.com) or via the [Cloud SDK](https://cloud.google.com/sdk). To create it via the SDK use the following command:

$ gcloud sql instances create YOUR_INSTANCE_NAME \
--activation-policy=ALWAYS \
--tier=db-n1-standard-1

1. Set the root password on your Cloud SQL instance:

$ gcloud sql instances set-root-password YOUR_INSTANCE_NAME --password YOUR_INSTANCE_ROOT_PASSWORD

1. Use the MySQL command line tools (or a management tool of your choice) to create a [new user](https://cloud.google.com/sql/docs/create-user) and [database](https://cloud.google.com/sql/docs/create-database) for your application:

$ mysql -h [IP Address of database] -u root -p
mysql> create database YOUR_DATABASE;
mysql> create user 'YOUR_USER'@'%' identified by 'PASSWORD';
mysql> grant all on YOUR_DATABASE.* to 'YOUR_USER'@'%';

1. Set the connection string environment variable in src/main/appengine/app.yaml

## Running locally
$ mvn clean jetty:run

## Deploying
$ mvn clean gcloud:deploy
85 changes: 85 additions & 0 deletions managed_vms/cloudsql/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.managedvms</groupId>
<artifactId>managed-vms-cloudsql</artifactId>

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

<dependencies>
<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> <!-- http://dev.mysql.com/doc/connector-j/en/ -->
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>com.google.cloud.sql</groupId>
<artifactId>mysql-socket-factory</artifactId>
<version>1.0.0-beta1</version>
</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>gcloud-maven-plugin</artifactId>
<version>${maven.plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.3.7.v20160115</version>
</plugin>
</plugins>
</build>
</project>
27 changes: 27 additions & 0 deletions managed_vms/cloudsql/src/main/appengine/app.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# 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.

runtime: java
vm: true

handlers:
- url: /.*
script: this field is required, but ignored
secure: always

# [START env_variables]
env_variables:
SQL_REMOTE_URL: jdbc:mysql://google/YOUR-DB-NAME?cloudSqlInstance=YOUR-INSTANCE-NAME&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=USERNAME&password=PASSWORD
SQL_LOCAL_URL: jdbc:mysql://localhost/YOUR-DB-NAME?user=YOUR-USERNAME&password=PASSWORD&useSSL=false
# [END env_variables]
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/**
* 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.managedvms.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.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// [START example]
@SuppressWarnings("serial")
@WebServlet(name = "cloudsql", value = "")
public class CloudSqlServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException,
ServletException {
// 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");
// Detect if running remotely or locally and select correct connection url
String url;
if (System.getenv().containsKey("GAE_MODULE_INSTANCE")) {
url = System.getenv("SQL_REMOTE_URL");
} else {
url = System.getenv("SQL_LOCAL_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]
2 changes: 2 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
<project.oauth.version>1.19.0</project.oauth.version>
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.plugin.version>2.0.9.111.v20160525</maven.plugin.version>
</properties>

<prerequisites>
Expand Down Expand Up @@ -82,6 +83,7 @@
<module>logging</module>
<module>managed_vms/analytics</module>
<module>managed_vms/async-rest</module>
<module>managed_vms/cloudsql</module>
<module>managed_vms/cloudstorage</module>
<module>managed_vms/cron</module>
<module>managed_vms/datastore</module>
Expand Down

0 comments on commit 0e22377

Please sign in to comment.