Search in sources :

Example 1 with AppIdentityService

use of com.google.appengine.api.appidentity.AppIdentityService in project getting-started-java by GoogleCloudPlatform.

the class LaunchDataflowTemplate method doGet.

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String project = "YOUR_PROJECT_NAME";
    String bucket = "gs://YOUR_BUCKET_NAME";
    ArrayList<String> scopes = new ArrayList<String>();
    scopes.add("https://www.googleapis.com/auth/cloud-platform");
    final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
    final AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes);
    JSONObject jsonObj = null;
    try {
        JSONObject parameters = new JSONObject().put("datastoreReadGqlQuery", "SELECT * FROM Entries").put("datastoreReadProjectId", project).put("textWritePrefix", bucket + "/output/");
        JSONObject environment = new JSONObject().put("tempLocation", bucket + "/tmp/").put("bypassTempDirValidation", false);
        jsonObj = new JSONObject().put("jobName", "template-" + UUID.randomUUID().toString()).put("parameters", parameters).put("environment", environment);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    URL url = new URL(String.format("https://dataflow.googleapis.com/v1b3/projects/%s/templates" + ":launch?gcs_path=gs://dataflow-templates/latest/Datastore_to_GCS_Text", project));
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken());
    conn.setRequestProperty("Content-Type", "application/json");
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    jsonObj.write(writer);
    writer.close();
    int respCode = conn.getResponseCode();
    if (respCode == HttpURLConnection.HTTP_OK) {
        response.setContentType("application/json");
        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = reader.readLine()) != null) {
            response.getWriter().println(line);
        }
        reader.close();
    } else {
        StringWriter w = new StringWriter();
        IOUtils.copy(conn.getErrorStream(), w, "UTF-8");
        response.getWriter().println(w.toString());
    }
}
Also used : AppIdentityService(com.google.appengine.api.appidentity.AppIdentityService) InputStreamReader(java.io.InputStreamReader) ArrayList(java.util.ArrayList) JSONException(org.json.JSONException) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) JSONObject(org.json.JSONObject) StringWriter(java.io.StringWriter) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter)

Example 2 with AppIdentityService

use of com.google.appengine.api.appidentity.AppIdentityService in project java-docs-samples by GoogleCloudPlatform.

the class GaeInfoServlet method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String key = "";
    final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
    WebContext ctx = new WebContext(req, resp, getServletContext(), req.getLocale());
    resp.setContentType("text/html");
    ctx.setVariable("production", SystemProperty.environment.value().name());
    ctx.setVariable("ServiceAccountName", appIdentity.getServiceAccountName());
    ctx.setVariable("gcs", appIdentity.getDefaultGcsBucketName());
    ctx.setVariable("appId", SystemProperty.applicationId.get());
    ctx.setVariable("appVer", SystemProperty.applicationVersion.get());
    ctx.setVariable("version", SystemProperty.version.get());
    ctx.setVariable("environment", SystemProperty.environment.get());
    // Environment Atributes
    ApiProxy.Environment env = ApiProxy.getCurrentEnvironment();
    Map<String, Object> attr = env.getAttributes();
    TreeMap<String, String> m = new TreeMap<>();
    for (String k : attr.keySet()) {
        Object o = attr.get(k);
        if (o.getClass().getCanonicalName().equals("java.lang.String")) {
            m.put(k, (String) o);
        } else if (o.getClass().getCanonicalName().equals("java.lang.Boolean")) {
            m.put(k, ((Boolean) o).toString());
        } else {
            m.put(k, "a " + o.getClass().getCanonicalName());
        }
    }
    ctx.setVariable("attribs", m);
    m = new TreeMap<>();
    for (Enumeration<String> e = req.getHeaderNames(); e.hasMoreElements(); ) {
        key = e.nextElement();
        m.put(key, req.getHeader(key));
    }
    ctx.setVariable("headers", m);
    Cookie[] cookies = req.getCookies();
    m = new TreeMap<>();
    if (cookies != null && cookies.length != 0) {
        for (Cookie co : cookies) {
            m.put(co.getName(), co.getValue());
        }
    }
    ctx.setVariable("cookies", m);
    Properties properties = System.getProperties();
    m = new TreeMap<>();
    for (Enumeration e = properties.propertyNames(); e.hasMoreElements(); ) {
        key = (String) e.nextElement();
        m.put(key, (String) properties.get(key));
    }
    ctx.setVariable("systemprops", m);
    Map<String, String> envVar = System.getenv();
    m = new TreeMap<>(envVar);
    ctx.setVariable("envvar", m);
    // The metadata server is only on a production system
    if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
        m = new TreeMap<>();
        for (String k : metaPath) {
            m.put(k, fetchMetadata(k));
        }
        ctx.setVariable("Metadata", m.descendingMap());
        m = new TreeMap<>();
        for (String k : metaServiceAcct) {
            // substitute a service account for {account}
            k = k.replace("{account}", appIdentity.getServiceAccountName());
            m.put(k, fetchMetadata(k));
        }
        ctx.setVariable("sam", m.descendingMap());
        // Recursivly get all info about service accounts -- Note tokens are leftout by default.
        ctx.setVariable("rsa", fetchJsonMetadata("/computeMetadata/v1/instance/service-accounts/?recursive=true"));
        // Recursivly get all data on Metadata server.
        ctx.setVariable("ram", fetchJsonMetadata("/?recursive=true"));
    }
    templateEngine.process("index", ctx, resp.getWriter());
}
Also used : Cookie(javax.servlet.http.Cookie) AppIdentityService(com.google.appengine.api.appidentity.AppIdentityService) WebContext(org.thymeleaf.context.WebContext) Enumeration(java.util.Enumeration) ApiProxy(com.google.apphosting.api.ApiProxy) TreeMap(java.util.TreeMap) Properties(java.util.Properties)

Example 3 with AppIdentityService

use of com.google.appengine.api.appidentity.AppIdentityService in project java-docs-samples by GoogleCloudPlatform.

the class GAEInfoServlet method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/html");
    PrintWriter p = resp.getWriter();
    p.print("<html><body>");
    final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
    table(p, "AppIdentity", tr(td("ServiceAccountName") + td(appIdentity.getServiceAccountName())) + tr(td("GCS Bucket") + td(appIdentity.getDefaultGcsBucketName())));
    table(p, "SystemProperties", tr(td("appId") + td(SystemProperty.applicationId.get())) + tr(td("appVer") + td(SystemProperty.applicationVersion.get())) + tr(td("version") + td(SystemProperty.version.get())) + tr(td("environment") + td(SystemProperty.environment.get())));
    // Environment Atributes
    ApiProxy.Environment env = ApiProxy.getCurrentEnvironment();
    Map<String, Object> attr = env.getAttributes();
    String c = "";
    for (String key : attr.keySet()) {
        Object o = attr.get(key);
        if (o.getClass().getCanonicalName().equals("java.lang.String")) {
            c += tr(td(key) + td((String) o));
        } else {
            c += tr(td(key) + td(o.getClass().getCanonicalName()));
        }
    }
    table(p, "Environment Attributes", c);
    c = "";
    for (Enumeration<String> e = req.getHeaderNames(); e.hasMoreElements(); ) {
        String key = e.nextElement();
        String val = req.getHeader(key);
        c += tr(td(key) + td(val));
        ;
    }
    table(p, "Headers", c);
    Cookie[] cookies = req.getCookies();
    if (cookies != null && cookies.length != 0) {
        c = "";
        for (Cookie co : cookies) {
            c += tr(td(co.getName()) + td(co.getValue()) + td(co.getComment()) + td(co.getPath()) + td(Integer.toString(co.getMaxAge())));
        }
        table(p, "Cookies", c);
    }
    Properties properties = System.getProperties();
    c = "";
    for (Enumeration e = properties.propertyNames(); e.hasMoreElements(); ) {
        String key = (String) e.nextElement();
        c += tr(td(key) + td((String) properties.get(key)));
    }
    table(p, "Java SystemProperties", c);
    Map<String, String> envVar = System.getenv();
    c = "";
    for (String key : envVar.keySet()) {
        c += tr(td(key) + td(envVar.get(key)));
    }
    table(p, "Envirionment Variables", c);
    p.print("</body></html>");
    p.close();
}
Also used : Cookie(javax.servlet.http.Cookie) AppIdentityService(com.google.appengine.api.appidentity.AppIdentityService) Enumeration(java.util.Enumeration) ApiProxy(com.google.apphosting.api.ApiProxy) Properties(java.util.Properties) PrintWriter(java.io.PrintWriter)

Example 4 with AppIdentityService

use of com.google.appengine.api.appidentity.AppIdentityService in project java-docs-samples by GoogleCloudPlatform.

the class UrlShortener method createShortUrl.

// [START asserting_identity_to_Google_APIs]
/**
 * Returns a shortened URL by calling the Google URL Shortener API.
 *
 * <p>Note: Error handling elided for simplicity.
 */
public String createShortUrl(String longUrl) throws Exception {
    ArrayList<String> scopes = new ArrayList<String>();
    scopes.add("https://www.googleapis.com/auth/urlshortener");
    final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
    final AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes);
    // The token asserts the identity reported by appIdentity.getServiceAccountName()
    JSONObject request = new JSONObject();
    request.put("longUrl", longUrl);
    URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?pp=1");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Content-Type", "application/json");
    connection.addRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken());
    OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    request.write(writer);
    writer.close();
    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        // Note: Should check the content-encoding.
        // Any JSON parser can be used; this one is used for illustrative purposes.
        JSONTokener responseTokens = new JSONTokener(connection.getInputStream());
        JSONObject response = new JSONObject(responseTokens);
        return (String) response.get("id");
    } else {
        try (InputStream s = connection.getErrorStream();
            InputStreamReader r = new InputStreamReader(s, StandardCharsets.UTF_8)) {
            throw new RuntimeException(String.format("got error (%d) response %s from %s", connection.getResponseCode(), CharStreams.toString(r), connection.toString()));
        }
    }
}
Also used : AppIdentityService(com.google.appengine.api.appidentity.AppIdentityService) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) URL(java.net.URL) JSONTokener(org.json.JSONTokener) HttpURLConnection(java.net.HttpURLConnection) JSONObject(org.json.JSONObject) OutputStreamWriter(java.io.OutputStreamWriter)

Example 5 with AppIdentityService

use of com.google.appengine.api.appidentity.AppIdentityService in project java-docs-samples by GoogleCloudPlatform.

the class FirebaseChannel method createFirebaseToken.

/**
 * Create a secure JWT token for the given userId.
 */
public String createFirebaseToken(Game game, String userId) {
    final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
    final BaseEncoding base64 = BaseEncoding.base64();
    String header = base64.encode("{\"typ\":\"JWT\",\"alg\":\"RS256\"}".getBytes());
    // Construct the claim
    String channelKey = game.getChannelKey(userId);
    String clientEmail = appIdentity.getServiceAccountName();
    long epochTime = System.currentTimeMillis() / 1000;
    // an hour from now
    long expire = epochTime + 60 * 60;
    Map<String, Object> claims = new HashMap<String, Object>();
    claims.put("iss", clientEmail);
    claims.put("sub", clientEmail);
    claims.put("aud", IDENTITY_ENDPOINT);
    claims.put("uid", channelKey);
    claims.put("iat", epochTime);
    claims.put("exp", expire);
    String payload = base64.encode(new Gson().toJson(claims).getBytes());
    String toSign = String.format("%s.%s", header, payload);
    AppIdentityService.SigningResult result = appIdentity.signForApp(toSign.getBytes());
    return String.format("%s.%s", toSign, base64.encode(result.getSignature()));
}
Also used : AppIdentityService(com.google.appengine.api.appidentity.AppIdentityService) HashMap(java.util.HashMap) Gson(com.google.gson.Gson) BaseEncoding(com.google.common.io.BaseEncoding)

Aggregations

AppIdentityService (com.google.appengine.api.appidentity.AppIdentityService)8 ApiProxy (com.google.apphosting.api.ApiProxy)3 Enumeration (java.util.Enumeration)3 Properties (java.util.Properties)3 Cookie (javax.servlet.http.Cookie)3 InputStreamReader (java.io.InputStreamReader)2 OutputStreamWriter (java.io.OutputStreamWriter)2 HttpURLConnection (java.net.HttpURLConnection)2 URL (java.net.URL)2 ArrayList (java.util.ArrayList)2 TreeMap (java.util.TreeMap)2 JSONObject (org.json.JSONObject)2 WebContext (org.thymeleaf.context.WebContext)2 GoogleCredential (com.google.api.client.googleapis.auth.oauth2.GoogleCredential)1 BaseEncoding (com.google.common.io.BaseEncoding)1 Gson (com.google.gson.Gson)1 BufferedReader (java.io.BufferedReader)1 InputStream (java.io.InputStream)1 PrintWriter (java.io.PrintWriter)1 Reader (java.io.Reader)1