|
| 1 | +/* |
| 2 | + * Copyright 2018 Google LLC |
| 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 | +package com.google.example.datastore; |
| 18 | + |
| 19 | +import com.google.appengine.api.appidentity.AppIdentityService; |
| 20 | +import com.google.appengine.api.appidentity.AppIdentityServiceFactory; |
| 21 | +import com.google.apphosting.api.ApiProxy; |
| 22 | +import com.google.common.io.CharStreams; |
| 23 | +import java.io.IOException; |
| 24 | +import java.io.InputStream; |
| 25 | +import java.io.InputStreamReader; |
| 26 | +import java.io.OutputStreamWriter; |
| 27 | +import java.net.HttpURLConnection; |
| 28 | +import java.net.URL; |
| 29 | +import java.nio.charset.StandardCharsets; |
| 30 | +import java.text.SimpleDateFormat; |
| 31 | +import java.util.ArrayList; |
| 32 | +import java.util.Date; |
| 33 | +import java.util.logging.Logger; |
| 34 | +import javax.servlet.annotation.WebServlet; |
| 35 | +import javax.servlet.http.HttpServlet; |
| 36 | +import javax.servlet.http.HttpServletRequest; |
| 37 | +import javax.servlet.http.HttpServletResponse; |
| 38 | +import org.json.JSONArray; |
| 39 | +import org.json.JSONObject; |
| 40 | +import org.json.JSONTokener; |
| 41 | + |
| 42 | +@WebServlet(name = "DatastoreExportServlet", value = "/cloud-datastore-export") |
| 43 | +public class DatastoreExportServlet extends HttpServlet { |
| 44 | + |
| 45 | + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); |
| 46 | + |
| 47 | + private static final Logger log = Logger.getLogger(DatastoreExportServlet.class.getName()); |
| 48 | + |
| 49 | + @Override |
| 50 | + public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { |
| 51 | + |
| 52 | + // Validate outputURL parameter |
| 53 | + String outputUrlPrefix = request.getParameter("output_url_prefix"); |
| 54 | + |
| 55 | + if (outputUrlPrefix == null || !outputUrlPrefix.matches("^gs://.*")) { |
| 56 | + // Send error response if outputURL not set or not a Cloud Storage bucket |
| 57 | + response.setStatus(HttpServletResponse.SC_CONFLICT); |
| 58 | + response.setContentType("text/plain"); |
| 59 | + response.getWriter().println("Error: Must provide a valid output_url_prefix."); |
| 60 | + |
| 61 | + } else { |
| 62 | + |
| 63 | + // Put together export request headers |
| 64 | + URL url = new URL("https://datastore.googleapis.com/v1/projects/" + PROJECT_ID + ":export"); |
| 65 | + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); |
| 66 | + connection.setDoOutput(true); |
| 67 | + connection.setRequestMethod("POST"); |
| 68 | + connection.addRequestProperty("Content-Type", "application/json"); |
| 69 | + |
| 70 | + // Get an access token to authorize export request |
| 71 | + ArrayList<String> scopes = new ArrayList<String>(); |
| 72 | + scopes.add("https://www.googleapis.com/auth/datastore"); |
| 73 | + final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService(); |
| 74 | + final AppIdentityService.GetAccessTokenResult accessToken = |
| 75 | + AppIdentityServiceFactory.getAppIdentityService().getAccessToken(scopes); |
| 76 | + connection.addRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken()); |
| 77 | + |
| 78 | + // Build export request payload based on URL parameters |
| 79 | + // Required: output_url_prefix |
| 80 | + // Optional: entity filter |
| 81 | + JSONObject exportRequest = new JSONObject(); |
| 82 | + |
| 83 | + // If output prefix ends with a slash, use as-is |
| 84 | + // Otherwise, add a timestamp to form unique output url |
| 85 | + if (!outputUrlPrefix.endsWith("/")) { |
| 86 | + String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); |
| 87 | + outputUrlPrefix = outputUrlPrefix + "/" + timeStamp + "/"; |
| 88 | + } |
| 89 | + |
| 90 | + // Add outputUrl to payload |
| 91 | + exportRequest.put("output_url_prefix", outputUrlPrefix); |
| 92 | + |
| 93 | + // Build optional entity filter to export subset of |
| 94 | + // kinds or namespaces |
| 95 | + JSONObject entityFilter = new JSONObject(); |
| 96 | + |
| 97 | + // Read kind parameters and add to export request if not null |
| 98 | + String[] kinds = request.getParameterValues("kind"); |
| 99 | + if (kinds != null) { |
| 100 | + JSONArray kindsJson = new JSONArray(kinds); |
| 101 | + entityFilter.put("kinds", kinds); |
| 102 | + } |
| 103 | + |
| 104 | + // Read namespace parameters and add to export request if not null |
| 105 | + String[] namespaces = request.getParameterValues("namespace_id"); |
| 106 | + if (namespaces != null) { |
| 107 | + JSONArray namespacesJson = new JSONArray(namespaces); |
| 108 | + entityFilter.put("namespaceIds", namespacesJson); |
| 109 | + } |
| 110 | + |
| 111 | + // Add entity filter to payload |
| 112 | + // Finish export request payload |
| 113 | + exportRequest.put("entityFilter", entityFilter); |
| 114 | + |
| 115 | + // Send export request |
| 116 | + OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); |
| 117 | + exportRequest.write(writer); |
| 118 | + writer.close(); |
| 119 | + |
| 120 | + // Examine server's response |
| 121 | + if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { |
| 122 | + // Request failed, log errors and return |
| 123 | + InputStream s = connection.getErrorStream(); |
| 124 | + InputStreamReader r = new InputStreamReader(s, StandardCharsets.UTF_8); |
| 125 | + String errorMessage = |
| 126 | + String.format( |
| 127 | + "got error (%d) response %s from %s", |
| 128 | + connection.getResponseCode(), CharStreams.toString(r), connection.toString()); |
| 129 | + log.warning(errorMessage); |
| 130 | + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); |
| 131 | + response.setContentType("text/plain"); |
| 132 | + response.getWriter().println( |
| 133 | + "Failed to initiate export."); |
| 134 | + return; |
| 135 | + } |
| 136 | + |
| 137 | + // Success, print export operation information |
| 138 | + JSONObject exportResponse = new JSONObject(new JSONTokener(connection.getInputStream())); |
| 139 | + |
| 140 | + response.setContentType("text/plain"); |
| 141 | + response.getWriter().println( |
| 142 | + "Export started:\n" + exportResponse.toString(4)); |
| 143 | + } |
| 144 | + } |
| 145 | +} |
0 commit comments