Skip to content

Sql stuff #736

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

Merged
merged 3 commits into from
Jun 29, 2017
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
46 changes: 29 additions & 17 deletions appengine-java8/cloudsql/README.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,36 @@
# Cloud SQL sample for Google App Engine
This sample demonstrates how to use [Cloud SQL](https://cloud.google.com/sql/) on Google App Engine

This sample demonstrates how to use [Cloud SQL](https://cloud.google.com/cloudsql/) on Google App
Engine standard Java 8

## 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.cloud.google.com/sql/instances). Alternatively, you can use MySQL tools such as the command line client or workbench.
2. Change the root password (under Access Control) and / or create a new user / password.
3. Create a Database (under Databases) (or use MySQL with `gcloud beta sql connect <instance> --user=root`)
4. Note the **Instance connection name** under Overview > properties
(It will look like project:instance for 1st Generation or project:region:zone for 2nd Generation)
* If you haven't already, Download and initialize the [Cloud SDK](https://cloud.google.com/sdk/)

`gcloud init`

* If you haven't already, Create an App Engine app within the current Google Cloud Project

`gcloud app create`

* If you haven't already, Setup
[Application Default Credentials](https://developers.google.com/identity/protocols/application-default-credentials)

`gcloud auth application-default login`


* [Create an instance](https://cloud.google.com/sql/docs/mysql/create-instance)

* [Create a Database](https://cloud.google.com/sql/docs/mysql/create-manage-databases)

or
* [Create a user](https://cloud.google.com/sql/docs/mysql/create-manage-users)

* Note the **Instance connection name** under Overview > properties

## Running locally

```bash
gcloud sql instances describe <instance> | grep connectionName
$ mvn clean appengine:run -DINSTANCE_CONNECTION_NAME=instanceConnectionName -Duser=root -Dpassword=myPassowrd -Ddatabase=myDatabase
```

## Deploying
Expand All @@ -24,12 +40,8 @@ $ mvn clean appengine:deploy -DINSTANCE_CONNECTION_NAME=instanceConnectionName -
-Dpassword=myPassword -Ddatabase=myDatabase
```

Or you can update the properties in `pom.xml`

## Running locally
## Cleaning up

* [Delete your Instance](https://cloud.google.com/sql/docs/mysql/delete-instance)

```bash
$ mvn clean appengine:run -DINSTANCE_CONNECTION_NAME=instanceConnectionName -Duser=root -Dpassword=myPassowrd -Ddatabase=myDatabase
```
Note - you must use a local mysql instance for the 1st Generation instance and change the local Url
in `src/main/webapp/WEB-INF/appengine-web.xml` to use your local server.
2 changes: 1 addition & 1 deletion appengine-java8/cloudsql/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@
<dependency>
<groupId>com.google.cloud.sql</groupId>
<artifactId>mysql-socket-factory</artifactId> <!-- mysql-socket-factory-connector-j-6 -->
<version>1.0.2</version>
<version>1.0.3</version>
</dependency>
<!-- [END dependencies] -->
</dependencies>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package com.example.appengine.cloudsql;

import com.google.common.base.Stopwatch;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Inet4Address;
Expand All @@ -28,6 +30,7 @@
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
Expand All @@ -41,14 +44,26 @@
@WebServlet(name = "CloudSQL", description = "CloudSQL: Write low order IP address 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";

String path = req.getRequestURI();
if (path.startsWith("/favicon.ico")) {
return; // ignore the request for favicon.ico
}

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);
Expand All @@ -60,51 +75,45 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOExc
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");
}
log("connecting to: " + url);
try (Connection conn = DriverManager.getConnection(url);
PreparedStatement statementCreateVisit = conn.prepareStatement(createVisitSql)) {
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.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");
}
out.println("Elapsed: " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
}
} catch (SQLException e) {
throw new ServletException("SQL error", e);
}
}

@Override
public void init() throws ServletException {
try {
String url = System.getProperty("cloudsql");
log("connecting to: " + url);
try {
Class.forName("com.mysql.jdbc.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.
}
}
}
// [END example]
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,8 @@
<threadsafe>true</threadsafe>
<runtime>java8</runtime>

<!-- <use-google-connector-j>true</use-google-connector-j> NO LONGER REQUIRED -->
<system-properties>
<property name="ae-cloudsql.cloudsql-database-url" value="jdbc:mysql://google/${database}?useSSL=false&amp;cloudSqlInstance=${INSTANCE_CONNECTION_NAME}&amp;socketFactory=com.google.cloud.sql.mysql.SocketFactory&amp;user=${user}&amp;password=${password}" />
<property name="ae-cloudsql.local-database-url" value="jdbc:mysql://google/${database}?useSSL=false&amp;cloudSqlInstance=${INSTANCE_CONNECTION_NAME}&amp;socketFactory=com.google.cloud.sql.mysql.SocketFactory&amp;user=${user}&amp;password=${password}" />
<property name="cloudsql" value="jdbc:mysql://google/${database}?useSSL=false&amp;cloudSqlInstance=${INSTANCE_CONNECTION_NAME}&amp;socketFactory=com.google.cloud.sql.mysql.SocketFactory&amp;user=${user}&amp;password=${password}" />
</system-properties>
</appengine-web-app>
<!-- [END config] -->
13 changes: 0 additions & 13 deletions appengine-java8/gaeinfo/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,6 @@ Use either:

$ mvn appengine:deploy

## Gradle
### Running locally

$ gradle appengineRun

If you do not have gradle installed, you can run using `./gradlew appengineRun`.

### Deploying

$ gradle appengineDeploy

If you do not have gradle installed, you can deploy using `./gradlew appengineDeploy`.

<!--
## Intelij Idea
Limitations - Appengine Standard support in the Intellij plugin is only available for the Ultimate Edition of Idea.
Expand Down
1 change: 1 addition & 0 deletions appengine-java8/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
<module>memcache</module>
<module>multitenancy</module>
<module>oauth2</module>
<module>postgres</module>
<module>requests</module>

<module>remote-client</module>
Expand Down
45 changes: 45 additions & 0 deletions appengine-java8/postgres/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Postgre SQL sample for Google App Engine J8
This sample demonstrates how to use [Cloud SQL](https://cloud.google.com/cloudsql/) on Google App
Engine standard Java 8

## Setup

* If you haven't already, Download and initialize the [Cloud SDK](https://cloud.google.com/sdk/)

`gcloud init`

* If you haven't already, Create an App Engine app within the current Google Cloud Project

`gcloud app create`

* If you haven't already, Setup [Application Default Credentials](https://developers.google.com/identity/protocols/application-default-credentials)

`gcloud auth application-default login`


* [Create an instance](https://cloud.google.com/sql/docs/postgres/create-instance)

* [Create a Database](https://cloud.google.com/sql/docs/postgres/create-manage-databases)

* [Create a user](https://cloud.google.com/sql/docs/postgres/create-manage-users)

* Note the **Instance connection name** under Overview > properties

## Running locally

```bash
$ mvn clean appengine:run -DINSTANCE_CONNECTION_NAME=instanceConnectionName -Duser=root -Dpassword=myPassowrd -Ddatabase=myDatabase
```

## Deploying

```bash
$ mvn clean appengine:deploy -DINSTANCE_CONNECTION_NAME=instanceConnectionName -Duser=root
-Dpassword=myPassword -Ddatabase=myDatabase
```


## Cleaning up

* [Delete your Instance](https://cloud.google.com/sql/docs/postgres/delete-instance)

116 changes: 116 additions & 0 deletions appengine-java8/postgres/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
<!--
Copyright 2017 Google Inc.

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-postgreSQL-j8</artifactId>

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

<!-- [START properties] -->
<properties>
<!-- INSTANCE_CONNECTION_NAME from Cloud Console > SQL > Instance Details > Properties
or gcloud sql instances describe <instance>
-->
<INSTANCE_CONNECTION_NAME>Project:Region:Instance</INSTANCE_CONNECTION_NAME>
<user>root</user>
<password>myPassword</password>
<database>sqldemo</database>

<!-- [START_EXCLUDE] -->
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<!-- [END_EXCLUDE] -->
</properties>
<!-- [END properties] -->

<dependencies>
<!-- Parent POM defines ${appengine.sdk.version} (updates frequently). -->
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-1.0-sdk</artifactId>
<version>1.9.54</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<type>jar</type>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client-appengine</artifactId>
<version>1.22.0</version>
</dependency>

<!-- [START dependencies] -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.1.1</version>
</dependency>

<dependency>
<groupId>com.google.cloud.sql</groupId>
<artifactId>postgres-socket-factory</artifactId>
<version>1.0.3</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>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<webResources>
<!-- in order to interpolate version from pom into appengine-web.xml -->
<resource>
<directory>${basedir}/src/main/webapp/WEB-INF</directory>
<filtering>true</filtering>
<targetPath>WEB-INF</targetPath>
</resource>
</webResources>
</configuration>
</plugin>

<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>appengine-maven-plugin</artifactId>
<version>1.3.1</version>
<configuration>
<deploy.promote>true</deploy.promote>
<deploy.stopPreviousVersion>true</deploy.stopPreviousVersion>
</configuration>
</plugin>

</plugins>
</build>
</project>
Loading