com.google.api.server.spi.config.ApiMethod Java Examples

The following examples show how to use com.google.api.server.spi.config.ApiMethod. 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 File: ApiConfigValidatorTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testApiMethodConfigWithApiMethodNameContainingContinuousDots() throws Exception {
  @Api(name = "testApi", version = "v1", resource = "bar")
  final class Test {
    @ApiMethod(name = "TestApi..testMethod")
    public void test() {
    }
  }

  ApiConfig config = configLoader.loadConfiguration(ServiceContext.create(), Test.class);

  try {
    validator.validate(config);
    fail("Expected InvalidMethodNameException.");
  } catch (InvalidMethodNameException expected) {
  }
}
 
Example #2
Source File: ApiConfigValidatorTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidateMethods_ignoredMethod() throws Exception {
  final class Bean {

  }
  @Api
  final class Endpoint {
    @ApiMethod(ignored = AnnotationBoolean.TRUE)
    public void thisShouldBeIgnored(Bean resource1, Bean resource2) {
    }
  }
  ApiConfig config = configLoader.loadConfiguration(ServiceContext.create(), Endpoint.class);
  // If this passes validation, then no error will be thrown. Otherwise, the validator will
  // complain that the method has two resources.
  validator.validate(config);
}
 
Example #3
Source File: Fido2RequestHandler.java    From webauthndemo with Apache License 2.0 6 votes vote down vote up
@ApiMethod(name = "getSignRequest", path="get/sign")
public List<String> getSignRequest(User user) throws OAuthRequestException {
  if (user == null) {
    throw new OAuthRequestException("User is not authenticated");
  }

  PublicKeyCredentialRequestOptions assertion =
      new PublicKeyCredentialRequestOptions(Constants.APP_ID);
  SessionData session = new SessionData(assertion.challenge, Constants.APP_ID);
  session.save(user.getEmail());

  assertion.populateAllowList(user.getEmail());
  JsonObject assertionJson = assertion.getJsonObject();
  JsonObject sessionJson = session.getJsonObject();
  assertionJson.add("session", sessionJson);

  List<String> resultList = new ArrayList<String>();
  resultList.add(assertionJson.toString());
  return resultList;
}
 
Example #4
Source File: WaxEndpoint.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
/**
 * Responds with the {@link WaxDataItem} resource requested.
 *
 * @throws NotFoundException if the session doesn't exist or has no {@link WaxDataItem} with the
 *         requested id
 */
@ApiMethod(
    name = "items.get",
    path = "sessions/{sessionId}/items/{itemId}")
public WaxDataItem get(@Named("sessionId") String sessionId, @Named("itemId") String itemId)
    throws NotFoundException {
  try {
    WaxDataItem item = store.get(sessionId, itemId);
    if (item != null) {
      return item;
    }
    throw new NotFoundException("Invalid itemId: " + itemId);
  } catch (InvalidSessionException e) {
    throw new NotFoundException(e.getMessage());
  }
}
 
Example #5
Source File: ApiConfigAnnotationReaderTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicEndpoint() throws Exception {
  ApiConfig config = createConfig(Endpoint0.class);
  annotationReader.loadEndpointClass(serviceContext, Endpoint0.class, config);
  assertEquals("api", config.getName());
  assertEquals(0, config.getApiClassConfig().getMethods().size());

  annotationReader.loadEndpointMethods(serviceContext, Endpoint0.class,
      config.getApiClassConfig().getMethods());
  assertEquals(1, config.getApiClassConfig().getMethods().size());
  ApiMethodConfig method = config.getApiClassConfig().getMethods().get(
      methodToEndpointMethod(Endpoint0.class.getMethod("getFoo", String.class)));
  validateMethod(method,
      "Endpoint0.getFoo",
      "foo/{id}",
      ApiMethod.HttpMethod.GET,
      DEFAULT_SCOPES,
      DEFAULT_AUDIENCES,
      DEFAULT_CLIENTIDS,
      null,
      null);
}
 
Example #6
Source File: ApiConfigValidatorTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testApiMethodConfigWithApiMethodNameContainingStartingDot() throws Exception {
  @Api(name = "testApi", version = "v1", resource = "bar")
  final class Test {
    @ApiMethod(name = ".Api.TestMethod")
    public void test() {
    }
  }

  ApiConfig config = configLoader.loadConfiguration(ServiceContext.create(), Test.class);

  try {
    validator.validate(config);
    fail("Expected InvalidMethodNameException.");
  } catch (InvalidMethodNameException expected) {
  }
}
 
Example #7
Source File: ApiConfigAnnotationReaderTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerializedParameter() throws Exception {
  @Api
  final class Test {
    @SuppressWarnings("unused")
    public void method(@Named("serialized") TestBean tb) {}
  }

  ApiConfig config = createConfig(Test.class);
  annotationReader.loadEndpointClass(serviceContext, Test.class, config);
  annotationReader.loadEndpointMethods(serviceContext, Test.class,
      config.getApiClassConfig().getMethods());

  ApiMethodConfig methodConfig =
      config.getApiClassConfig().getMethods().get(methodToEndpointMethod(Test.class.getMethod(
          "method", TestBean.class)));
  validateMethod(methodConfig, "Test.method", "method/{serialized}", ApiMethod.HttpMethod.POST,
      DEFAULT_SCOPES,
      DEFAULT_AUDIENCES,
      DEFAULT_CLIENTIDS,
      null,
      null);
  validateParameter(methodConfig.getParameterConfigs().get(0), "serialized", false, null,
      TestBean.class, TestSerializer.class, String.class);
}
 
Example #8
Source File: ApiConfigValidatorTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testApiMethodConfigWithApiMethodNameContainingSpecialCharacter() throws Exception {
  @Api(name = "testApi", version = "v1", resource = "bar")
  final class Test {
    @ApiMethod(name = "Api.Test#Method")
    public void test() {
    }
  }

  ApiConfig config = configLoader.loadConfiguration(ServiceContext.create(), Test.class);

  try {
    validator.validate(config);
    fail("Expected InvalidMethodNameException.");
  } catch (InvalidMethodNameException expected) {
  }
}
 
Example #9
Source File: ApiConfigAnnotationReaderTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuperclassWithoutApi() throws Exception {
  @Api
  class Foo {
    @SuppressWarnings("unused")
    public void foo() {}
  }

  class Bar extends Foo {
    @ApiMethod(name = "overridden")
    @Override
    public void foo() {}
  }

  ApiConfig config = createConfig(Bar.class);
  annotationReader.loadEndpointClass(serviceContext, Bar.class, config);
  annotationReader.loadEndpointMethods(serviceContext, Bar.class,
      config.getApiClassConfig().getMethods());

  // Make sure method comes from Bar even though that class is not annotated with @Api.
  ApiMethodConfig methodConfig =
      Iterables.getOnlyElement(config.getApiClassConfig().getMethods().values());
  assertEquals("overridden", methodConfig.getName());
  assertEquals(Bar.class.getName() + ".foo", methodConfig.getFullJavaName());
}
 
Example #10
Source File: TestEndpoint.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@ApiMethod(httpMethod = HttpMethod.GET, path = "testparamspath/{anint}/{along}/{afloat}/{adouble}"
    + "/{aboolean}/{astring}/{asimpledate}/{adateandtime}/{adate}/{anenum}")
public FieldContainer testParamsPath(
    @Named("anint") int anInt,
    @Named("along") long aLong,
    @Named("afloat") float aFloat,
    @Named("adouble") double aDouble,
    @Named("aboolean") boolean aBoolean,
    @Named("astring") String aString,
    @Named("asimpledate") SimpleDate aSimpleDate,
    @Named("adateandtime") DateAndTime aDateAndTime,
    @Named("adate") Date aDate,
    @Named("anenum") TestEnum anEnum) {
  FieldContainer ret = new FieldContainer();
  ret.anInt = anInt;
  ret.aLong = aLong;
  ret.aFloat = aFloat;
  ret.aDouble = aDouble;
  ret.aBoolean = aBoolean;
  ret.aString = aString;
  ret.aSimpleDate = aSimpleDate;
  ret.aDateAndTime = aDateAndTime;
  ret.aDate = aDate;
  ret.anEnum = anEnum;
  return ret;
}
 
Example #11
Source File: AnnotationApiConfigGeneratorTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
/**
 * Test if the generated API has the expected method paths. First try this out without any
 * explicit paths.
 */
public void testMethodPaths_repeatRestPath() throws Exception {
  @SuppressWarnings("unused")
  @Api
  class Dates {
    @ApiMethod(httpMethod = "GET", path = "dates/{id1}/{id2}")
    public Date get(@Named("id1") String id1, @Named("id2") String id2) { return null; }

    @ApiMethod(httpMethod = "GET", path = "dates/{x}/{y}")
    public List<Date> listFromXY(@Named("x") String x, @Named("y") String y) { return null; }
  }
  try {
    g.generateConfig(Dates.class).get("myapi-v1.api");
    fail("Multiple methods with same RESTful signature");
  } catch (DuplicateRestPathException expected) {
    // expected
  }
}
 
Example #12
Source File: TestEndpoint.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@ApiMethod(httpMethod = HttpMethod.GET, path = "testparamsquery")
public FieldContainer testParamsQuery(
    @Named("anint") Integer anInt,
    @Named("along") Long aLong,
    @Named("afloat") Float aFloat,
    @Named("adouble") Double aDouble,
    @Named("aboolean") Boolean aBoolean,
    @Named("astring") String aString,
    @Named("asimpledate") SimpleDate aSimpleDate,
    @Named("adateandtime") DateAndTime aDateAndTime,
    @Named("adate") Date aDate,
    @Named("anenum") TestEnum anEnum) {
  FieldContainer ret = new FieldContainer();
  ret.anInt = anInt;
  ret.aLong = aLong;
  ret.aFloat = aFloat;
  ret.aDouble = aDouble;
  ret.aBoolean = aBoolean;
  ret.aString = aString;
  ret.aSimpleDate = aSimpleDate;
  ret.aDateAndTime = aDateAndTime;
  ret.aDate = aDate;
  ret.anEnum = anEnum;
  return ret;
}
 
Example #13
Source File: WaxEndpoint.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
/**
 * Responds with list of {@link WaxDataItem} for the {@link WaxSession} specified in the
 * request.
 *
 * @throws NotFoundException if the session doesn't exist
 */
@ApiMethod(
    name = "items.list",
    path = "sessions/{sessionId}/items")
public List<WaxDataItem> list(@Named("sessionId") String sessionId) throws NotFoundException {
  try {
    return store.list(sessionId);
  } catch (InvalidSessionException e) {
    throw new NotFoundException(e.getMessage());
  }
}
 
Example #14
Source File: WaxEndpoint.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
/**
 * Removes {@link WaxDataItem} resource from the specified {@link WaxSession}.
 *
 * @throws NotFoundException if the session or item id doesn't exist
 */
@ApiMethod(
    name = "items.delete",
    path = "sessions/{sessionId}/items/{itemId}")
public void delete(
    @Named("sessionId") String sessionId, @Named("itemId") String itemId)
        throws NotFoundException {
  try {
    if (!store.delete(sessionId, itemId)) {
      throw new NotFoundException("Invalid itemId: " + itemId);
    }
  } catch (InvalidSessionException e) {
    throw new NotFoundException(e.getMessage());
  }
}
 
Example #15
Source File: ApiConfigAnnotationReaderTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testEndpointWithBridgeMethods() throws Exception {
  ApiConfig config = createConfig(BridgeInheritanceEndpoint.class);
  annotationReader.loadEndpointClass(serviceContext, BridgeInheritanceEndpoint.class, config);
  annotationReader.loadEndpointMethods(serviceContext, BridgeInheritanceEndpoint.class,
      config.getApiClassConfig().getMethods());

  assertEquals(2, config.getApiClassConfig().getMethods().size());
  ApiMethodConfig fn1 = config.getApiClassConfig().getMethods().get(methodToEndpointMethod(
      BridgeInheritanceEndpoint.class.getMethod("fn1")));
  validateMethod(fn1,
      "api6.foos.fn1",
      "fn1",
      ApiMethod.HttpMethod.GET,
      DEFAULT_SCOPES,
      DEFAULT_AUDIENCES,
      DEFAULT_CLIENTIDS,
      null,
      null);
  ApiMethodConfig fn2 = config.getApiClassConfig().getMethods().get(methodToEndpointMethod(
      BridgeInheritanceEndpoint.class.getSuperclass().getMethod("fn2")));
  validateMethod(fn2,
      "api6.foos.fn2",
      "fn2",
      ApiMethod.HttpMethod.GET,
      DEFAULT_SCOPES,
      DEFAULT_AUDIENCES,
      DEFAULT_CLIENTIDS,
      null,
      null);

  ApiMethodConfig bridge = config.getApiClassConfig().getMethods().get(methodToEndpointMethod(
      BridgeInheritanceEndpoint.class.getSuperclass().getMethod("fn1")));
  assertNull(bridge);
}
 
Example #16
Source File: RestServletRequestParamReaderTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@ApiMethod(
    name = "testFormData",
    httpMethod = HttpMethod.POST,
    path = "testFormData")
public void testFormData(
    @Nullable @Named("foo") String foo,
    @Nullable @Named("bar") Integer bar) {
}
 
Example #17
Source File: ProxyingDiscoveryService.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@ApiMethod(
    name = "apis.list",
    path = "apis"
)
public DirectoryList getApiList(HttpServletRequest request) throws InternalServerErrorException {
  checkIsInitialized();
  return discoveryProvider.getDirectory(getActualRoot(request));
}
 
Example #18
Source File: BridgeInheritanceEndpoint.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Override
@ApiMethod(
    name = "api6.foos.fn1",
    path = "fn1",
    httpMethod = HttpMethod.GET
)
public Object fn1() {
  return null;
}
 
Example #19
Source File: SensorDataEndpoint.java    From raspberrypi-appengine-portal with Apache License 2.0 5 votes vote down vote up
@ApiMethod(name = "data.create", httpMethod = "post")
public SensorData create(SensorData data, User user) {
	
    // check the user is authenticated and authorised
	if(user == null) {
		log.warning("User is not authenticated");
		throw new RuntimeException("Authentication required!");
		
	} else if(!Constants.EMAIL_ADDRESS.equals(user.getEmail())) {
		
		log.warning("User is not authorised, email: " + user.getEmail());
		throw new RuntimeException("Not authorised!");
	}
	
	data.save();
	
	try {
	    // notify the client channels
	    ChannelService channelService = ChannelServiceFactory.getChannelService();

	    List<Client> clients = Client.findAll();
	    String json = GSON.toJson(data);

	    for(Client client: clients) {
	        channelService.sendMessage(new ChannelMessage(client.getId(), json));
	    }
	    
	} catch(Exception e) {
	    log.log(Level.SEVERE, "Failed to notify connected clients", e);
	}
		
	return data;
}
 
Example #20
Source File: BridgeInheritanceEndpoint.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@ApiMethod(
    name = "api6.foos.fn2",
    path = "fn2",
    httpMethod = HttpMethod.GET
)
public Object fn2() {
  return null;
}
 
Example #21
Source File: Fido2RequestHandler.java    From webauthndemo with Apache License 2.0 5 votes vote down vote up
@ApiMethod(name = "removeSecurityKey")
public String[] removeSecurityKey(User user, @Named("publicKey") String publicKey)
    throws OAuthRequestException {
  if (user == null) {
    throw new OAuthRequestException("User is not authenticated");
  }

  Credential.remove(user.getEmail(), publicKey);
  return new String[] {"OK"};
}
 
Example #22
Source File: Endpoint2.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@ApiMethod(
    name = "api2.foos.invisible0",
    path = "invisible0",
    httpMethod = HttpMethod.POST
)
protected String invisible0() {
  return null;
}
 
Example #23
Source File: Endpoint2.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
@ApiMethod(
    name = "api2.foos.invisible1",
    path = "invisible1",
    httpMethod = HttpMethod.POST
)
private String invisible1() {
  return null;
}
 
Example #24
Source File: WaxEndpoint.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
/**
 * Remove an existing session.
 * <p>
 * Clients that create sessions without a duration (will last forever) will need to call this
 * method on their own to clean up the session.
 *
 * @return {@link WaxRemoveSessionResponse} with the deleted session id
 * @throws InternalServerErrorException if the session deletion failed
 */
@ApiMethod(
    name = "sessions.remove",
    path = "removesession",
    httpMethod = HttpMethod.POST)
public WaxRemoveSessionResponse removeSession(@Named("sessionId") String sessionId)
    throws InternalServerErrorException {
  try {
    store.deleteSession(sessionId);
    return new WaxRemoveSessionResponse(sessionId);
  } catch (InvalidSessionException e) {
    throw new InternalServerErrorException(e.getMessage());
  }
}
 
Example #25
Source File: Endpoint1.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@ApiMethod(
    name = "foos.execute0",
    path = "execute0",
    httpMethod = "POST"
)
public Object execute0(@Named("id") String id, @Named("i0") int i0,
    @Named("i1") @Nullable Integer i1, @Named("long0") long long0,
    @Nullable @Named("long1") Long long1, @Named("b0") boolean b0,
    @Nullable @Named("b1") Boolean b1, @Named("f") float f,
    @Nullable @Named("d") Double d) {
  return null;
}
 
Example #26
Source File: AdSearchEndpoints.java    From AdSearch_Endpoints with Apache License 2.0 5 votes vote down vote up
@ApiMethod(name = "optimize", path = "optimize",
        httpMethod = HttpMethod.GET)
public List<AdsStatsInfo> optimize(@Named("keyWords") List<String> keyWords) {
    AdsOptimization adsOptimizer = new AdsOptimizationImpl(findMatch(keyWords));
    return adsOptimizer.filterAds(INVENTORY, MIN_RELEVANCE_SCORE, MIN_RESERVE_PRICE)
            .selectTopK(K).deDup().adsPricingAndAllocation(INVENTORY, MAINLINE_RESERVE_PRICE)
            .showResult();
}
 
Example #27
Source File: Endpoint1.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@ApiMethod(
    name = "foos.insert",
    path = "foos",
    httpMethod = HttpMethod.POST,
    cacheControl = @ApiMethodCacheControl(
        noCache = false,
        maxAge = 3
    )
)
public Foo insertFoo(Foo r) {
  return null;
}
 
Example #28
Source File: LimitMetricsEndpoint.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@ApiMethod(
    name = "custom",
    metricCosts = {
        @ApiMetricCost(name = "read", cost = 1),
        @ApiMetricCost(name = "write", cost = 2)
    })
public void customFoo() { }
 
Example #29
Source File: Fido2RequestHandler.java    From webauthndemo with Apache License 2.0 5 votes vote down vote up
@ApiMethod(name = "processSignResponse")
public List<String> processSignResponse(
    @Named("responseData") String responseData, User user)
    throws OAuthRequestException, ResponseException, ServletException {
  if (user == null) {
    throw new OAuthRequestException("User is not authenticated");
  }

  Gson gson = new Gson();
  JsonElement element = gson.fromJson(responseData, JsonElement.class);
  JsonObject object = element.getAsJsonObject();
  String clientDataJSON = object.get("clientDataJSON").getAsString();
  String authenticatorData = object.get("authenticatorData").getAsString();
  String credentialId = object.get("credentialId").getAsString();
  String signature = object.get("signature").getAsString();

  AuthenticatorAssertionResponse assertion =
      new AuthenticatorAssertionResponse(clientDataJSON, authenticatorData, signature);
  // TODO
  String type = null;
  String session = null;

  PublicKeyCredential cred = new PublicKeyCredential(credentialId, type,
      BaseEncoding.base64Url().decode(credentialId), assertion);

  Credential savedCredential;
  try {
    savedCredential = Server.validateAndFindCredential(cred, user.getEmail(), session);
  } catch (ResponseException e) {
    throw new ServletException("Unable to validate assertion", e);
  }

  Server.verifyAssertion(cred, user.getEmail(), session, savedCredential);

  List<String> resultList = new ArrayList<String>();
  resultList.add(savedCredential.toJson());
  return resultList;
}
 
Example #30
Source File: AdSearchEndpoints.java    From AdSearch_Endpoints with Apache License 2.0 4 votes vote down vote up
@ApiMethod(name = "findMatch", path = "findMatch",
        httpMethod = HttpMethod.GET)
public List<AdsStatsInfo> findMatch(@Named("keyWords") List<String> keyWords) {
    return ADS_INDEX.indexMatch(keyWords);
}