Java Code Examples for com.google.appengine.api.utils.SystemProperty

The following examples show how to use com.google.appengine.api.utils.SystemProperty. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: appinventor-extensions   Source File: CrashReport.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets extra system information to add to logs.
 *
 * @param req HTTP request (may be {@code null})
 */
private static String extraExtraInfo(HttpServletRequest req) {
  StringBuilder s = new StringBuilder();

  // If the app is running on App Engine...
  if (Server.isProductionServer()) {
    // the version ID of the runtime environment
    String version = SystemProperty.version.get();
    s.append("runtime.version").append("=").append(version).append("\n");
    // the application major version number + deploy timestamp
    version = SystemProperty.applicationVersion.get();
    s.append("application.version").append("=").append(version).append("\n");
  }
  s.append("build.version").append("=").append(buildData).append("\n");
  s.append("git.build.version").append("=").append(GitBuildId.getVersion()).append("\n");
  s.append("git.build.fingerprint").append("=").append(GitBuildId.getFingerprint()).append("\n");
  if (req != null) {
    s.append("request.details").append("=").append(req.toString()).append("\n");
  }
  return new String(s);
}
 
Example 2
Source Project: appinventor-extensions   Source File: BuildData.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the timestamp for when the app was deployed (as a Unix time,
 * in milliseconds, suitable for passing to the java.util.Date() constructor
 *
 */
public static long getTimestamp() {
  if (timestamp == 0) {
    // Note: the applicationVersion string has the format version.timestamp
    // The timestamp currently (when this was written) needs to be divided
    // by 2^28 to get it into unix epoch seconds. This could change according
    // to comments I found on the web, but there doesn't seem
    // to be any more stable API to get this info.
    String applicationVersion = SystemProperty.applicationVersion.get();
    if (applicationVersion != null) {
      String parts[] = applicationVersion.split("\\.");
      timestamp = (Long.parseLong(parts[1]) >> 28) * 1000;
      date = new Date(timestamp);
    }
  }
  return timestamp;
}
 
Example 3
Source Project: nomulus   Source File: RdeUploadActionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void before() throws Exception {
  // Force "development" mode so we don't try to really connect to GCS.
  SystemProperty.environment.set(SystemProperty.Environment.Value.Development);
  gcsService = GcsServiceFactory.createGcsService();

  createTld("tld");
  PGPPublicKey encryptKey = new FakeKeyringModule().get().getRdeStagingEncryptionKey();
  writeGcsFile(gcsService, GHOSTRYDE_FILE, Ghostryde.encode(DEPOSIT_XML.read(), encryptKey));
  writeGcsFile(gcsService, GHOSTRYDE_R1_FILE, Ghostryde.encode(DEPOSIT_XML.read(), encryptKey));
  writeGcsFile(gcsService, LENGTH_FILE, Long.toString(DEPOSIT_XML.size()).getBytes(UTF_8));
  writeGcsFile(gcsService, LENGTH_R1_FILE, Long.toString(DEPOSIT_XML.size()).getBytes(UTF_8));
  writeGcsFile(gcsService, REPORT_FILE, Ghostryde.encode(REPORT_XML.read(), encryptKey));
  writeGcsFile(gcsService, REPORT_R1_FILE, Ghostryde.encode(REPORT_XML.read(), encryptKey));
  tm()
      .transact(
          () -> {
            RdeRevision.saveRevision("lol", DateTime.parse("2010-10-17TZ"), FULL, 0);
            RdeRevision.saveRevision("tld", DateTime.parse("2010-10-17TZ"), FULL, 0);
          });
}
 
Example 4
Source Project: tech-gallery   Source File: TechGalleryUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Method to get the application version.
 *
 * @author <a href="mailto:[email protected]"> João Felipe de Medeiros Moreira </a>
 * @since 13/10/2015
 *
 * @return the application version.
 */
public static String getApplicationVersion() {
  String appVersion = SystemProperty.applicationVersion.get();
  if (!appVersion.contains("$")) {
    String namespace = appVersion;
    String[] version = appVersion.split("\\.");
    if (version.length > 0 && version[0].contains("-")) {
      namespace = version[0].split("-")[0];
    } else if (version.length > 0) {
      namespace = version[0];
    } else {
      namespace = appVersion;
    }
    return namespace;
  }
  return appVersion;
}
 
Example 5
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String email = request.getParameter("email");
    String conferenceInfo = request.getParameter("conferenceInfo");
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    String body = "Hi, you have created a following conference.\n" + conferenceInfo;
    try {
        Message message = new MimeMessage(session);
        InternetAddress from = new InternetAddress(
                String.format("[email protected]%s.appspotmail.com",
                        SystemProperty.applicationId.get()), "Conference Central");
        message.setFrom(from);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, ""));
        message.setSubject("You created a new Conference!");
        message.setText(body);
        Transport.send(message);
    } catch (MessagingException e) {
        LOG.log(Level.WARNING, String.format("Failed to send an mail to %s", email), e);
        throw new RuntimeException(e);
    }
}
 
Example 6
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String email = request.getParameter("email");
    String conferenceInfo = request.getParameter("conferenceInfo");
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    String body = "Hi, you have created a following conference.\n" + conferenceInfo;
    try {
        Message message = new MimeMessage(session);
        InternetAddress from = new InternetAddress(
                String.format("[email protected]%s.appspotmail.com",
                        SystemProperty.applicationId.get()), "Conference Central");
        message.setFrom(from);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, ""));
        message.setSubject("You created a new Conference!");
        message.setText(body);
        Transport.send(message);
    } catch (MessagingException e) {
        LOG.log(Level.WARNING, String.format("Failed to send an mail to %s", email), e);
        throw new RuntimeException(e);
    }
}
 
Example 7
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String email = request.getParameter("email");
    String conferenceInfo = request.getParameter("conferenceInfo");
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    String body = "Hi, you have created a following conference.\n" + conferenceInfo;
    try {
        Message message = new MimeMessage(session);
        InternetAddress from = new InternetAddress(
                String.format("[email protected]%s.appspotmail.com",
                        SystemProperty.applicationId.get()), "Conference Central");
        message.setFrom(from);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, ""));
        message.setSubject("You created a new Conference!");
        message.setText(body);
        Transport.send(message);
    } catch (MessagingException e) {
        LOG.log(Level.WARNING, String.format("Failed to send an mail to %s", email), e);
        throw new RuntimeException(e);
    }
}
 
Example 8
Source Project: appengine-gcs-client   Source File: GcsServiceFactory.java    License: Apache License 2.0 6 votes vote down vote up
static RawGcsService createRawGcsService(Map<String, String> headers) {
  ImmutableSet.Builder<HTTPHeader> builder = ImmutableSet.builder();
  if (headers != null) {
    for (Map.Entry<String, String> header : headers.entrySet()) {
      builder.add(new HTTPHeader(header.getKey(), header.getValue()));
    }
  }

  RawGcsService rawGcsService;
  Value location = SystemProperty.environment.value();
  if (location == SystemProperty.Environment.Value.Production || hasCustomAccessTokenProvider()) {
    rawGcsService = OauthRawGcsServiceFactory.createOauthRawGcsService(builder.build());
  } else if (location == SystemProperty.Environment.Value.Development) {
    rawGcsService = LocalRawGcsServiceFactory.createLocalRawGcsService();
  } else {
    Delegate<?> delegate = ApiProxy.getDelegate();
    if (delegate == null
        || delegate.getClass().getName().startsWith("com.google.appengine.tools.development")) {
      rawGcsService = LocalRawGcsServiceFactory.createLocalRawGcsService();
    } else {
      rawGcsService = OauthRawGcsServiceFactory.createOauthRawGcsService(builder.build());
    }
  }
  return rawGcsService;
}
 
Example 9
Source Project: appengine-tck   Source File: UserServiceServlet.java    License: Apache License 2.0 6 votes vote down vote up
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    userService = UserServiceFactory.getUserService();
    user = userService.getCurrentUser();
    String env = SystemProperty.environment.value().toString();
    String responseMsg = env + ",";

    String method = req.getParameter("method");

    if (method == null) {
        resp.getWriter().print(responseMsg + "Error: Must set method parameter.");
        return;
    }

    if (method.equals("env")) {
        responseMsg += env;
        resp.getWriter().print(responseMsg);
        return;
    }

    responseMsg += callMethod(method);
    resp.getWriter().print(responseMsg);
}
 
Example 10
Source Project: appengine-tck   Source File: RequestLogsTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * These could return different values from the implementations so just assert the basics.
 */
@Test
@InSequence(20)
public void testMiscProperties() throws Exception {
    RequestLogs logs = getRequestLogs1();

    assertNotNull("App Engine Release, e.g. 1.8.0, or empty string.", logs.getAppEngineRelease());
    assertTrue("Estimated cost of this request, in dollars.", logs.getCost() >= 0.0);
    assertTrue("Time required to process this request in microseconds.", logs.getLatencyUsec() >= 0);
    assertTrue("Microseconds request spent in pending request queue, if was pending at all.", logs.getPendingTimeUsec() >= 0);
    assertFalse("This should never be a loading request: " + logs.toString(), logs.isLoadingRequest());

    String appId = SystemProperty.applicationId.get();  // appIds have a prefix according to datacenter.
    assertTrue("The application ID that handled this request.", logs.getAppId().endsWith(appId));

    long cycles = logs.getMcycles();
    assertTrue("Number of machine cycles used to process this request: " + cycles, cycles >= 0);

    String getOffsetMsg = "Base64-encoded offset used with subsequent LogQuery to continue reading logs at the point in time immediately following this request.";
    assertNotNull(getOffsetMsg, logs.getOffset());
    assertTrue("Should be Base64: " + logs.getOffset(), Base64.isBase64(logs.getOffset().getBytes()));

    String mapEntryMsg = "File or class within the URL mapping used for this request: " + logs.getUrlMapEntry();
    assertNotNull(mapEntryMsg, logs.getUrlMapEntry());
}
 
Example 11
private String getHostname() throws IOException {
  if (hostname == null) {
    if (SystemProperty.environment.value().equals(SystemProperty.Environment.Value.Production)) {
      URL url = new URL(NETWORK_INTERFACE_METADATA_URL);
      HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
      BufferedReader reader = new BufferedReader(
          new InputStreamReader(httpUrlConnection.getInputStream()));
      String result, line = reader.readLine();
      result = line;
      while ((line = reader.readLine()) != null) {
        result += line;
      }
      hostname = result;
    } else {
      hostname = "localhost";
    }
  }
  return hostname;
}
 
Example 12
private String getCurrentHost() {
  if (Server.isProductionServer()) {
    if (StringUtils.isNullOrEmpty(appengineHost.get())) {
      String applicationVersionId = SystemProperty.applicationVersion.get();
      String applicationId = SystemProperty.applicationId.get();
      return applicationVersionId + "." + applicationId + ".appspot.com";
    } else {
      return appengineHost.get();
    }
  } else {
    // TODO(user): Figure out how to make this more generic
    return "localhost:8888";
  }
}
 
Example 13
Source Project: appinventor-extensions   Source File: GalleryServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
public GalleryServiceImpl() {
  String bucket = Flag.createFlag("gallery.bucket", "").get();
  boolean galleryEnabled = Flag.createFlag("use.gallery",false).get();
  String envirnment = SystemProperty.environment.value().toString();
  String adminEmail = Flag.createFlag("gallery.admin.email", "").get();
  settings = new GallerySettings(galleryEnabled, bucket, envirnment, adminEmail);
}
 
Example 14
Source Project: policyscanner   Source File: UserManagedKeysApp.java    License: Apache License 2.0 5 votes vote down vote up
private PipelineOptions getCloudExecutionOptions(String stagingLocation) {
  DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class);
  options.setProject(SystemProperty.applicationId.get());
  options.setStagingLocation(stagingLocation);
  options.setRunner(BlockingDataflowPipelineRunner.class);
  return options;
}
 
Example 15
Source Project: policyscanner   Source File: LiveStateCheckerRunner.java    License: Apache License 2.0 5 votes vote down vote up
private static PipelineOptions getCloudExecutionOptions(String stagingLocation) {
  DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class);
  options.setProject(SystemProperty.applicationId.get());
  options.setStagingLocation(stagingLocation);
  options.setRunner(BlockingDataflowPipelineRunner.class);
  return options;
}
 
Example 16
Source Project: policyscanner   Source File: DesiredStateEnforcerApp.java    License: Apache License 2.0 5 votes vote down vote up
private PipelineOptions getCloudExecutionOptions(String stagingLocation) {
  DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class);
  options.setProject(SystemProperty.applicationId.get());
  options.setStagingLocation(stagingLocation);
  options.setRunner(BlockingDataflowPipelineRunner.class);
  return options;
}
 
Example 17
Source Project: endpoints-java   Source File: EnvUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIsRunningOnAppEngineProd() {
  SystemProperty.environment.set(SystemProperty.Environment.Value.Production);
  assertTrue(EnvUtil.isRunningOnAppEngineProd());
  SystemProperty.environment.set(SystemProperty.Environment.Value.Development);
  assertFalse(EnvUtil.isRunningOnAppEngineProd());
  System.clearProperty(EnvUtil.ENV_APPENGINE_RUNTIME);
  assertFalse(EnvUtil.isRunningOnAppEngineProd());
}
 
Example 18
Source Project: getting-started-java   Source File: HelloAppEngine.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException {

  Properties properties = System.getProperties();

  response.setContentType("text/plain");
  response.getWriter().println("Hello App Engine - Standard using "
      + SystemProperty.version.get() + " Java " + properties.get("java.specification.version"));

}
 
Example 19
Source Project: tech-gallery   Source File: ShareTechnologyTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    SystemProperty.applicationVersion.set("test");
    helper.setUp();
    closeable = ObjectifyService.begin();
    currentUser = UserServiceFactory.getUserService().getCurrentUser();
}
 
Example 20
Source Project: java-docs-samples   Source File: HelloAppEngine.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException {
  Properties properties = System.getProperties();

  response.setContentType("text/plain");
  response.getWriter().println("Hello App Engine - Standard using "
          + SystemProperty.version.get() + " Java "
          + properties.get("java.specification.version"));
}
 
Example 21
Source Project: appengine-java-vm-hello   Source File: HelloInfo.java    License: Apache License 2.0 5 votes vote down vote up
public static String getInfo() {
  String version = SystemProperty.applicationVersion.get();
  String majorVersion = version.substring(0, version.indexOf('.'));
  Environment env = ApiProxy.getCurrentEnvironment();
  String hostname =
      "" + env.getAttributes().get("com.google.appengine.runtime.default_version_hostname");
  String infostring = "version: " + majorVersion + " and hostname: " + hostname;
  return infostring;
}
 
Example 22
Source Project: appengine-java-vm-runtime   Source File: VmRuntimeUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Set the Environment system property to Development or Production.
 */

static void setEnvironmentSystemProperty(String partition) {
  if ("dev".equals(partition)) {
    System.setProperty(
        SystemProperty.environment.key(), SystemProperty.Environment.Value.Development.name());
  } else {
    System.setProperty(
        SystemProperty.environment.key(), SystemProperty.Environment.Value.Production.name());
  }
}
 
Example 23
Source Project: appengine-java-vm-runtime   Source File: VmRuntimeUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Install system properties based on the provided VmApiProxyEnvironment.
 */
public static void installSystemProperties(
    VmApiProxyEnvironment environment, AppEngineWebXml appEngineWebXml) {
  setEnvironmentSystemProperty(environment.getPartition());
  System.setProperty(SystemProperty.version.key(), getServerInfo());
  System.setProperty(
      SystemProperty.applicationId.key(), AppId.parse(environment.getAppId()).getLongAppId());
  System.setProperty(SystemProperty.applicationVersion.key(), environment.getVersionId());
  System.setProperty("appengine.jetty.also_log_to_apiproxy", "true");
  if (appEngineWebXml!=null) {
    for (Map.Entry<String, String> entry : appEngineWebXml.getSystemProperties().entrySet()) {
      System.setProperty(entry.getKey(), entry.getValue());
    }
  }
}
 
Example 24
/**
 * Test that all AppEngine specific system properties are set up when the
 * VmRuntimeFilter is initialized.
 *
 * @throws Exception
 */
public void testSystemProperties() throws Exception {
  String[] lines = fetchUrl(createUrl("/printSystemProperties"));
  assertEquals(7, lines.length);
  assertEquals("sysprop1 value", lines[0]);
  assertEquals("sysprop2 value", lines[1]);
  assertEquals("null", lines[2]);
  assertEquals(SystemProperty.Environment.Value.Production.name(), lines[3]);
  assertTrue(lines[4].startsWith("Google App Engine/"));
  assertEquals(PROJECT, lines[5]);
  assertEquals(VERSION + ".0", lines[6]);
}
 
Example 25
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException {

  Properties properties = System.getProperties();

  response.setContentType("text/plain");
  response.getWriter().println("Hello App Engine - Standard using "
      + SystemProperty.version.get() + " Java " + properties.get("java.specification.version"));
}
 
Example 26
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException {

  Properties properties = System.getProperties();

  response.setContentType("text/plain");
  response.getWriter().println("Hello App Engine - Standard using "
      + SystemProperty.version.get() + " Java " + properties.get("java.specification.version"));
}
 
Example 27
Source Project: yawp   Source File: AppengineWebAppContext.java    License: MIT License 5 votes vote down vote up
@Override
protected void doStart() throws Exception {
    this.helper = createHelper();
    this.environment = ApiProxy.getCurrentEnvironment();
    getServletContext().setAttribute(API_PROXY_LOCAL, ApiProxy.getDelegate());
    getServletContext().setAttribute(APPENGINE_WEB_XML, readAppengineWebXml());
    getServletContext().setAttribute(WEB_XML, readWebXml());
    SystemProperty.environment.set(SystemProperty.Environment.Value.Development);
    configureUserRealmAppengineHelper();
    super.doStart();
}
 
Example 28
Source Project: appengine-gcs-client   Source File: OauthRawGcsService.java    License: Apache License 2.0 5 votes vote down vote up
OauthRawGcsService(OAuthURLFetchService urlfetch, ImmutableSet<HTTPHeader> headers) {
  this.urlfetch = checkNotNull(urlfetch, "Null urlfetch");
  this.headers = checkNotNull(headers, "Null headers");
  AppIdentityCredential cred = new AppIdentityCredential(OAUTH_SCOPES);
  storage = new Storage.Builder(new UrlFetchTransport(), new JacksonFactory(), cred)
      .setApplicationName(SystemProperty.applicationId.get()).build();
}
 
Example 29
Source Project: appengine-tck   Source File: CapabilityTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * check unknown service.
 */
@Test
public void testDummyService() {
    // only check this in appserver since everything in dev_appserver has ENABLED status.
    if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
        String pName = "dummy";
        Capability capability = new Capability(pName);
        CapabilityState cState = capabilitiesService.getStatus(capability);
        assertEquals(pName, cState.getCapability().getPackageName());
        assertEquals(CapabilityStatus.UNKNOWN, cState.getStatus());
    }
}
 
Example 30
Source Project: appengine-tck   Source File: NamespaceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testEntity() {
    for (String ns : namespaceDat) {
        NamespaceManager.set(ns);
        Query query = new Query(kindName);
        Entity readRec = service.prepare(query).asIterator().next();
        assertEquals(ns, readRec.getNamespace());
        String appId = readRec.getAppId();
        appId = appId.substring(appId.indexOf("~") + 1);
        assertEquals(SystemProperty.applicationId.get(), appId);
        assertTrue(readRec.hasProperty("jobType"));
    }
}