Tuesday, May 29, 2018

Google Cloud Translate Sample

Java Version

This sample requires you to have Java8.

Download Maven

This sample uses the Apache Maven build system. Before getting started, be sure to download and install it. When you use Maven as described here, it will automatically download the needed client libraries.

Authentication

This sample uses API Key for authentication.
 API Manager > Credentials > Create credentials > API Key
  • Set the environment variable GOOGLE_API_KEY
 export GOOGLE_API_KEY=<YOUR_PROJECT_API_KEY>

 

Download Source code

 
git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
cd java-docs-sample/translate

Run the sample

To build the sample, we use Maven.
mvn clean compile assembly:single
We can then run the assembled JAR file with the java command. The variable $COMMAND takes three values langsupport, detect and translate.
JAR_FILE=target/translate-1.0-jar-with-dependencies.jar
java -jar $JAR_FILE <detect|translate|langsupport> <text>
    <optional_source> <optional_target>
Example Usage:
INPUT="A quick brown fox jumped over a lazy dog."
SOURCE_LANG="en"
TARGET_LANG="fr"
Translate API Features:
  • List the languages supported by the API
    java -jar $JAR_FILE langsupport
    
  • List the languages supported for given target language
    java -jar $JAR_FILE langsupport $TARGET_LANG
    
  • Detect input text language
    java -jar $JAR_FILE detect "$INPUT"
    
  • Translate input text (with options)
    java -jar $JAR_FILE translate "$INPUT"
    java -jar $JAR_FILE translate "$INPUT" $SOURCE_LANG $TARGET_LANG
    

Translation API Client Libraries (Java)

Installing the client library

Setting up authentication

To run the client library, you must first set up authentication by creating a service account and setting an environment variable.
GCP Console


  1. Go to the Create service account key page in the GCP Console.
    Go to the Create Service Account Key page
  2. From the Service account drop-down list, select New service account.
  3. Enter a name into the Service account name field.
  4. From the Role drop-down list, select Project > Owner.
    Note: The Role field authorizes your service account to access resources. You can view and change this field later using GCP Console. If you are developing a production application, specify more granular permissions than Project > Owner. For more information, see granting roles to service accounts.
  5. Click Create. A JSON file that contains your key downloads to your computer.

Enviroment Variables
Provide authentication credentials to your application code by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS. Replace [PATH] with the file path of the JSON file that contains your service account key, and [FILE_NAME] with the filename.

Clone source
git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
cd ./java-docs-samples/translate/cloud-client

Build your project with:
mvn clean package -DskipTests
You can then run a given ClassName via:
mvn exec:java -Dexec.mainClass=com.example.translate.ClassName \
    -DpropertyName=propertyValue \
 -Dexec.args="any arguments to the app"

Translate a string (using the quickstart sample)

mvn exec:java -Dexec.mainClass=com.example.translate.QuickstartSample

Quickstart Google Cloud Translation API

This page shows how to make a Google Cloud Translation API request with curl.

Before you begin

  1. Set up a GCP Console project. Set up a project
    Click to:
    • Create or select a project.
    • Enable the Cloud Translation API for that project.
    • Create a service account.
    • Download a private key as JSON.
    You can view and manage these resources at any time in the GCP Console.
  2. Install and initialize the Cloud SDK.
  3. Provide authentication credentials to your application code by running the following command. Replace [PATH] with the location of the JSON file that contains your credentials.
    gcloud auth activate-service-account --key-file=[PATH]

Make a Translation API request

Make a Translation API Request using a REST method call to the v2 translate method.
  1. Use curl to make a request to the https://translation.googleapis.com/language/translate/v2 endpoint.
    The curl command includes JSON with the text to be translated (q), the language to translate from (source), and the language to translate to (target).
    The source and target languages are identified using the iso-639-1 codes. The source language is English (en) and the target language is Spanish (es). The format of the query is noted as "text" for plain text.
    The sample curl command uses the gcloud auth print-access-token command to get an authentication token.
    curl -s -X POST -H "Content-Type: application/json" \
        -H "Authorization: Bearer "$(gcloud auth print-access-token) \
        --data "{
      'q': 'The Great Pyramid of Giza (also known as the Pyramid of Khufu or the
            Pyramid of Cheops) is the oldest and largest of the three pyramids in
            the Giza pyramid complex.',
      'source': 'en',
      'target': 'es',
      'format': 'text'
    }" "https://translation.googleapis.com/language/translate/v2"
      
    You should see a response similar to the following:
    {
      "data": {
        "translations": [
          {
            "translatedText": "La Gran Pirámide de Giza (también conocida como la
             Pirámide de Khufu o la Pirámide de Keops) es la más antigua y más
             grande de las tres pirámides en el complejo de la pirámide de Giza."
          }
        ]
      }
    }
    
      
Congratulations! You've sent your first request to the Cloud Translation API!

Clean up

To avoid unnecessary Google Cloud Platform charges, use the GCP Console to delete your project if you do not need it.

Wednesday, May 23, 2018

Quickstart for Node.js in the App Engine Flexible Environment

This quickstart shows you how to create a small App Engine application that displays a short message.

Before you begin

Before running and deploying this sample, take the following steps:
  1. Use the GCP Console to create a new GCP project, create an App Engine application, and enable billing:
    Go to App Engine When prompted, select the region where you want your App Engine application located and then enable billing.
  2. Install the following prerequisites locally:
    1. Download and install git.
    2. Prepare your environment for Node.js development.
    3. Download and install the Google Cloud SDK and then initialize the gcloud tool:
      Download the SDK
  3. Alternatively: You can use Google Cloud Shell, which comes with git and Cloud SDK already installed, and many other features, such as language support and code editors. After Google Cloud Shell is launched, you can proceed with the rest of this tutorial and execute your commands within Cloud Shell.
This quickstart demonstrates a simple Node.js application written with the Express.js framework.

Download the Hello World app

We've created a simple Hello World app for Node.js so you can quickly get a feel for deploying an app to the App Engine flexible environment. Follow these steps from a command line to download Hello World to your local machine.
Download the sample app and navigate into the app directory:
  1. Clone the Hello World sample app repository to your local machine:
    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples
    
    Alternatively, you can download the sample as a zip file and extract it.
  2. Change to the directory that contains the sample code:
    cd nodejs-docs-samples/appengine/hello-world/flexible

Run Hello World on your local machine

  1. Install dependencies for this project by entering the following command:
    npm install
    or if you are using Yarn:
    yarn install
  2. Run the start script.
    npm start
    or if you are using Yarn:
    yarn start
  3. View your app in your web browser:
    • If you are using Cloud Shell, in the toolbar, click Web Preview and select Preview on port 8080 instead.
    • If you are not using Cloud Shell, enter the following address:
      http://localhost:8080
      
You can see the Hello World message from the sample app displayed in the page.
In your terminal window, press Ctrl+C to exit the web server.

Deploy and run Hello World on App Engine

To deploy your app to the App Engine flexible environment:
  1. Deploy the Hello World app by running the following command from the hello-world/flexible directory:
    gcloud app deploy
    Learn about the optional flags.
  2. Launch your browser and view the app at http://YOUR_PROJECT_ID.appspot.com, by running the following command:
    gcloud app browse
This time, the page that displays the Hello World message is delivered by a web server running on an App Engine instance. Congratulations! You've deployed your first Node.js app to App Engine flexible environment!
See the following sections for information about cleaning up as well as links to the possible next steps that you can take.

Clean up

To avoid incurring charges, you can delete your GCP project to stop billing for all the resources used within that project.
  1. In the GCP Console, go to the Projects page. Go to the Projects page
  2. In the project list, select the project you want to delete and click Delete project. After selecting the checkbox next to the project name, click
      Delete project
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

What's next

Learn the whole platform

Now that you know what it's like to develop and deploy App Engine apps, you can stretch out and see the rest of Google Cloud Platform. You already have the Google Cloud SDK installed and that gives you the tools to interact with products like Google Cloud SQL, Google Cloud Storage, Google Cloud Datastore, and more. For a guided walkthrough that teaches you how to create an application that uses the entire platform, not just App Engine, check out our quickstart on creating the Bookshelf app.

Learn about the App Engine flexible environment

Here are some topics to help continue your learning about App Engine.

Hello World code review

Hello World is the simplest possible App Engine app, as it contains only one service, has only one version, and all of the code is located within the app's root directory. This section describes each of the app files in detail.

app.js

The app.js file contains the JavaScript code to start a server and respond to requests.
The following code responds to requests from web clients by displaying the 'Hello World' message, via a server that runs on port 8080.
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.status(200).send('Hello, world!').end();
});
// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
  console.log('Press Ctrl+C to quit.');
});

app.yaml

The app.yaml file describes an application's deployment configuration:
runtime: nodejsenv: flex
# This sample incurs costs to run on the App Engine flexible environment. 
# The settings below are to reduce costs during testing and are not appropriate
# for production use. For more information, see:
# https://cloud.google.com/appengine/docs/flexible/nodejs/configuring-your-app-with-app-yaml
manual_scaling:  instances: 1resources:  cpu: 1
  memory_gb: 0.5
  disk_size_gb: 10
Here, app.yaml specifies the runtime used by the app, and sets env: flex, specifying that the app uses the flexible environment.

package.json

package.json is used to specify application dependencies, node version, and application startup.
{
  "name": "appengine-hello-world",
  "description": "Simple Hello World Node.js sample for Google App Engine Flexible Environment.",
  "version": "0.0.1",
  "private": true,
  "license": "Apache-2.0",
  "author": "Google Inc.",
  "repository": {
    "type": "git",
    "url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git"
  },
  "engines": {
    "node": ">=4.3.2"
  },
  "scripts": {
    "deploy": "gcloud app deploy",
    "start": "node app.js",
    "lint": "repo-tools lint",
    "pretest": "npm run lint",
    "system-test": "repo-tools test app",
    "test": "npm run system-test",
    "e2e-test": "repo-tools test deploy"
  },
  "dependencies": {
    "express": "4.16.2"
  },
  "devDependencies": {
    "@google-cloud/nodejs-repo-tools": "2.2.1"
  },
  "cloud-repo-tools": {
    "test": {
      "app": {
        "msg": "Hello, world!"
      }
    },
    "requiresKeyFile": true,
    "requiresProjectId": true
  }
}
This package.json specifies that the application uses Node.js v4.3.2 or later, depends on express, and that node app.js is used to start the application. For more details about how your application is installed and run, see the Node.js runtime documentation.

GCP - App Engine - Quickstart (Node.js)

Introduction

In this tutorial, you'll deploy a sample Node.js application to Google App 
By the end, you'll have learned how to:
  • Configure Deployments
    Learn how to edit a YAML file to edit a deployment’s configuration
  • Deploy apps with Google Cloud Shell
    Deploy with Cloud Shell, a web-based command line tool
This is a real App Engine deployment, so when the tutorial is over you can keep working on it.

Using Google Cloud Shell

Cloud Shell is a built-in command line tool for the console. We're going to use Cloud Shell to deploy our app.
  1. Open Google Cloud Shell
  2. Clone the sample code
    Use Cloud Shell to clone and navigate to the "Hello World" code. The sample code is cloned from your project repository to the Cloud Shell.
    In Cloud Shell enter:
    Clone a sample repository:
    TUTORIALDIR=src/crawler-20180523/nodejs_mvms_quickstart-2018-05-23-14-42
git clone https://github.com/GoogleCloudPlatform/nodejs-getting-started.git $TUTORIALDIR
Switch to the tutorial directory:
cd $TUTORIALDIR/1-hello-world

Configuring your deployment

You are now in the main directory for the sample code. We'll look at the files that configure your application.

The app.js file contains the JavaScript code to start a server and respond to requests.
The following code responds to requests from web clients by displaying the Hello World message, via a server that runs on port 8080.

Google App Engine uses YAML files to specify a deployment's configuration. app.yaml files contain information about your application, like the runtime environment, URL handlers, and more.


Testing your app

    Install npm packages
    We will install the npm packages on Cloud Shell in order to test run the Node.js app.
    To install npm packages, enter:
    npm install
  1. Test your app on Cloud Shell
    Cloud Shell lets you test your app before deploying to make sure it's running as intended, just like debugging on your local machine.
    To test your app enter:
    export PORT=8080
    npm start
  2. Preview your app with "Web preview"
    Your app is now running on Cloud Shell. You can access the app by using "Web preview" to connect to port 8080.
  3. Terminating the preview instance
    Terminate the instance of the application by pressing Ctrl+C in the Cloud Shell.

    Last steps

    Ensuring Compute Engine is initialized
    Compute Engine needs a few moments to initialize. The tutorial will continue automatically once it's ready.
    Deploying with Cloud Shell
    You can use Cloud Shell to deploy your app. To deploy your app enter:
    gcloud app deploy --project crawler-20180523
    Visit your app
    Congratulations! Your app has been deployed. The default URL of your app is crawler-20180523.appspot.com  Click the URL to visit it.
    The app is now running in the cloud. We will show you how to delete the project to avoid potential charges. 
    1. You can check in on your app by monitoring its status on the App Engine dashboard.
      Open the menu on the left side of the console.
      Then, select the App Engine section.

    Congratulations

    You have successfully deployed an App Engine application! Here are some next steps:
      1. Delete your tutorial project You should delete your project  to avoid additional charges.
      2. Download the Google Cloud SDK and develop locally
    1. After it downloads, extract the file  and initialize the SDK .
    2. Build your next application Learn how to use App Engine with other Cloud Platform products:

     

    Use MongoDB

    Deploy MongoDB on Compute Engine or use a managed, MongoDB service. 

    Learn to use Cloud Storage

    Cloud Storage is a powerful and simple object storage service.