├── .classpath ├── .gitignore ├── .project ├── CONTRIB.md ├── LICENSE ├── README.md ├── src ├── META-INF │ └── jdoconfig.xml ├── com │ └── google │ │ └── devrel │ │ └── samples │ │ └── ttt │ │ ├── Board.java │ │ ├── PMF.java │ │ ├── Score.java │ │ └── spi │ │ ├── BoardV1.java │ │ ├── Ids.java │ │ └── ScoresV1.java └── log4j.properties └── war ├── WEB-INF ├── appengine-web.xml ├── logging.properties └── web.xml ├── css └── base.css ├── favicon.ico ├── images └── caution.gif ├── index.html └── js ├── base.js └── render.js /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .DS_Store 3 | .settings 4 | *.jar 5 | *.iml 6 | *~ 7 | target/ 8 | classes/ 9 | appengine-generated/ 10 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | tictactoe-java 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | com.google.gdt.eclipse.core.webAppProjectValidator 15 | 16 | 17 | 18 | 19 | com.google.appengine.eclipse.core.enhancerbuilder 20 | 21 | 22 | 23 | 24 | com.google.appengine.eclipse.core.gaeProjectChangeNotifier 25 | 26 | 27 | 28 | 29 | com.google.appengine.eclipse.core.projectValidator 30 | 31 | 32 | 33 | 34 | 35 | org.eclipse.jdt.core.javanature 36 | com.google.appengine.eclipse.core.gaeNature 37 | 38 | 39 | -------------------------------------------------------------------------------- /CONTRIB.md: -------------------------------------------------------------------------------- 1 | # How to become a contributor and submit your own code 2 | 3 | ## Contributor License Agreements 4 | 5 | We'd love to accept your sample apps and patches! Before we can take them, we have to jump a couple of legal hurdles. 6 | 7 | Please fill out either the individual or corporate Contributor License Agreement (CLA). 8 | 9 | * If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](http://code.google.com/legal/individual-cla-v1.0.html). 10 | * If you work for a company that wants to allow you to contribute your work, then you'll need to sign a [corporate CLA](http://code.google.com/legal/corporate-cla-v1.0.html). 11 | 12 | Follow either of the two links above to access the appropriate CLA and instructions for how to sign and return it. Once we receive it, we'll be able to accept your pull requests. 13 | 14 | ## Contributing A Patch 15 | 16 | 1. Submit an issue describing your proposed change to the repo in question. 17 | 1. The repo owner will respond to your issue promptly. 18 | 1. If your proposed change is accepted, and you haven't already done so, sign a Contributor License Agreement (see details above). 19 | 1. Fork the desired repo, develop and test your code changes. 20 | 1. Ensure that your code adheres to the existing style in the sample to which you are contributing. Refer to the [Google Cloud Platform Samples Style Guide](https://github.com/GoogleCloudPlatform/Template/wiki/style.html) for the recommended coding standards for this organization. 21 | 1. Ensure that your code has an appropriate set of unit tests which all pass. 22 | 1. Submit a pull request. 23 | 24 | ## Contributing A New Sample App 25 | 26 | 1. Submit an issue to the GoogleCloudPlatform/Template repo describing your proposed sample app. 27 | 1. The Template repo owner will respond to your enhancement issue promptly. Instructional value is the top priority when evaluating new app proposals for this collection of repos. 28 | 1. If your proposal is accepted, and you haven't already done so, sign a Contributor License Agreement (see details above). 29 | 1. Create your own repo for your app following this naming convention: 30 | * {product}-{app-name}-{language} 31 | * products: appengine, compute, storage, bigquery, prediction, cloudsql 32 | * example: appengine-guestbook-python 33 | * For multi-product apps, concatenate the primary products, like this: compute-appengine-demo-suite-python. 34 | * For multi-language apps, concatenate the primary languages like this: appengine-sockets-python-java-go. 35 | 1. Clone the README.md, CONTRIB.md and LICENSE files from the GoogleCloudPlatform/Template repo. 36 | 1. Ensure that your code adheres to the existing style in the sample to which you are contributing. Refer to the [Google Cloud Platform Samples Style Guide](https://github.com/GoogleCloudPlatform/Template/wiki/style.html) for the recommended coding standards for this organization. 37 | 1. Ensure that your code has an appropriate set of unit tests which all pass. 38 | 1. Submit a request to fork your repo in GoogleCloudPlatform organizationt via your proposal issue. 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | appengine-endpoints-backend-java 2 | ================================ 3 | 4 | ![status: inactive](https://img.shields.io/badge/status-inactive-red.svg) 5 | 6 | This project is no longer actively developed or maintained. 7 | 8 | This application implements a simple backend for a Tic Tac Toe game using 9 | Google Cloud Endpoints, App Engine, and Java. 10 | 11 | ## Products 12 | - [App Engine][1] 13 | 14 | ## Language 15 | - [Java][2] 16 | 17 | ## APIs 18 | - [Google Cloud Endpoints][3] 19 | 20 | ## Setup Instructions 21 | 1. Import the project into Eclipse. 22 | 1. Make sure the App Engine SDK jars are added to the `war/WEB-INF/lib` 23 | directory, either by adding them by hand, or having Eclipse do it. (An easy) 24 | way to do this in Eclipse is to unset and reset whether or not the project 25 | uses Google App Engine. 26 | 1. Update the value of `application` in `appengine-web.xml` to the app ID you 27 | have registered in the App Engine admin console and would like to use to host 28 | your instance of this sample. 29 | 1. Update the values in `src/com/google/devrel/samples/ttt/spi/Ids.java` to 30 | reflect the respective client IDs you have registered in the 31 | [APIs Console][4]. 32 | 1. Update the value of `google.devrel.samples.ttt.CLIENT_ID` in 33 | [`war/js/render.js`][6] to reflect the web client ID you have registered in the 34 | [APIs Console][4]. 35 | 1. Run the application, and ensure it's running by visiting your local server's 36 | address (by default [localhost:8888][5].) 37 | 1. Deploy your application. 38 | 39 | 40 | [1]: https://developers.google.com/appengine 41 | [2]: http://java.com/en/ 42 | [3]: https://developers.google.com/appengine/docs/java/endpoints/ 43 | [4]: https://code.google.com/apis/console 44 | [5]: https://localhost:8888/ 45 | [6]: https://github.com/GoogleCloudPlatform/appengine-endpoints-tictactoe-java/blob/master/war/js/render.js 46 | -------------------------------------------------------------------------------- /src/META-INF/jdoconfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/com/google/devrel/samples/ttt/Board.java: -------------------------------------------------------------------------------- 1 | /* Copyright 2013 Google Inc. All Rights Reserved. 2 | * 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | 16 | package com.google.devrel.samples.ttt; 17 | 18 | /** 19 | * Defines the state of the board in a game of Tic Tac Toe. This class is only 20 | * used as a wire format. 21 | */ 22 | public class Board { 23 | /** 24 | * The current state of the board, represented as a single dimensional array, 25 | * e.g. ----X---- which represents a board with an X in the center. 26 | */ 27 | private String state; 28 | 29 | public String getState() { 30 | return state; 31 | } 32 | 33 | public void setState(String state) { 34 | this.state = state; 35 | } 36 | } -------------------------------------------------------------------------------- /src/com/google/devrel/samples/ttt/PMF.java: -------------------------------------------------------------------------------- 1 | /* Copyright 2013 Google Inc. All Rights Reserved. 2 | * 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | 16 | package com.google.devrel.samples.ttt; 17 | 18 | import javax.jdo.JDOHelper; 19 | import javax.jdo.PersistenceManagerFactory; 20 | 21 | public final class PMF { 22 | private static final PersistenceManagerFactory pmfInstance = 23 | JDOHelper.getPersistenceManagerFactory("transactions-optional"); 24 | 25 | private PMF() {} 26 | 27 | public static PersistenceManagerFactory get() { 28 | return pmfInstance; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/com/google/devrel/samples/ttt/Score.java: -------------------------------------------------------------------------------- 1 | /* Copyright 2013 Google Inc. All Rights Reserved. 2 | * 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | 16 | package com.google.devrel.samples.ttt; 17 | 18 | import java.util.Date; 19 | import javax.jdo.annotations.IdGeneratorStrategy; 20 | import javax.jdo.annotations.IdentityType; 21 | import javax.jdo.annotations.PersistenceCapable; 22 | import javax.jdo.annotations.Persistent; 23 | import javax.jdo.annotations.PrimaryKey; 24 | import com.google.appengine.api.users.User; 25 | 26 | /** 27 | * Defines an entity representing the outcome of a game of Tic Tac Toe. This 28 | * class is used as both the definition of a score in the datastore, as well as 29 | * the format of the data sent over the wire. 30 | */ 31 | @PersistenceCapable(identityType = IdentityType.APPLICATION) 32 | public class Score { 33 | @PrimaryKey 34 | @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) 35 | private Long id; 36 | 37 | /** 38 | * Who played the game. 39 | */ 40 | @Persistent 41 | private User player; 42 | 43 | /** 44 | * The outcome of the game. 45 | */ 46 | @Persistent 47 | private String outcome; 48 | 49 | /** 50 | * When the game was played. 51 | */ 52 | @Persistent 53 | private Date played; 54 | 55 | public Score(User player, String outcome, Date played) { 56 | this.player = player; 57 | this.outcome = outcome; 58 | this.played = played; 59 | } 60 | 61 | public Long getId() { 62 | return id; 63 | } 64 | 65 | public User getPlayer() { 66 | return player; 67 | } 68 | 69 | public void setPlayer(User player) { 70 | this.player = player; 71 | } 72 | 73 | public String getOutcome() { 74 | return outcome; 75 | } 76 | 77 | public void setOutcome(String outcome) { 78 | this.outcome = outcome; 79 | } 80 | 81 | public Date getPlayed() { 82 | return played; 83 | } 84 | 85 | public void setPlayed(Date played) { 86 | this.played = played; 87 | } 88 | } -------------------------------------------------------------------------------- /src/com/google/devrel/samples/ttt/spi/BoardV1.java: -------------------------------------------------------------------------------- 1 | /* Copyright 2013 Google Inc. All Rights Reserved. 2 | * 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | 16 | package com.google.devrel.samples.ttt.spi; 17 | 18 | import java.util.Random; 19 | 20 | import com.google.api.server.spi.config.Api; 21 | import com.google.api.server.spi.config.ApiMethod; 22 | import com.google.devrel.samples.ttt.Board; 23 | 24 | /** 25 | * Defines v1 of a Board resource as part of the tictactoe API, which provides 26 | * clients the ability to query for a computer's next move given an input 27 | * board. 28 | */ 29 | @Api( 30 | name = "tictactoe", 31 | version = "v1", 32 | clientIds = {Ids.WEB_CLIENT_ID, Ids.ANDROID_CLIENT_ID, Ids.IOS_CLIENT_ID}, 33 | audiences = {Ids.ANDROID_AUDIENCE} 34 | ) 35 | public class BoardV1 { 36 | public static final char X = 'X'; 37 | public static final char O = 'O'; 38 | public static final char DASH = '-'; 39 | 40 | /** 41 | * Provides the ability to insert a new Score entity. 42 | * 43 | * @param board object representing the state of the board 44 | * @return the board including the computer's move 45 | */ 46 | @ApiMethod(name = "board.getmove", httpMethod = "POST") 47 | public Board getmove(Board board) { 48 | char[][] parsed = parseBoard(board.getState()); 49 | int free = countFree(parsed); 50 | parsed = addMove(parsed, free); 51 | 52 | StringBuilder builder = new StringBuilder(); 53 | for (int i = 0; i < parsed.length; i++) { 54 | builder.append(String.valueOf(parsed[i])); 55 | } 56 | Board updated = new Board(); 57 | updated.setState(builder.toString()); 58 | return updated; 59 | } 60 | 61 | private char[][] parseBoard(String boardString) { 62 | char[][] board = new char[3][3]; 63 | char[] chars = boardString.toCharArray(); 64 | if (chars.length == 9) { 65 | for (int i = 0; i < chars.length; i++) { 66 | board[i/3][i%3] = chars[i]; 67 | } 68 | } 69 | 70 | return board; 71 | } 72 | 73 | private int countFree(char[][] board) { 74 | int count = 0; 75 | for (int i = 0; i < board.length; i++) { 76 | for (int j = 0; j < board[i].length; j++) { 77 | if (board[i][j] != X && board[i][j] != O) { 78 | count++; 79 | } 80 | } 81 | } 82 | return count; 83 | } 84 | 85 | private char[][] addMove(char[][] board, int free) { 86 | int index = new Random().nextInt(free) + 1; 87 | for (int i = 0; i < board.length; i++) { 88 | for (int j = 0; j < board.length; j++) { 89 | if (board[i][j] == DASH) { 90 | if (free == index) { 91 | board[i][j] = O; 92 | return board; 93 | } else { 94 | free--; 95 | } 96 | } 97 | } 98 | } 99 | // Only occurs when empty > the number of actual empty squares. 100 | return board; 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/com/google/devrel/samples/ttt/spi/Ids.java: -------------------------------------------------------------------------------- 1 | /* Copyright 2013 Google Inc. All Rights Reserved. 2 | * 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | 16 | package com.google.devrel.samples.ttt.spi; 17 | 18 | /** 19 | * Contains the client IDs for allowed clients consuming the tictactoe API. 20 | */ 21 | public class Ids { 22 | public static final String WEB_CLIENT_ID = "replace this with your web client application ID"; 23 | public static final String ANDROID_CLIENT_ID = "replace this with your Android client ID"; 24 | public static final String IOS_CLIENT_ID = "replace this with your iOS client ID"; 25 | public static final String ANDROID_AUDIENCE = WEB_CLIENT_ID; 26 | } 27 | -------------------------------------------------------------------------------- /src/com/google/devrel/samples/ttt/spi/ScoresV1.java: -------------------------------------------------------------------------------- 1 | /* Copyright 2013 Google Inc. All Rights Reserved. 2 | * 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | 16 | package com.google.devrel.samples.ttt.spi; 17 | 18 | import java.io.IOException; 19 | import java.util.Date; 20 | import java.util.List; 21 | 22 | import javax.annotation.Nullable; 23 | import javax.inject.Named; 24 | import javax.jdo.PersistenceManager; 25 | import javax.jdo.Query; 26 | 27 | import com.google.api.server.spi.config.Api; 28 | import com.google.api.server.spi.config.ApiMethod; 29 | import com.google.appengine.api.oauth.OAuthRequestException; 30 | import com.google.appengine.api.users.User; 31 | import com.google.devrel.samples.ttt.PMF; 32 | import com.google.devrel.samples.ttt.Score; 33 | 34 | /** 35 | * Defines v1 of a Score resource as part of the tictactoe API, which provides 36 | * clients the ability to insert and list scores. 37 | */ 38 | @Api( 39 | name = "tictactoe", 40 | version = "v1", 41 | clientIds = {Ids.WEB_CLIENT_ID, Ids.ANDROID_CLIENT_ID, Ids.IOS_CLIENT_ID}, 42 | audiences = {Ids.ANDROID_AUDIENCE} 43 | ) 44 | public class ScoresV1 { 45 | private static final String WHEN = "1"; 46 | private static final String OUTCOME = "2"; 47 | 48 | private static final String DEFAULT_LIMIT = "10"; 49 | 50 | /** 51 | * Provides the ability to query for a collection of Score entities. 52 | * 53 | * @param limit maximum number of entries to return 54 | * @param order how the entries should be ordered 55 | * @param user object representing the current user making requests 56 | * @return the collection of Score entities 57 | * @throws OAuthRequestException if the token included in the request is 58 | * invalid, the client ID included in the token is not in the list of 59 | * allowed clientIds, or the audience included in the token is not in 60 | * the list of allowed audiences. 61 | * @throws IOException 62 | */ 63 | @ApiMethod(name = "scores.list") 64 | @SuppressWarnings("unchecked") 65 | public List list(@Nullable @Named("limit") String limit, @Nullable 66 | @Named("order") String order, User user) throws OAuthRequestException, 67 | IOException { 68 | PersistenceManager pm = getPersistenceManager(); 69 | Query query = pm.newQuery(Score.class); 70 | if (order != null) { 71 | if (order.equals(WHEN)) { 72 | query.setOrdering("played desc"); 73 | } else if (order.equals(OUTCOME)) { 74 | query.setOrdering("outcome asc"); 75 | } 76 | } else { 77 | query.setOrdering("played desc"); 78 | } 79 | 80 | if (user != null) { 81 | query.setFilter("player == userParam"); 82 | query.declareParameters("com.google.appengine.api.users.User userParam"); 83 | } else { 84 | throw new OAuthRequestException("Invalid user."); 85 | } 86 | 87 | if (limit == null) { 88 | limit = DEFAULT_LIMIT; 89 | } 90 | query.setRange(0, new Long(limit)); 91 | 92 | return (List) pm.newQuery(query).execute(user); 93 | } 94 | 95 | /** 96 | * Provides the ability to insert a new Score entity. 97 | * 98 | * @param score object representing the outcome to save 99 | * @param user object representing the current user making requests 100 | * @return the object that was saved 101 | * @throws OAuthRequestException if the token included in the request is 102 | * invalid, the client ID included in the token is not in the list of 103 | * allowed clientIds, or the audience included in the token is not in 104 | * the list of allowed audiences. 105 | * @throws IOException 106 | */ 107 | @ApiMethod(name = "scores.insert") 108 | public Score insert(Score score, User user) throws 109 | OAuthRequestException, IOException { 110 | if (user != null) { 111 | score.setPlayed(new Date()); 112 | score.setPlayer(user); 113 | PersistenceManager pm = getPersistenceManager(); 114 | pm.makePersistent(score); 115 | pm.close(); 116 | return score; 117 | } else { 118 | throw new OAuthRequestException("Invalid user."); 119 | } 120 | } 121 | 122 | private static PersistenceManager getPersistenceManager() { 123 | return PMF.get().getPersistenceManager(); 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /src/log4j.properties: -------------------------------------------------------------------------------- 1 | # A default log4j configuration for log4j users. 2 | # 3 | # To use this configuration, deploy it into your application's WEB-INF/classes 4 | # directory. You are also encouraged to edit it as you like. 5 | 6 | # Configure the console as our one appender 7 | log4j.appender.A1=org.apache.log4j.ConsoleAppender 8 | log4j.appender.A1.layout=org.apache.log4j.PatternLayout 9 | log4j.appender.A1.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p [%c] - %m%n 10 | 11 | # tighten logging on the DataNucleus Categories 12 | log4j.category.DataNucleus.JDO=WARN, A1 13 | log4j.category.DataNucleus.Persistence=WARN, A1 14 | log4j.category.DataNucleus.Cache=WARN, A1 15 | log4j.category.DataNucleus.MetaData=WARN, A1 16 | log4j.category.DataNucleus.General=WARN, A1 17 | log4j.category.DataNucleus.Utility=WARN, A1 18 | log4j.category.DataNucleus.Transaction=WARN, A1 19 | log4j.category.DataNucleus.Datastore=WARN, A1 20 | log4j.category.DataNucleus.ClassLoading=WARN, A1 21 | log4j.category.DataNucleus.Plugin=WARN, A1 22 | log4j.category.DataNucleus.ValueGeneration=WARN, A1 23 | log4j.category.DataNucleus.Enhancer=WARN, A1 24 | log4j.category.DataNucleus.SchemaTool=WARN, A1 25 | -------------------------------------------------------------------------------- /war/WEB-INF/appengine-web.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | your-app-id 4 | 1 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /war/WEB-INF/logging.properties: -------------------------------------------------------------------------------- 1 | # A default java.util.logging configuration. 2 | # (All App Engine logging is through java.util.logging by default). 3 | # 4 | # To use this configuration, copy it into your application's WEB-INF 5 | # folder and add the following to your appengine-web.xml: 6 | # 7 | # 8 | # 9 | # 10 | # 11 | 12 | # Set the default logging level for all loggers to WARNING 13 | .level = WARNING 14 | -------------------------------------------------------------------------------- /war/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | SystemServiceServlet 4 | com.google.api.server.spi.SystemServiceServlet 5 | 6 | services 7 | com.google.devrel.samples.ttt.spi.BoardV1,com.google.devrel.samples.ttt.spi.ScoresV1 8 | 9 | 10 | 11 | SystemServiceServlet 12 | /_ah/spi/* 13 | 14 | 15 | index.html 16 | 17 | 18 | 19 | 20 | 21 | / 22 | 23 | 24 | CONFIDENTIAL 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /war/css/base.css: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2010-2013 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | @import url(https://fonts.googleapis.com/css?family=Open+Sans); 18 | 19 | body { 20 | margin: 0px; 21 | padding: 0px; 22 | font-size: 18pt; 23 | font-family: "Open Sans", "Helvetica", "Arial"; 24 | } 25 | #content { 26 | width: 100%; 27 | } 28 | #signin { 29 | display: -webkit-box; 30 | -webkit-box-orient: horizontal; 31 | display: -moz-box; 32 | -moz-box-orient: horizontal; 33 | display: box; 34 | box-orient: horizontal; 35 | padding: 1em; 36 | background-color: whiteSmoke; 37 | border-bottom: 1pt solid #E5E5E5; 38 | } 39 | #board, #warning { 40 | margin: 1em; 41 | display: -webkit-box; 42 | -webkit-box-orient: vertical; 43 | -webkit-box-align: center; 44 | display: -moz-box; 45 | -moz-box-orient: vertical; 46 | -moz-box-align: center; 47 | display: box; 48 | box-orient: vertical; 49 | box-align: center; 50 | } 51 | #gameHistoryWrapper { 52 | background-color: whiteSmoke; 53 | } 54 | #victory { 55 | height: 1em; 56 | padding: 5pt; 57 | font-weight: bold; 58 | } 59 | 60 | /* Initial element visibility */ 61 | .hidden { 62 | display: none !important; 63 | } 64 | 65 | /* Signin styles */ 66 | #signinStatusContainer { 67 | -webkit-box-flex: 1; 68 | -moz-box-flex: 1; 69 | box-flex: 1; 70 | display: -webkit-box; 71 | display: -moz-box; 72 | display: box; 73 | } 74 | 75 | #signinStatusContainer > :not(.visible) { 76 | display: none; 77 | } 78 | 79 | /* Board styles */ 80 | table { 81 | text-align: center; 82 | padding: 5pt 0pt; 83 | border-spacing: 0pt; 84 | } 85 | td { 86 | width: 5em; 87 | height: 5em; 88 | border: 2pt solid #000; 89 | -webkit-transition: all .1s; 90 | -moz-transition: all .1s; 91 | transition: all .1s; 92 | } 93 | td:hover { 94 | background: #D3E3E8; 95 | } 96 | td:active { 97 | background: #CFF4FF; 98 | } 99 | td.noTop { 100 | border-top: 0pt; 101 | } 102 | td.noLeft { 103 | border-left: 0pt; 104 | } 105 | td.noRight { 106 | border-right: 0pt; 107 | } 108 | td.noBottom { 109 | border-bottom: 0pt; 110 | } 111 | 112 | /* Game history styles */ 113 | #gameHistoryWrapper h2 { 114 | font-size: 14pt; 115 | font-weight: bold; 116 | padding: 1em; 117 | margin: 0pt; 118 | background-color: lightSlateGray; 119 | color: #white; 120 | } 121 | #gameHistoryWrapper ul { 122 | font-size: 12pt; 123 | font-weight: bold; 124 | padding: 0pt; 125 | margin: 0pt; 126 | list-style-type: none; 127 | } 128 | #gameHistoryWrapper li { 129 | padding: 5pt 0pt 5pt 2em; 130 | margin: 0pt; 131 | background-color: whiteSmoke; 132 | } 133 | #gameHistoryWrapper li:nth-child(even) { 134 | padding: 5pt 0pt 5pt 2em; 135 | margin: 0pt; 136 | background-color: #D5D5D5; 137 | } 138 | -------------------------------------------------------------------------------- /war/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GoogleCloudPlatform/appengine-endpoints-tictactoe-java/fe8d6bcb0a6e0fd8df800c8ea3791e4f97fe1fee/war/favicon.ico -------------------------------------------------------------------------------- /war/images/caution.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GoogleCloudPlatform/appengine-endpoints-tictactoe-java/fe8d6bcb0a6e0fd8df800c8ea3791e4f97fe1fee/war/images/caution.gif -------------------------------------------------------------------------------- /war/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | TicTacToe 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 |
14 |
15 | 16 |
17 |
18 |
19 | Sign Out 20 |
21 | (not signed in) 22 |
23 |
24 | 25 |

You must sign in to play!

26 |
27 | 48 | 52 |
53 | 54 | 55 | -------------------------------------------------------------------------------- /war/js/base.js: -------------------------------------------------------------------------------- 1 | // Copyright 2012 Google Inc. All Rights Reserved. 2 | 3 | /** 4 | * @fileoverview 5 | * Provides methods for the TicTacToe sample UI and interaction with the 6 | * TicTacToe API. 7 | * 8 | * @author danielholevoet@google.com (Dan Holevoet) 9 | */ 10 | 11 | /** google global namespace for Google projects. */ 12 | var google = google || {}; 13 | 14 | /** devrel namespace for Google Developer Relations projects. */ 15 | google.devrel = google.devrel || {}; 16 | 17 | /** samples namespace for DevRel sample code. */ 18 | google.devrel.samples = google.devrel.samples || {}; 19 | 20 | /** TicTacToe namespace for this sample. */ 21 | google.devrel.samples.ttt = google.devrel.samples.ttt || {}; 22 | 23 | /** 24 | * Status for an unfinished game. 25 | * @type {number} 26 | */ 27 | google.devrel.samples.ttt.NOT_DONE = 0; 28 | 29 | /** 30 | * Status for a victory. 31 | * @type {number} 32 | */ 33 | google.devrel.samples.ttt.WON = 1; 34 | 35 | /** 36 | * Status for a loss. 37 | * @type {number} 38 | */ 39 | google.devrel.samples.ttt.LOST = 2; 40 | 41 | /** 42 | * Status for a tie. 43 | * @type {number} 44 | */ 45 | google.devrel.samples.ttt.TIE = 3; 46 | 47 | /** 48 | * Strings for each numerical status. 49 | * @type {Array.number} 50 | */ 51 | google.devrel.samples.ttt.STATUS_STRINGS = [ 52 | 'NOT_DONE', 53 | 'WON', 54 | 'LOST', 55 | 'TIE' 56 | ]; 57 | 58 | /** 59 | * Whether or not the user is signed in. 60 | * @type {boolean} 61 | */ 62 | google.devrel.samples.ttt.signedIn = false; 63 | 64 | /** 65 | * Whether or not the game is waiting for a user's move. 66 | * @type {boolean} 67 | */ 68 | google.devrel.samples.ttt.waitingForMove = true; 69 | 70 | /** 71 | * Signs the user out. 72 | */ 73 | google.devrel.samples.ttt.signout = function() { 74 | document.getElementById('signinButtonContainer').classList.add('visible'); 75 | document.getElementById('signedInStatus').classList.remove('visible'); 76 | google.devrel.samples.ttt.setBoardEnablement(false); 77 | google.devrel.samples.ttt.signedIn = false; 78 | } 79 | 80 | /** 81 | * Handles a square click. 82 | * @param {MouseEvent} e Mouse click event. 83 | */ 84 | google.devrel.samples.ttt.clickSquare = function(e) { 85 | if (google.devrel.samples.ttt.waitingForMove) { 86 | var button = e.target; 87 | button.innerHTML = 'X'; 88 | button.removeEventListener('click', google.devrel.samples.ttt.clickSquare); 89 | google.devrel.samples.ttt.waitingForMove = false; 90 | 91 | var boardString = google.devrel.samples.ttt.getBoardString(); 92 | var status = google.devrel.samples.ttt.checkForVictory(boardString); 93 | if (status == google.devrel.samples.ttt.NOT_DONE) { 94 | google.devrel.samples.ttt.getComputerMove(boardString); 95 | } else { 96 | google.devrel.samples.ttt.handleFinish(status); 97 | } 98 | } 99 | }; 100 | 101 | /** 102 | * Resets the game board. 103 | */ 104 | google.devrel.samples.ttt.resetGame = function() { 105 | var buttons = document.querySelectorAll('td'); 106 | for (var i = 0; i < buttons.length; i++) { 107 | var button = buttons[i]; 108 | button.removeEventListener('click', google.devrel.samples.ttt.clickSquare); 109 | button.addEventListener('click', google.devrel.samples.ttt.clickSquare); 110 | button.innerHTML = '-'; 111 | } 112 | document.getElementById('victory').innerHTML = ''; 113 | google.devrel.samples.ttt.waitingForMove = true; 114 | }; 115 | 116 | /** 117 | * Gets the computer's move. 118 | * @param {string} boardString Current state of the board. 119 | */ 120 | google.devrel.samples.ttt.getComputerMove = function(boardString) { 121 | gapi.client.tictactoe.board.getmove({'state': boardString}).execute( 122 | function(resp) { 123 | google.devrel.samples.ttt.setBoardFilling(resp.state); 124 | var status = google.devrel.samples.ttt.checkForVictory(resp.state); 125 | if (status != google.devrel.samples.ttt.NOT_DONE) { 126 | google.devrel.samples.ttt.handleFinish(status); 127 | } else { 128 | google.devrel.samples.ttt.waitingForMove = true; 129 | } 130 | }); 131 | }; 132 | 133 | /** 134 | * Sends the result of the game to the server. 135 | * @param {number} status Result of the game. 136 | */ 137 | google.devrel.samples.ttt.sendResultToServer = function(status) { 138 | gapi.client.tictactoe.scores.insert({'outcome': 139 | google.devrel.samples.ttt.STATUS_STRINGS[status]}).execute( 140 | function(resp) { 141 | google.devrel.samples.ttt.queryScores(); 142 | }); 143 | }; 144 | 145 | /** 146 | * Queries for results of previous games. 147 | */ 148 | google.devrel.samples.ttt.queryScores = function() { 149 | gapi.client.tictactoe.scores.list().execute(function(resp) { 150 | var history = document.getElementById('gameHistory'); 151 | history.innerHTML = ''; 152 | if (resp.items) { 153 | for (var i = 0; i < resp.items.length; i++) { 154 | var score = document.createElement('li'); 155 | score.innerHTML = resp.items[i].outcome; 156 | history.appendChild(score); 157 | } 158 | } 159 | }); 160 | }; 161 | 162 | /** 163 | * Shows or hides the board and game elements. 164 | * @param {boolean} state Whether to show or hide the board elements. 165 | */ 166 | google.devrel.samples.ttt.setBoardEnablement = function(state) { 167 | if (!state) { 168 | document.getElementById('board').classList.add('hidden'); 169 | document.getElementById('gameHistoryWrapper').classList.add('hidden'); 170 | document.getElementById('warning').classList.remove('hidden'); 171 | } else { 172 | document.getElementById('board').classList.remove('hidden'); 173 | document.getElementById('gameHistoryWrapper').classList.remove('hidden'); 174 | document.getElementById('warning').classList.add('hidden'); 175 | } 176 | }; 177 | 178 | /** 179 | * Sets the filling of the squares of the board. 180 | * @param {string} boardString Current state of the board. 181 | */ 182 | google.devrel.samples.ttt.setBoardFilling = function(boardString) { 183 | var buttons = document.querySelectorAll('td'); 184 | for (var i = 0; i < buttons.length; i++) { 185 | var button = buttons[i]; 186 | button.innerHTML = boardString.charAt(i); 187 | } 188 | }; 189 | 190 | /** 191 | * Checks for a victory condition. 192 | * @param {string} boardString Current state of the board. 193 | * @return {number} Status code for the victory state. 194 | */ 195 | google.devrel.samples.ttt.checkForVictory = function(boardString) { 196 | var status = google.devrel.samples.ttt.NOT_DONE; 197 | 198 | // Checks rows and columns. 199 | for (var i = 0; i < 3; i++) { 200 | var rowString = google.devrel.samples.ttt.getStringsAtPositions( 201 | boardString, i*3, (i*3)+1, (i*3)+2); 202 | status |= google.devrel.samples.ttt.checkSectionVictory(rowString); 203 | 204 | var colString = google.devrel.samples.ttt.getStringsAtPositions( 205 | boardString, i, i+3, i+6); 206 | status |= google.devrel.samples.ttt.checkSectionVictory(colString); 207 | } 208 | 209 | // Check top-left to bottom-right. 210 | var diagonal = google.devrel.samples.ttt.getStringsAtPositions(boardString, 211 | 0, 4, 8); 212 | status |= google.devrel.samples.ttt.checkSectionVictory(diagonal); 213 | 214 | // Check top-right to bottom-left. 215 | diagonal = google.devrel.samples.ttt.getStringsAtPositions(boardString, 2, 216 | 4, 6); 217 | status |= google.devrel.samples.ttt.checkSectionVictory(diagonal); 218 | 219 | if (status == google.devrel.samples.ttt.NOT_DONE) { 220 | if (boardString.indexOf('-') == -1) { 221 | return google.devrel.samples.ttt.TIE; 222 | } 223 | } 224 | 225 | return status; 226 | }; 227 | 228 | /** 229 | * Checks whether a set of three squares are identical. 230 | * @param {string} section Set of three squares to check. 231 | * @return {number} Status code for the victory state. 232 | */ 233 | google.devrel.samples.ttt.checkSectionVictory = function(section) { 234 | var a = section.charAt(0); 235 | var b = section.charAt(1); 236 | var c = section.charAt(2); 237 | if (a == b && a == c) { 238 | if (a == 'X') { 239 | return google.devrel.samples.ttt.WON; 240 | } else if (a == 'O') { 241 | return google.devrel.samples.ttt.LOST 242 | } 243 | } 244 | return google.devrel.samples.ttt.NOT_DONE; 245 | }; 246 | 247 | /** 248 | * Handles the end of the game. 249 | * @param {number} status Status code for the victory state. 250 | */ 251 | google.devrel.samples.ttt.handleFinish = function(status) { 252 | var victory = document.getElementById('victory'); 253 | if (status == google.devrel.samples.ttt.WON) { 254 | victory.innerHTML = 'You win!'; 255 | } else if (status == google.devrel.samples.ttt.LOST) { 256 | victory.innerHTML = 'You lost!'; 257 | } else { 258 | victory.innerHTML = 'You tied!'; 259 | } 260 | google.devrel.samples.ttt.sendResultToServer(status); 261 | }; 262 | 263 | /** 264 | * Gets the current representation of the board. 265 | * @return {string} Current state of the board. 266 | */ 267 | google.devrel.samples.ttt.getBoardString = function() { 268 | var boardStrings = []; 269 | var buttons = document.querySelectorAll('td'); 270 | for (var i = 0; i < buttons.length; i++) { 271 | boardStrings.push(buttons[i].innerHTML); 272 | } 273 | return boardStrings.join(''); 274 | }; 275 | 276 | /** 277 | * Gets the values of the board at the given positions. 278 | * @param {string} boardString Current state of the board. 279 | * @param {number} first First element to retrieve. 280 | * @param {number} second Second element to retrieve. 281 | * @param {number} third Third element to retrieve. 282 | */ 283 | google.devrel.samples.ttt.getStringsAtPositions = function(boardString, first, 284 | second, third) { 285 | return [boardString.charAt(first), 286 | boardString.charAt(second), 287 | boardString.charAt(third)].join(''); 288 | }; 289 | 290 | /** 291 | * Initializes the application. 292 | * @param {string} apiRoot Root of the API's path. 293 | * @param {string} tokenEmail The email parsed from the auth/ID token. 294 | */ 295 | google.devrel.samples.ttt.init = function(apiRoot, tokenEmail) { 296 | // Loads the Tic Tac Toe API asynchronously, and triggers login 297 | // in the UI when loading has completed. 298 | var callback = function() { 299 | google.devrel.samples.ttt.signedIn = true; 300 | document.getElementById('userLabel').innerHTML = tokenEmail; 301 | google.devrel.samples.ttt.setBoardEnablement(true); 302 | google.devrel.samples.ttt.queryScores(); 303 | } 304 | gapi.client.load('tictactoe', 'v1', callback, apiRoot); 305 | 306 | var buttons = document.querySelectorAll('td'); 307 | for (var i = 0; i < buttons.length; i++) { 308 | var button = buttons[i]; 309 | button.addEventListener('click', google.devrel.samples.ttt.clickSquare); 310 | } 311 | 312 | var reset = document.querySelector('#restartButton'); 313 | reset.addEventListener('click', google.devrel.samples.ttt.resetGame); 314 | }; 315 | -------------------------------------------------------------------------------- /war/js/render.js: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Google Inc. All Rights Reserved. 2 | 3 | /** 4 | * @fileoverview 5 | * Provides methods for the utility methods needed to render the Google+ 6 | * Sign-In button. 7 | * 8 | * @author dhermes@google.com (Danny Hermes) 9 | */ 10 | 11 | /** google global namespace for Google projects. */ 12 | var google = google || {}; 13 | 14 | /** devrel namespace for Google Developer Relations projects. */ 15 | google.devrel = google.devrel || {}; 16 | 17 | /** samples namespace for DevRel sample code. */ 18 | google.devrel.samples = google.devrel.samples || {}; 19 | 20 | /** TicTacToe namespace for this sample. */ 21 | google.devrel.samples.ttt = google.devrel.samples.ttt || {}; 22 | 23 | /** 24 | * Client ID of the application (from the APIs Console). 25 | * @type {string} 26 | */ 27 | google.devrel.samples.ttt.CLIENT_ID = 28 | 'YOUR-CLIENT-ID'; 29 | 30 | /** 31 | * Scopes used by the application. 32 | * @type {string} 33 | */ 34 | google.devrel.samples.ttt.SCOPES = 35 | 'https://www.googleapis.com/auth/userinfo.email ' + 36 | 'https://www.googleapis.com/auth/plus.login'; 37 | 38 | /** 39 | * Parses email from the claim set of a JWT ID token. 40 | * 41 | * NOTE: We are not validating the ID token since from a trusted source. 42 | * We are simply parsed the value from the JWT. 43 | * 44 | * See http://www.tbray.org/ongoing/When/201x/2013/04/04/ID-Tokens 45 | * or 46 | * http://openid.net/specs/openid-connect-messages-1_0.html#StandardClaims 47 | * for more info. 48 | * 49 | * @param {string} idToken A base64 JWT containing a user ID token. 50 | * @return {string} The email parsed from the claim set, else undefined 51 | * if one can't be parsed. 52 | */ 53 | google.devrel.samples.ttt.getEmailFromIDToken = function(idToken) { 54 | if (typeof idToken !== 'string') { 55 | return; 56 | } 57 | 58 | var segments = idToken.split('.'); 59 | if (segments.length !== 3) { 60 | return; 61 | } 62 | 63 | try { 64 | var claimSet = JSON.parse(atob(segments[1])); 65 | } catch (e) { 66 | return; 67 | } 68 | 69 | if (claimSet.email && typeof claimSet.email === 'string') { 70 | return claimSet.email; 71 | } 72 | } 73 | 74 | /** 75 | * Handles the Google+ Sign In response. 76 | * 77 | * Success calls google.devrel.samples.ttt.init. Failure makes the Sign-In 78 | * button visible. 79 | * 80 | * @param {Object} authResult The contents returned from the Google+ 81 | * Sign In attempt. 82 | */ 83 | google.devrel.samples.ttt.signinCallback = function(authResult) { 84 | var tokenEmail = google.devrel.samples.ttt.getEmailFromIDToken( 85 | authResult.id_token); 86 | if (authResult.access_token && tokenEmail) { 87 | google.devrel.samples.ttt.init('//' + window.location.host + '/_ah/api', 88 | tokenEmail); 89 | 90 | document.getElementById('signinButtonContainer').classList.remove( 91 | 'visible'); 92 | document.getElementById('signedInStatus').classList.add('visible'); 93 | } else { 94 | document.getElementById('signinButtonContainer').classList.add('visible'); 95 | document.getElementById('signedInStatus').classList.remove('visible'); 96 | 97 | if (!authResult.error) { 98 | console.log('Unexpected result'); 99 | console.log(authResult); 100 | } else if (authResult.error !== 'immediate_failed') { 101 | console.log('Unexpected error occured: ' + authResult.error); 102 | } else { 103 | console.log('Immediate mode failed, user needs to click Sign In.'); 104 | } 105 | } 106 | }; 107 | 108 | /** 109 | * Renders the Google+ Sign-in button using auth parameters. 110 | */ 111 | google.devrel.samples.ttt.render = function() { 112 | gapi.signin.render('signinButton', { 113 | 'callback': google.devrel.samples.ttt.signinCallback, 114 | 'clientid': google.devrel.samples.ttt.CLIENT_ID, 115 | 'cookiepolicy': 'single_host_origin', 116 | 'requestvisibleactions': 'http://schemas.google.com/AddActivity', 117 | 'scope': google.devrel.samples.ttt.SCOPES 118 | }); 119 | }; 120 | // A quirk of the JSONP callback of the plusone client makes it so 121 | // our callback must exist as an element in window. 122 | window['google.devrel.samples.ttt.render'] = google.devrel.samples.ttt.render; 123 | 124 | // Recommended code to load Google+ JS library. 125 | (function() { 126 | var newScriptElement = document.createElement('script'); 127 | newScriptElement.type = 'text/javascript'; 128 | newScriptElement.async = true; 129 | newScriptElement.src = 'https://apis.google.com/js/client:plusone.js' + 130 | '?onload=google.devrel.samples.ttt.render'; 131 | var firstScriptElement = document.getElementsByTagName('script')[0]; 132 | firstScriptElement.parentNode.insertBefore(newScriptElement, 133 | firstScriptElement); 134 | })(); 135 | --------------------------------------------------------------------------------