use of com.google.api.server.spi.config.model.ApiParameterConfig in project endpoints-java by cloudendpoints.
the class ApiConfigAnnotationReaderTest method genericParameterTypeTestImpl.
private <T> void genericParameterTypeTestImpl() throws Exception {
@Api
class Bar<T1> {
@SuppressWarnings("unused")
public void bar(T1 t1) {
}
}
class Foo extends Bar<T> {
}
ApiConfig config = createConfig(Foo.class);
annotationReader.loadEndpointMethods(serviceContext, Foo.class, config.getApiClassConfig().getMethods());
ApiParameterConfig parameter = config.getApiClassConfig().getMethods().get(methodToEndpointMethod(Foo.class.getSuperclass().getDeclaredMethod("bar", Object.class))).getParameterConfigs().get(0);
assertEquals(ApiParameterConfig.Classification.UNKNOWN, parameter.getClassification());
}
use of com.google.api.server.spi.config.model.ApiParameterConfig in project endpoints-java by cloudendpoints.
the class ApiConfigAnnotationReaderTest method testParameterAnnotations_javax.
@Test
public void testParameterAnnotations_javax() throws Exception {
@Api
class Endpoint {
@SuppressWarnings("unused")
public void method(@javax.inject.Named("foo") @javax.annotation.Nullable int foo) {
}
}
ApiConfig config = createConfig(Endpoint.class);
annotationReader.loadEndpointClass(serviceContext, Endpoint.class, config);
annotationReader.loadEndpointMethods(serviceContext, Endpoint.class, config.getApiClassConfig().getMethods());
ApiMethodConfig methodConfig = Iterables.getOnlyElement(config.getApiClassConfig().getMethods().values());
ApiParameterConfig parameterConfig = Iterables.getOnlyElement(methodConfig.getParameterConfigs());
validateParameter(parameterConfig, "foo", true, null, int.class, null, int.class);
}
use of com.google.api.server.spi.config.model.ApiParameterConfig in project endpoints-java by cloudendpoints.
the class RestServletRequestParamReader method read.
@Override
public Object[] read() throws ServiceException {
// TODO: Take charset from content-type as encoding
try {
EndpointMethod method = getMethod();
if (method.getParameterClasses().length == 0) {
return new Object[0];
}
HttpServletRequest servletRequest = endpointsContext.getRequest();
JsonNode node;
// this case, each part represents a named parameter instead.
if (ServletFileUpload.isMultipartContent(servletRequest)) {
try {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(servletRequest);
ObjectNode obj = (ObjectNode) objectReader.createObjectNode();
while (iter.hasNext()) {
FileItemStream item = iter.next();
if (item.isFormField()) {
obj.put(item.getFieldName(), IoUtil.readStream(item.openStream()));
} else {
throw new BadRequestException("unable to parse multipart form field");
}
}
node = obj;
} catch (FileUploadException e) {
throw new BadRequestException("unable to parse multipart request", e);
}
} else {
String requestBody = IoUtil.readRequestBody(servletRequest);
logger.atFine().log("requestBody=%s", requestBody);
// Unlike the Lily protocol, which essentially always requires a JSON body to exist (due to
// path and query parameters being injected into the body), bodies are optional here, so we
// create an empty body and inject named parameters to make deserialize work.
node = Strings.isEmptyOrWhitespace(requestBody) ? objectReader.createObjectNode() : objectReader.readTree(requestBody);
}
if (!node.isObject()) {
throw new BadRequestException("expected a JSON object body");
}
ObjectNode body = (ObjectNode) node;
Map<String, Class<?>> parameterMap = getParameterMap(method);
// the order of precedence is resource field > query parameter > path parameter.
for (Enumeration<?> e = servletRequest.getParameterNames(); e.hasMoreElements(); ) {
String parameterName = (String) e.nextElement();
if (!body.has(parameterName)) {
Class<?> parameterClass = parameterMap.get(parameterName);
ApiParameterConfig parameterConfig = parameterConfigMap.get(parameterName);
if (parameterClass != null && parameterConfig.isRepeated()) {
ArrayNode values = body.putArray(parameterName);
for (String value : servletRequest.getParameterValues(parameterName)) {
values.add(value);
}
} else {
body.put(parameterName, servletRequest.getParameterValues(parameterName)[0]);
}
}
}
for (Entry<String, String> entry : rawPathParameters.entrySet()) {
String parameterName = entry.getKey();
Class<?> parameterClass = parameterMap.get(parameterName);
if (parameterClass != null && !body.has(parameterName)) {
if (parameterConfigMap.get(parameterName).isRepeated()) {
ArrayNode values = body.putArray(parameterName);
for (String value : COMPOSITE_PATH_SPLITTER.split(entry.getValue())) {
values.add(value);
}
} else {
body.put(parameterName, entry.getValue());
}
}
}
for (Entry<String, ApiParameterConfig> entry : parameterConfigMap.entrySet()) {
if (!body.has(entry.getKey()) && entry.getValue().getDefaultValue() != null) {
body.put(entry.getKey(), entry.getValue().getDefaultValue());
}
}
return deserializeParams(body);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | IOException e) {
logger.atInfo().withCause(e).log("Unable to read request parameter(s)");
throw new BadRequestException(e);
}
}
use of com.google.api.server.spi.config.model.ApiParameterConfig in project endpoints-java by cloudendpoints.
the class SwaggerGenerator method writeApiMethod.
private void writeApiMethod(ApiMethodConfig methodConfig, ApiConfig apiConfig, Swagger swagger, GenerationContext genCtx) throws ApiConfigException {
Path path = getOrCreatePath(swagger, methodConfig);
Operation operation = new Operation();
operation.setOperationId(getOperationId(apiConfig, methodConfig));
operation.setDescription(methodConfig.getDescription());
Collection<String> pathParameters = methodConfig.getPathParameters();
for (ApiParameterConfig parameterConfig : methodConfig.getParameterConfigs()) {
switch(parameterConfig.getClassification()) {
case API_PARAMETER:
boolean isPathParameter = pathParameters.contains(parameterConfig.getName());
SerializableParameter parameter = isPathParameter ? new PathParameter() : new QueryParameter();
parameter.setName(parameterConfig.getName());
parameter.setDescription(parameterConfig.getDescription());
boolean required = isPathParameter || (!parameterConfig.getNullable() && parameterConfig.getDefaultValue() == null);
if (parameterConfig.isRepeated()) {
TypeToken<?> t = parameterConfig.getRepeatedItemSerializedType();
parameter.setType("array");
Property p = getSwaggerArrayProperty(t);
if (parameterConfig.isEnum()) {
// TODO: Not sure if this is the right check
((StringProperty) p).setEnum(getEnumValues(t));
}
parameter.setItems(p);
} else if (parameterConfig.isEnum()) {
parameter.setType("string");
parameter.setEnum(getEnumValues(parameterConfig.getType()));
parameter.setRequired(required);
} else {
parameter.setType(TYPE_TO_STRING_MAP.get(parameterConfig.getSchemaBaseType().getType()));
parameter.setFormat(TYPE_TO_FORMAT_MAP.get(parameterConfig.getSchemaBaseType().getType()));
parameter.setRequired(required);
}
operation.parameter(parameter);
break;
case RESOURCE:
TypeToken<?> requestType = parameterConfig.getSchemaBaseType();
Schema schema = genCtx.schemata.getOrAdd(requestType, apiConfig);
BodyParameter bodyParameter = new BodyParameter();
bodyParameter.setName("body");
bodyParameter.setSchema(new RefModel(schema.name()));
operation.addParameter(bodyParameter);
break;
case UNKNOWN:
throw new IllegalArgumentException("Unclassifiable parameter type found.");
case INJECTED:
// Do nothing, these are synthetic and created by the framework.
break;
}
}
Response response = new Response().description("A successful response");
if (methodConfig.hasResourceInResponse()) {
TypeToken<?> returnType = ApiAnnotationIntrospector.getSchemaType(methodConfig.getReturnType(), apiConfig);
Schema schema = genCtx.schemata.getOrAdd(returnType, apiConfig);
response.setSchema(new RefProperty(schema.name()));
}
operation.response(200, response);
writeAuthConfig(swagger, methodConfig, operation);
if (methodConfig.isApiKeyRequired()) {
List<Map<String, List<String>>> security = operation.getSecurity();
// security requirements, add a new one for just the API key.
if (security != null) {
for (Map<String, List<String>> securityEntry : security) {
securityEntry.put(API_KEY, ImmutableList.<String>of());
}
} else {
operation.addSecurity(API_KEY, ImmutableList.<String>of());
}
Map<String, SecuritySchemeDefinition> definitions = swagger.getSecurityDefinitions();
if (definitions == null || !definitions.containsKey(API_KEY)) {
swagger.securityDefinition(API_KEY, new ApiKeyAuthDefinition(API_KEY_PARAM, In.QUERY));
}
}
path.set(methodConfig.getHttpMethod().toLowerCase(), operation);
addDefinedMetricCosts(genCtx.limitMetrics, operation, methodConfig.getMetricCosts());
}
use of com.google.api.server.spi.config.model.ApiParameterConfig in project endpoints-java by cloudendpoints.
the class DiscoveryGenerator method computeParameterOrder.
private List<String> computeParameterOrder(ApiMethodConfig methodConfig) {
ImmutableSortedSet.Builder<String> queryParamBuilder = ImmutableSortedSet.naturalOrder();
Collection<String> pathParameters = methodConfig.getPathParameters();
for (ApiParameterConfig parameterConfig : methodConfig.getParameterConfigs()) {
if (parameterConfig.getClassification() == Classification.API_PARAMETER && !pathParameters.contains(parameterConfig.getName()) && !parameterConfig.getNullable()) {
queryParamBuilder.add(parameterConfig.getName());
}
}
List<String> order = new ArrayList<>(pathParameters);
order.addAll(queryParamBuilder.build());
return order;
}
Aggregations