├── ruby
├── .gitignore
├── token
│ └── access_token.txt.template
├── Gemfile
├── Gemfile.lock
├── README.md
└── src
│ └── app.rb
├── php
├── .gitignore
├── token
│ └── access_token.txt.template
├── README.md
└── public
│ └── leadgen.php
├── csharp
├── .gitignore
├── token
│ └── access_token.txt.template
├── src
│ └── LeadGenWebhook
│ │ ├── Startup.cs
│ │ ├── Program.cs
│ │ └── LeadGenWebhookModule.cs
├── leadgenwebhook.csproj
└── README.md
├── python
├── .gitignore
├── token
│ └── access_token.txt.template
├── requirements.txt
├── README.md
└── src
│ └── main.py
├── java
├── .gitignore
├── token
│ └── access_token.txt.template
├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
├── build.gradle
├── settings.gradle
├── README.md
├── gradlew.bat
├── src
│ └── main
│ │ └── java
│ │ └── LeadGenWebhook.java
└── gradlew
├── nodejs
├── .gitignore
├── token
│ └── access_token.txt.template
├── package.json
├── README.md
└── src
│ └── index.js
├── LICENSE
└── README.md
/ruby/.gitignore:
--------------------------------------------------------------------------------
1 | access_token.txt
2 |
--------------------------------------------------------------------------------
/php/.gitignore:
--------------------------------------------------------------------------------
1 | access_token.txt
2 | *.swp
3 |
--------------------------------------------------------------------------------
/csharp/.gitignore:
--------------------------------------------------------------------------------
1 | obj
2 | bin
3 | access_token.txt
4 |
--------------------------------------------------------------------------------
/python/.gitignore:
--------------------------------------------------------------------------------
1 | venv
2 | __pycache__
3 | access_token.txt
4 |
--------------------------------------------------------------------------------
/java/.gitignore:
--------------------------------------------------------------------------------
1 | build/*
2 | access_token.txt
3 | *.swp
4 | .gradle
5 | .m2
6 |
--------------------------------------------------------------------------------
/csharp/token/access_token.txt.template:
--------------------------------------------------------------------------------
1 | REPLACE_THIS_TEXT_WITH_YOUR_ACCESS_TOKEN
2 |
--------------------------------------------------------------------------------
/java/token/access_token.txt.template:
--------------------------------------------------------------------------------
1 | REPLACE_THIS_TEXT_WITH_YOUR_ACCESS_TOKEN
2 |
--------------------------------------------------------------------------------
/nodejs/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | npm-debug.log
3 | access_token.txt
4 | *.swp
5 |
--------------------------------------------------------------------------------
/nodejs/token/access_token.txt.template:
--------------------------------------------------------------------------------
1 | REPLACE_THIS_TEXT_WITH_YOUR_ACCESS_TOKEN
2 |
--------------------------------------------------------------------------------
/php/token/access_token.txt.template:
--------------------------------------------------------------------------------
1 | REPLACE_THIS_TEXT_WITH_YOUR_ACCESS_TOKEN
2 |
--------------------------------------------------------------------------------
/python/token/access_token.txt.template:
--------------------------------------------------------------------------------
1 | REPLACE_THIS_TEXT_WITH_YOUR_ACCESS_TOKEN
2 |
--------------------------------------------------------------------------------
/ruby/token/access_token.txt.template:
--------------------------------------------------------------------------------
1 | REPLACE_THIS_TEXT_WITH_YOUR_ACCESS_TOKEN
2 |
--------------------------------------------------------------------------------
/java/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/supasate/facebook-realtime-lead-ads-demo/HEAD/java/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/ruby/Gemfile:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | source "https://rubygems.org"
4 |
5 | git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
6 |
7 | gem "sinatra", ">= 2.0.2"
8 |
--------------------------------------------------------------------------------
/java/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/python/requirements.txt:
--------------------------------------------------------------------------------
1 | certifi==2018.1.18
2 | chardet==3.0.4
3 | click==6.7
4 | Flask>=0.12.3
5 | future==0.16.0
6 | idna==2.6
7 | itsdangerous==0.24
8 | Jinja2==2.10
9 | MarkupSafe==1.0
10 | requests>=2.20.0
11 | urllib3>=1.23
12 | Werkzeug==0.14.1
13 |
--------------------------------------------------------------------------------
/csharp/src/LeadGenWebhook/Startup.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Builder;
2 | using Nancy.Owin;
3 |
4 | namespace LeadGenWebhook
5 | {
6 | public class Startup
7 | {
8 | public void Configure(IApplicationBuilder app)
9 | {
10 | app.UseOwin(x => x.UseNancy());
11 | }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/java/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'java'
3 | id 'application'
4 | }
5 |
6 | mainClassName = 'LeadGenWebhook'
7 |
8 | dependencies {
9 | compile 'io.javalin:javalin:1.3.0'
10 | compile 'org.slf4j:slf4j-simple:1.7.25'
11 | compile 'org.json:json:20180130'
12 | }
13 |
14 | repositories {
15 | jcenter()
16 | }
17 |
--------------------------------------------------------------------------------
/java/settings.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * This file was generated by the Gradle 'init' task.
3 | *
4 | * The settings file is used to specify which projects to include in your build.
5 | *
6 | * Detailed information about configuring a multi-project build in Gradle can be found
7 | * in the user guide at https://docs.gradle.org/4.6/userguide/multi_project_builds.html
8 | */
9 |
10 | rootProject.name = 'lead-gen-webhook'
11 |
--------------------------------------------------------------------------------
/ruby/Gemfile.lock:
--------------------------------------------------------------------------------
1 | GEM
2 | remote: https://rubygems.org/
3 | specs:
4 | mustermann (1.0.3)
5 | rack (2.0.6)
6 | rack-protection (2.0.4)
7 | rack
8 | sinatra (2.0.4)
9 | mustermann (~> 1.0)
10 | rack (~> 2.0)
11 | rack-protection (= 2.0.4)
12 | tilt (~> 2.0)
13 | tilt (2.0.8)
14 |
15 | PLATFORMS
16 | ruby
17 |
18 | DEPENDENCIES
19 | sinatra (>= 2.0.2)
20 |
21 | BUNDLED WITH
22 | 1.17.1
23 |
--------------------------------------------------------------------------------
/nodejs/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "realtime-leadgen-node-demo",
3 | "version": "1.0.0",
4 | "description": "A Node.js demo for retrieving realtime leads from Facebook lead ads",
5 | "main": "index.js",
6 | "dependencies": {
7 | "axios": "^0.18.0",
8 | "body-parser": "^1.18.2",
9 | "express": "^4.16.2"
10 | },
11 | "scripts": {
12 | "start": "node src/index.js"
13 | },
14 | "author": "Supasate Ping Choochaisri",
15 | "license": "MIT"
16 | }
17 |
--------------------------------------------------------------------------------
/csharp/leadgenwebhook.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | Exe
4 | netcoreapp1.1
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/csharp/src/LeadGenWebhook/Program.cs:
--------------------------------------------------------------------------------
1 | using System.IO;
2 | using Microsoft.AspNetCore.Builder;
3 | using Microsoft.AspNetCore.Hosting;
4 |
5 | namespace LeadGenWebhook
6 | {
7 | public class Program
8 | {
9 | const string PORT = "3000";
10 |
11 | public static void Main(string[] args)
12 | {
13 | var host = new WebHostBuilder()
14 | .UseContentRoot(Directory.GetCurrentDirectory())
15 | .UseKestrel()
16 | .UseStartup()
17 | .UseUrls("https://*:" + PORT)
18 | .Build();
19 |
20 | host.Run();
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Supasate Choochaisri
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/java/README.md:
--------------------------------------------------------------------------------
1 | # Facebook Realtime Lead Ads Demo (Java)
2 |
3 | A Java demo based on [Javalin](https://github.com/tipsy/javalin) for retrieving realtime leads from Facebook lead ads
4 |
5 | # Prerequisites
6 |
7 | 1. HTTPS domain and HTTPS endpoint must be accessible from Facebook
8 | 2. A page admin's access token with `manage_pages` permission
9 |
10 | # Getting Started
11 |
12 | 1. Copy the file `token/access_token.txt.template` to `token/access_token.txt` and change its content to your system user access token.
13 |
14 | Note: Your system user needs to be a page admin and grant `manage_pages` permission.
15 |
16 | 2. Build with gradle
17 |
18 | ```base
19 | ./gradlew build
20 | ```
21 |
22 | 3. Run
23 |
24 | ```bash
25 | ./gradlew run
26 | ```
27 |
28 | # How to test with your local machine
29 |
30 | If you don't have a HTTPS domain, you can test it with your local machine by using ngrok (or other https tunneling service).
31 |
32 | 1. Install ngrok.
33 |
34 | ```bash
35 | npm install -g ngrok
36 | ```
37 |
38 | 2. Start ngrok tunneling to forward http(s) traffic to port 3000 (or your preferred port).
39 |
40 | ```bash
41 | ngrok http 3000
42 | ```
43 |
44 | 3. It will print its status with a line like the following:
45 |
46 | ```bash
47 | Forwarding https://7f05e4bb.ngrok.io -> localhost:3000
48 | ```
49 |
50 | Copy this https URL. We will use it to set up a webhook.
51 |
--------------------------------------------------------------------------------
/php/README.md:
--------------------------------------------------------------------------------
1 | Facebook Realtime Lead Ads Demo (PHP)
2 | =========================================
3 | A PHP demo for retrieving realtime leads from Facebook lead ads
4 |
5 | Prerequisites
6 | =============
7 | 1. HTTPS domain and HTTPS endpoint must be accessible from Facebook
8 | 2. A page admin's access token with `manage_pages` permission
9 |
10 | Getting Started
11 | ===============
12 | 1. Copy the file `token/access_token.txt.template` to `token/access_token.txt` and change its content to your system user access token.
13 |
14 | Note: Your system user needs to be a page admin and grant `manage_pages` permission.
15 |
16 | 2. Start a built-in PHP web server at port 3000 (or your preferred port)
17 | ```bash
18 | php -S localhost:3000 -t public
19 | ```
20 |
21 | How to test with your local machine
22 | ===================================
23 | If you don't have a HTTPS domain, you can test it with your local machine by using ngrok (or other https tunneling service).
24 |
25 | 1. Install ngrok.
26 | ```bash
27 | npm install -g ngrok
28 | ```
29 | 2. Start ngrok tunneling to forward http(s) traffic to port 3000 (or your preferred port).
30 | ```bash
31 | ngrok http 3000
32 | ```
33 |
34 | 3. It will print its status with a line like the following:
35 | ```bash
36 | Forwarding https://7f05e4bb.ngrok.io -> localhost:3000
37 | ```
38 | Copy this https URL. We will use it to set up a webhook.
39 |
40 |
--------------------------------------------------------------------------------
/python/README.md:
--------------------------------------------------------------------------------
1 | # Facebook Realtime Lead Ads Demo (Python)
2 |
3 | A Python demo based on [Flask](https://github.com/pallets/flask) for retrieving realtime leads from Facebook lead ads
4 |
5 | # Prerequisites
6 |
7 | 1. HTTPS domain and HTTPS endpoint must be accessible from Facebook
8 | 2. A page admin's access token with `manage_pages` permission
9 |
10 | # Getting Started
11 |
12 | 1. Install packages
13 |
14 | ```bash
15 | pip install -r requirements.txt
16 | ```
17 |
18 | 2. Copy the file `token/access_token.txt.template` to `token/access_token.txt` and change its content to your system user access token.
19 |
20 | Note: Your system user needs to be a page admin and grant `manage_pages` permission.
21 |
22 | 3. Start
23 |
24 | ```bash
25 | python src/main.py
26 | ```
27 |
28 | # How to test with your local machine
29 |
30 | If you don't have a HTTPS domain, you can test it with your local machine by using ngrok (or other https tunneling service).
31 |
32 | 1. Install ngrok.
33 |
34 | ```bash
35 | npm install -g ngrok
36 | ```
37 |
38 | 2. Start ngrok tunneling to forward http(s) traffic to port 3000 (or your preferred port).
39 |
40 | ```bash
41 | ngrok http 3000
42 | ```
43 |
44 | 3. It will print its status with a line like the following:
45 |
46 | ```bash
47 | Forwarding https://7f05e4bb.ngrok.io -> localhost:3000
48 | ```
49 |
50 | Copy this https URL. We will use it to set up a webhook.
51 |
--------------------------------------------------------------------------------
/ruby/README.md:
--------------------------------------------------------------------------------
1 | # Facebook Realtime Lead Ads Demo (Ruby)
2 |
3 | A Ruby demo based on [Sinatra](https://github.com/sinatra/sinatra) for retrieving realtime leads from Facebook lead ads.
4 |
5 | # Prerequisites
6 |
7 | 1. HTTPS domain and HTTPS endpoint must be accessible from Facebook
8 | 2. A page admin's access token with `manage_pages` permission
9 |
10 | # Getting Started
11 |
12 | 1. Install packages with [bundle](http://bundler.io/)
13 |
14 | ```bash
15 | bundle install
16 | ```
17 |
18 | 2. Copy the file `token/access_token.txt.template` to `token/access_token.txt` and change its content to your system user access token.
19 |
20 | Note: Your system user needs to be a page admin and grant `manage_pages` permission.
21 |
22 | 3. Start
23 |
24 | ```bash
25 | ruby src/app.rb
26 | ```
27 |
28 | # How to test with your local machine
29 |
30 | If you don't have a HTTPS domain, you can test it with your local machine by using ngrok (or other https tunneling service).
31 |
32 | 1. Install ngrok.
33 |
34 | ```bash
35 | npm install -g ngrok
36 | ```
37 |
38 | 2. Start ngrok tunneling to forward http(s) traffic to port 3000 (or your preferred port).
39 |
40 | ```bash
41 | ngrok http 3000
42 | ```
43 |
44 | 3. It will print its status with a line like the following:
45 |
46 | ```bash
47 | Forwarding https://7f05e4bb.ngrok.io -> localhost:3000
48 | ```
49 |
50 | Copy this https URL. We will use it to set up a webhook.
51 |
--------------------------------------------------------------------------------
/nodejs/README.md:
--------------------------------------------------------------------------------
1 | # Facebook Realtime Lead Ads Demo (Node.js)
2 |
3 | A Node.js demo based on [express](https://github.com/expressjs/express) for retrieving realtime leads from Facebook lead ads
4 |
5 | # Prerequisites
6 |
7 | 1. HTTPS domain and HTTPS endpoint must be accessible from Facebook
8 | 2. A page admin's access token with `manage_pages` permission
9 |
10 | # Getting Started
11 |
12 | 1. Install required packages.
13 |
14 | ```bash
15 | npm install
16 | ```
17 |
18 | or
19 |
20 | ```bash
21 | yarn
22 | ```
23 |
24 | 2. Copy the file `src/access_token.txt.template` to `src/access_token.txt` and change its content to your system user access token.
25 | Note: Your system user needs to be a page admin and grant `manage_pages` permission.
26 |
27 | 3. Start the server
28 |
29 | ```bash
30 | npm start
31 | ```
32 |
33 | # How to test with your local machine
34 |
35 | If you don't have a HTTPS domain, you can test it with your local machine by using ngrok (or other https tunneling service).
36 |
37 | 1. Install ngrok.
38 |
39 | ```bash
40 | npm install -g ngrok
41 | ```
42 |
43 | 2. Start ngrok tunneling to forward http(s) traffic to port 3000 (or your preferred port).
44 |
45 | ```bash
46 | ngrok http 3000
47 | ```
48 |
49 | 3. It will print its status with a line like the following:
50 |
51 | ```bash
52 | Forwarding https://7f05e4bb.ngrok.io -> localhost:3000
53 | ```
54 |
55 | Copy this https URL. We will use it to set up a webhook.
56 |
--------------------------------------------------------------------------------
/csharp/README.md:
--------------------------------------------------------------------------------
1 | # Facebook Realtime Lead Ads Demo (C#)
2 |
3 | A C# demo based on [Nancy](https://github.com/NancyFx/Nancy) for retrieving realtime leads from Facebook lead ads
4 |
5 | # Prerequisites
6 |
7 | 1. HTTPS domain and HTTPS endpoint must be accessible from Facebook
8 | 2. A page admin's access token with `manage_pages` permission
9 |
10 | # Getting Started
11 | 1. Install [.NET Core SDK 1.1.7](https://github.com/dotnet/core/blob/master/release-notes/download-archives/1.1.6-download.md) (It doesn't work on .NET Core 2.0)
12 |
13 | 2. Install packages
14 |
15 | ```bash
16 | dotnet restore
17 | ```
18 |
19 | 3. Copy the file `token/access_token.txt.template` to `token/access_token.txt` and change its content to your system user access token.
20 |
21 | Note: Your system user needs to be a page admin and grant `manage_pages` permission.
22 |
23 | 4. Start
24 |
25 | ```bash
26 | dotnet run
27 | ```
28 |
29 | # How to test with your local machine
30 |
31 | If you don't have a HTTPS domain, you can test it with your local machine by using ngrok (or other https tunneling service).
32 |
33 | 1. Install ngrok.
34 |
35 | ```bash
36 | npm install -g ngrok
37 | ```
38 |
39 | 2. Start ngrok tunneling to forward http(s) traffic to port 3000 (or your preferred port).
40 |
41 | ```bash
42 | ngrok http 3000
43 | ```
44 |
45 | 3. It will print its status with a line like the following:
46 |
47 | ```bash
48 | Forwarding https://7f05e4bb.ngrok.io -> localhost:3000
49 | ```
50 |
51 | Copy this https URL. We will use it to set up a webhook.
52 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Facebook Realtime Lead Ads Demo
2 |
3 | Demos for retrieving realtime leads from Facebook lead ads.
4 |
5 | ## What web frameworks we use to build the demos
6 |
7 | To make our demo applications can run as stand alone applications without additional web servers, we've built them based on micro web frameworks as follows:
8 |
9 | * C# - based on [Nancy](https://github.com/NancyFx/Nancy)
10 | * Java - based on [Javalin](https://github.com/tipsy/javalin)
11 | * Node.js (JavaScript) - based on [express](https://github.com/expressjs/express)
12 | * PHP - vanilla PHP with built-in web server
13 | * Python - based on [Flask](https://github.com/pallets/flask)
14 | * Ruby - based on [Sinatra](https://github.com/sinatra/sinatra)
15 |
16 | ## Prerequisites
17 |
18 | 1. Have access to your [Facebook App](httsp://developers.facebook.com/apps).
19 | 2. Have access to your [Business Manager](https://business.facebook.com/select/).
20 | 3. Have access to your Facebook Page associated with a lead ads campaign.
21 | 4. Add the Facebook app and page to your Business Manager. (in Business Manager -> Business Settings -> Apps -> Add)
22 | 5. Create a `System User`. (in Business Manager left column menu (need to have at least 1 app in Business Manager to see the System User menu))
23 | 6. Assign your page to the system user as `Page Admin`. (in Business Manager -> Business Settings -> System Users -> Assign Assets)
24 | 7. Assign the system user to your facebook app as developer (in App dashboard -> Roles).
25 | 8. Subscribe your App to your Page by [calling Graph API](https://developers.facebook.com/docs/graph-api/reference/page/subscribed_apps) (Note: you can use [Graph API Explorer](https://developers.facebook.com/tools/explorer/). Select your App and get page access token for your page and make a POST request to `//subscribed_apps`)
26 | 9. Generate system user access token with `manage_pages` and `leads_retrieval` permission. (in Business Manager -> Business Settings -> System Users -> Generate New Token)
27 |
28 | ## Note
29 |
30 | We've simplified the demo applications to make them concise for a crash-course workshop and intentionally ignored handling some edge cases.
31 |
--------------------------------------------------------------------------------
/java/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/ruby/src/app.rb:
--------------------------------------------------------------------------------
1 | require 'sinatra'
2 | require 'net/http'
3 |
4 | set :port, 3000
5 |
6 | ###################################################################
7 | # Part 1: Subscribe a leadgen endpoint to webhook #
8 | ###################################################################
9 | # A token that Facebook will echo back to you as part of
10 | # callback URL verification.
11 | VERIFY_TOKEN = 'YOUR_SECURE_VERIFY_TOKEN'
12 | # Endpoint for verifying webhook subscripton
13 | get '/leadgen' do
14 | # Extract a verify token we set in the webhook subscription
15 | # and a challenge to echo back.
16 | verify_token = params['hub.verify_token']
17 | challenge = params['hub.challenge']
18 |
19 | if verify_token.nil? || challenge.nil?
20 | return 'Missing hub.verify_token and hub.challenge params'
21 | end
22 |
23 | if verify_token != VERIFY_TOKEN
24 | return 'Verify token does not match'
25 | end
26 | # We echo the received challenge back to Facebook to finish
27 | # the verification process.
28 | return challenge
29 | end
30 |
31 | ###################################################################
32 | # Part 2: Retrieving realtime leads #
33 | ###################################################################
34 | # Your system user access token file path.
35 | # Note: Your system user needs to be an admin of the subscribed page.
36 | ACCESS_TOKEN_PATH = File.join(File.dirname(__FILE__), '..', 'token', 'access_token.txt')
37 | # Graph API endpoint
38 | GRAPH_API_VERSION = 'v2.12'
39 | GRAPH_API_ENDPOINT = "https://graph.facebook.com/#{GRAPH_API_VERSION}"
40 |
41 | # Facebook will post realtime leads to this endpoint
42 | # if we've already subscribed to the webhook in part 1.
43 | post '/leadgen' do
44 | if !File.file?(ACCESS_TOKEN_PATH)
45 | puts 'Access token file does not exsist'
46 | return 500
47 | end
48 |
49 | access_token = File.read(ACCESS_TOKEN_PATH)
50 |
51 | # Get value from POST request body
52 | body = JSON.parse request.body.read
53 | body['entry'].each { |page|
54 | page['changes'].each { |change|
55 | # We get page, form, and lead IDs from the change here.
56 | # We need the lead gen ID to get the lead data.
57 | # The form ID and page ID are optional.
58 | # You may want to record them into your CRM system.
59 | page_id = change['value']['page_id']
60 | form_id = change['value']['form_id']
61 | leadgen_id = change['value']['leadgen_id']
62 | puts "Page ID #{page_id}, Form ID #{form_id}, Leadgen ID #{leadgen_id}"
63 | # Call graph API to request lead info with the lead ID
64 | # and access token.
65 | leadgen_uri = "#{GRAPH_API_ENDPOINT}/#{leadgen_id}?access_token=#{access_token}"
66 | response = JSON.parse Net::HTTP.get(URI.parse(leadgen_uri))
67 | created_time = response['created_time']
68 | field_data = response['field_data']
69 |
70 | # Handle lead answer here (insert data into your CRM system)
71 | puts "Created time #{created_time}"
72 | field_data.each { |field|
73 | question = field['name']
74 | answers = field['values'].join(',')
75 | puts "Question #{question}"
76 | puts "Answer #{answers}"
77 | }
78 | }
79 | }
80 | # Send HTTP 200 OK status to indicate we've received the update.
81 | return 200
82 | end
83 |
--------------------------------------------------------------------------------
/php/public/leadgen.php:
--------------------------------------------------------------------------------
1 | id;
63 | $created_time = $response->created_time;
64 | $field_data = $response->field_data;
65 |
66 | // Handle lead answer here (insert data into your CRM system)
67 | console_log('Lead ID '.$id);
68 | console_log('Created time '.$created_time);
69 | foreach ($field_data as $field) {
70 | $question = $field->name;
71 | $answers = $field->values;
72 | console_log('Question '.$question);
73 | console_log('Answers '.print_r($answers, true));
74 | }
75 | }
76 | }
77 | // Send HTTP 200 OK status to indicate we've received the update.
78 | http_response_code(200);
79 | }
80 |
--------------------------------------------------------------------------------
/nodejs/src/index.js:
--------------------------------------------------------------------------------
1 | const axios = require('axios');
2 | const bodyParser = require('body-parser');
3 | const express = require('express');
4 | const fs = require('fs');
5 | const path = require('path');
6 |
7 | const SERVER_PORT = 3000;
8 | const app = express();
9 | app.use(bodyParser.json());
10 |
11 | /////////////////////////////////////////////////////////////////////////
12 | // Part 1: Subscribe a leadgen endpoint to webhook //
13 | /////////////////////////////////////////////////////////////////////////
14 |
15 | // A token that Facebook will echo back to you as part of callback URL verification.
16 | const VERIFY_TOKEN = 'YOUR_SECURE_VERIFY_TOKEN';
17 |
18 | // Endpoint for verifying webhook subscripton
19 | app.get('/leadgen', (req, res) => {
20 | if (!req.query) {
21 | res.send({success: false, reason: 'Empty request params'});
22 | return;
23 | }
24 | // Extract a verify token we set in the webhook subscription and a challenge to echo back.
25 | const verifyToken = req.query['hub.verify_token'];
26 | const challenge = req.query['hub.challenge'];
27 |
28 | if (!verifyToken || !challenge) {
29 | res.send({
30 | success: false,
31 | reason: 'Missing hub.verify_token and hub.challenge params',
32 | });
33 | return;
34 | }
35 |
36 | if (verifyToken !== VERIFY_TOKEN) {
37 | res.send({success: false, reason: 'Verify token does not match'});
38 | return;
39 | }
40 | // We echo the received challenge back to Facebook to finish the verification process.
41 | res.send(challenge);
42 | });
43 |
44 | /////////////////////////////////////////////////////////////////////////
45 | // Part 2: Retrieving realtime leads //
46 | /////////////////////////////////////////////////////////////////////////
47 |
48 | // Graph API endpoint
49 | const GRAPH_API_VERSION = 'v2.12';
50 | const GRAPH_API_ENDPOINT = `https://graph.facebook.com/${GRAPH_API_VERSION}`;
51 | // Your system user access token file path.
52 | // Note: Your system user needs to be an admin of the subscribed page.
53 | const ACCESS_TOKEN_PATH = path.join(
54 | __dirname,
55 | '..',
56 | 'token',
57 | 'access_token.txt'
58 | );
59 |
60 | // Read access token for calling graph API.
61 | if (!fs.existsSync(ACCESS_TOKEN_PATH)) {
62 | console.log(`The file ${ACCESS_TOKEN_PATH} does not exist.`);
63 | process.exit(1);
64 | }
65 | const accessToken = fs.readFileSync(ACCESS_TOKEN_PATH, 'utf-8');
66 | // Facebook will post realtime leads to this endpoint if we've already subscribed to the webhook in part 1.
67 | app.post('/leadgen', (req, res) => {
68 | const entry = req.body.entry;
69 |
70 | entry.forEach(page => {
71 | page.changes.forEach(change => {
72 | // We get page, form, and lead IDs from the change here.
73 | // We need the lead gen ID to get the lead data.
74 | // The form ID and page ID are optional. You may want to record them into your CRM system.
75 | const {page_id, form_id, leadgen_id} = change.value;
76 | console.log(
77 | `Page ID ${page_id}, Form ID ${form_id}, Lead gen ID ${leadgen_id}`
78 | );
79 |
80 | // Call graph API to request lead info with the lead ID and access token.
81 | const leadgenURI = `${GRAPH_API_ENDPOINT}/${leadgen_id}?access_token=${accessToken}`;
82 |
83 | axios(leadgenURI)
84 | .then(response => {
85 | const {created_time, id, field_data} = response.data;
86 |
87 | // Handle lead answer here (insert data into your CRM system)
88 | console.log('Lead id', id);
89 | console.log('Created time', created_time);
90 | field_data.forEach(field => {
91 | console.log('Question ', field.name);
92 | console.log('Answers ', field.values);
93 | });
94 | })
95 | .catch(error => {
96 | // Handle error here
97 | console.log(error);
98 | });
99 | });
100 | });
101 | // Send HTTP 200 OK status to indicate we've received the update.
102 | res.sendStatus(200);
103 | });
104 |
105 | // Start web server
106 | app.listen(SERVER_PORT, () =>
107 | console.log(`Server is listening at localhost:${SERVER_PORT}`)
108 | );
109 |
--------------------------------------------------------------------------------
/python/src/main.py:
--------------------------------------------------------------------------------
1 | from flask import Flask, request, make_response, jsonify
2 | from os import path
3 | import json
4 | import requests
5 |
6 | app = Flask(__name__)
7 |
8 |
9 | @app.route('/leadgen', methods=['GET', 'POST'])
10 | def leadgen():
11 | if request.method == 'GET':
12 | ###################################################################
13 | # Part 1: Subscribe a leadgen endpoint to webhook #
14 | ###################################################################
15 | # A token that Facebook will echo back to you as part of
16 | # callback URL verification.
17 | VERIFY_TOKEN = 'YOUR_SECURE_VERIFY_TOKEN'
18 | # Extract a verify token we set in the webhook subscription
19 | # and a challenge to echo back.
20 | verify_token = request.args.get('hub.verify_token')
21 | challenge = request.args.get('hub.challenge')
22 |
23 | if (not verify_token or not challenge):
24 | return 'Missing hub.verify_token and hub.challenge params'
25 |
26 | if (verify_token != VERIFY_TOKEN):
27 | return 'Verify token does not match'
28 | # We echo the received challenge back to Facebook to finish
29 | # the verification process.
30 | return challenge
31 | elif request.method == 'POST':
32 | ###################################################################
33 | # Part 2: Retrieving realtime leads #
34 | ###################################################################
35 | # Facebook will post realtime leads to this endpoint
36 | # if we've already subscribed to the webhook in part 1.
37 |
38 | # Graph API endpoint
39 | GRAPH_API_VERSION = 'v2.12'
40 | GRAPH_API_ENDPOINT = 'https://graph.facebook.com/' + GRAPH_API_VERSION
41 | # Your system user access token file path.
42 | # Note: Your system user needs to be an admin of the subscribed page.
43 | current_dir = path.dirname(path.realpath(__file__))
44 | ACCESS_TOKEN_PATH = path.join(
45 | current_dir, '..', 'token', 'access_token.txt'
46 | )
47 | if not path.isfile(ACCESS_TOKEN_PATH):
48 | error_message = 'Access token file does not exsist'
49 | app.logger.error(error_message)
50 | return make_response(
51 | jsonify(success=False, message=error_message),
52 | 500
53 | )
54 |
55 | f = open(ACCESS_TOKEN_PATH, 'r')
56 | access_token = f.read()
57 | # Get value from POST request body
58 | body = request.get_json()
59 | for page in body.get('entry'):
60 | for change in page.get('changes'):
61 | # We get page, form, and lead IDs from the change here.
62 | # We need the lead gen ID to get the lead data.
63 | # The form ID and page ID are optional.
64 | # You may want to record them into your CRM system.
65 | value = change.get('value')
66 | page_id = value.get('page_id')
67 | form_id = value.get('form_id')
68 | leadgen_id = value.get('leadgen_id')
69 | print('Page ID {}, Form ID {}, Lead ID {}'.format(
70 | page_id, form_id, leadgen_id
71 | ))
72 |
73 | # Call graph API to request lead info with the lead ID
74 | # and access token.
75 | leadgen_uri = (GRAPH_API_ENDPOINT + '/' + leadgen_id +
76 | '?access_token=' + access_token)
77 | response = json.loads(requests.get(leadgen_uri).text)
78 | created_time = response.get('created_time')
79 | field_data = response.get('field_data')
80 |
81 | # Handle lead answer here (insert data into your CRM system)
82 | print('Created time ', created_time)
83 | for field in field_data:
84 | question = field.get('name')
85 | answers = field.get('values')
86 | print('Question ', question)
87 | print('Answers ', ','.join(answers))
88 |
89 | # Send HTTP 200 OK status to indicate we've received the update.
90 | return make_response(jsonify(success=True), 200)
91 |
92 |
93 | PORT = 3000
94 |
95 | if __name__ == '__main__':
96 | app.run(host='0.0.0.0', port=PORT)
97 |
--------------------------------------------------------------------------------
/csharp/src/LeadGenWebhook/LeadGenWebhookModule.cs:
--------------------------------------------------------------------------------
1 | using Nancy;
2 | using Nancy.Extensions;
3 | using Newtonsoft.Json;
4 | using System;
5 | using System.IO;
6 | using System.Net;
7 |
8 | namespace LeadGenWebhook
9 | {
10 | public class LeadGenWebhookModule : NancyModule
11 | {
12 | public LeadGenWebhookModule()
13 | {
14 | ///////////////////////////////////////////////////////////////////
15 | // Part 1: Subscribe a leadgen endpoint to webhook //
16 | ///////////////////////////////////////////////////////////////////
17 | // A token that Facebook will echo back to you as part of callback URL verification.
18 | const string VERIFY_TOKEN = "YOUR_SECURE_VERIFY_TOKEN";
19 | // Endpoint for verifying webhook subscripton
20 | Get("/leadgen", parameters => {
21 | // Extract a verify token we set in the webhook subscription and a challenge to echo back.
22 | var verifyToken = this.Request.Query["hub.verify_token"];
23 | var challenge = this.Request.Query["hub.challenge"];
24 |
25 | if (verifyToken == null || challenge == null) {
26 | return "Missing hub.verify_token and hub.challenge params";
27 | }
28 |
29 | if (verifyToken != VERIFY_TOKEN) {
30 | return "Verify token does not match";
31 | }
32 | // We echo the received challenge back to Facebook to finish the verification process.
33 | return challenge;
34 | });
35 |
36 | string ACCESS_TOKEN_PATH = Path.Combine(
37 | Directory.GetCurrentDirectory(),
38 | "token/access_token.txt"
39 | );
40 | string GRAPH_API_VERSION = "v2.12";
41 | string GRAPH_API_ENDPOINT = $"https://graph.facebook.com/{GRAPH_API_VERSION}";
42 |
43 | Post("/leadgen", async parameters => {
44 | // Read access token for calling graph API.
45 | if (!File.Exists(ACCESS_TOKEN_PATH)) {
46 | Console.WriteLine("The access token file does not exist.");
47 | return 500;
48 | }
49 | string accessToken = File.ReadAllText(ACCESS_TOKEN_PATH);
50 |
51 | // Get value from POST request body
52 | dynamic body = JsonConvert.DeserializeObject(this.Request.Body.AsString());
53 |
54 | foreach (dynamic page in body.entry) {
55 | foreach (dynamic change in page.changes) {
56 | // We get page, form, and lead IDs from the change here.
57 | // We need the lead gen ID to get the lead data.
58 | // The form ID and page ID are optional. You may want to record them into your CRM system.
59 | string pageID = change.value.page_id;
60 | string formID = change.value.form_id;
61 | string leadgenID = change.value.leadgen_id;
62 | Console.WriteLine($"Page ID {pageID}, Form ID {formID}, Leadgen ID {leadgenID}");
63 |
64 | // Call graph API to request lead info with the lead ID and access token.\
65 | string leadgenUri = $"{GRAPH_API_ENDPOINT}/{leadgenID}?access_token={accessToken}";
66 | HttpWebRequest request = (HttpWebRequest)WebRequest.Create(leadgenUri);
67 | using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
68 | using(Stream stream = response.GetResponseStream())
69 | using(StreamReader reader = new StreamReader(stream))
70 | {
71 | dynamic jsonResponse = JsonConvert.DeserializeObject(await reader.ReadToEndAsync());
72 | string createdTime = jsonResponse.created_time;
73 | dynamic fieldData = jsonResponse.field_data;
74 |
75 | // Handle lead answer here (insert data into your CRM system)
76 | Console.WriteLine($"Created time {createdTime}");
77 | foreach (dynamic field in fieldData) {
78 | string question = field.name;
79 | string answers = String.Join(",", field.values);
80 | Console.WriteLine($"Question {question}");
81 | Console.WriteLine($"Answers {answers}");
82 | }
83 | }
84 | }
85 | }
86 | // Send HTTP 200 OK status to indicate we've received the update.
87 | return 200;
88 | });
89 | }
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/java/src/main/java/LeadGenWebhook.java:
--------------------------------------------------------------------------------
1 | import io.javalin.Javalin;
2 | import java.io.File;
3 | import java.io.FileNotFoundException;
4 | import java.net.URL;
5 | import java.util.Scanner;
6 | import org.json.JSONArray;
7 | import org.json.JSONObject;
8 |
9 |
10 | public class LeadGenWebhook {
11 | public static final int SERVER_PORT = 3000;
12 |
13 | public static void main(String[] args) {
14 | Javalin app = Javalin.start(SERVER_PORT);
15 | /////////////////////////////////////////////////////////////////////////
16 | // Part 1: Subscribe a leadgen endpoint to webhook //
17 | /////////////////////////////////////////////////////////////////////////
18 | // A token that Facebook will echo back to you as part of callback URL verification.
19 | String VERIFY_TOKEN = "YOUR_SECURE_VERIFY_TOKEN";
20 | // Endpoint for verifying webhook subscripton
21 | app.get("/leadgen", ctx -> {
22 | if (ctx.anyQueryParamNull("hub.verify_token", "hub.challenge")) {
23 | ctx.result("Missing hub.verify_token and hub.challenge params");
24 | return;
25 | }
26 | // Extract a verify token we set in the webhook subscription and a challenge to echo back.
27 | String verifyToken = ctx.queryParam("hub.verify_token");
28 | String challenge = ctx.queryParam("hub.challenge");
29 |
30 | if (!verifyToken.equals(VERIFY_TOKEN)) {
31 | ctx.result("Verify token does not match");
32 | return;
33 | }
34 | // We echo the received challenge back to Facebook to finish the verification process.
35 | ctx.result(challenge);
36 | });
37 |
38 | /////////////////////////////////////////////////////////////////////////
39 | // Part 2: Retrieving realtime leads //
40 | /////////////////////////////////////////////////////////////////////////
41 | // Graph API endpoint
42 | String GRAPH_API_VERSION = "v2.12";
43 | String GRAPH_API_ENDPOINT = "https://graph.facebook.com/" + GRAPH_API_VERSION;
44 | // Your system user access token file path.
45 | // Note: Your system user needs to be an admin of the subscribed page.
46 | String ACCESS_TOKEN_PATH = System.getProperty("user.dir") + "/token/access_token.txt";
47 | // Read access token for calling graph API.
48 | String accessTokenBuffer = null;
49 | try {
50 | Scanner sc = new Scanner(new File(ACCESS_TOKEN_PATH));
51 | accessTokenBuffer = sc.next();
52 | } catch (FileNotFoundException error) {
53 | System.out.println("The access token file does not exist. " + ACCESS_TOKEN_PATH);
54 | System.exit(0);
55 | }
56 | final String accessToken = accessTokenBuffer;
57 | // Facebook will post realtime leads to this endpoint if we've already subscribed to the webhook in part 1.
58 | app.post("/leadgen", ctx -> {
59 | JSONObject body = new JSONObject(ctx.body());
60 | JSONArray entry = body.getJSONArray("entry");
61 |
62 | for (int i = 0; i < entry.length(); i++) {
63 | JSONArray changes = entry.getJSONObject(i).getJSONArray("changes");
64 | for (int j = 0; j < changes.length(); j++) {
65 | JSONObject change = changes.getJSONObject(j).getJSONObject("value");
66 | // We get page, form, and lead IDs from the change here.
67 | // We need the lead gen ID to get the lead data.
68 | // The form ID and page ID are optional. You may want to record them into your CRM system.
69 | String pageID = change.getString("page_id");
70 | String formID = change.getString("form_id");
71 | String leadgenID = change.getString("leadgen_id");
72 | System.out.println("Page ID " + pageID + ", Form ID " + formID + ", Lead gen ID " + leadgenID);
73 |
74 | // Call graph API to request lead info with the lead ID and access token.
75 | String leadgenURI = GRAPH_API_ENDPOINT + "/" + leadgenID + "?access_token=" + accessToken;
76 | Scanner urlScanner = new Scanner(new URL(leadgenURI).openStream());
77 | // “\A” is a regex for the beginning of the input.
78 | // next() will return from the beginning all the way to the end.
79 | JSONObject response = new JSONObject(urlScanner.useDelimiter("\\A").next());
80 |
81 | String createdTime = response.getString("created_time");
82 | String id = response.getString("id");
83 | JSONArray fields = response.getJSONArray("field_data");
84 |
85 | // Handle lead answer here (insert data into your CRM system)
86 | System.out.println("Lead ID " + id);
87 | System.out.println("Created time " + createdTime);
88 | for (int k = 0; k < fields.length(); k++) {
89 | JSONObject field = fields.getJSONObject(k);
90 | String question = field.getString("name");
91 | JSONArray answers = field.getJSONArray("values");
92 |
93 | System.out.println("Question " + question);
94 | System.out.println("Answers " + answers.join(","));
95 | }
96 | }
97 | }
98 | // Send HTTP 200 OK status to indicate we've received the update.
99 | ctx.status(200);
100 | });
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/java/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------