use of org.apache.geode.rest.internal.web.exception.GemfireRestException in project geode by apache.
the class CommonCrudController method servers.
@RequestMapping(method = { RequestMethod.GET }, value = "/servers", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
@ApiOperation(value = "fetch all REST enabled servers in the DS", notes = "Find all gemfire node where developer REST service is up and running!", response = void.class)
@ApiResponses({ @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 401, message = "Invalid Username or Password."), @ApiResponse(code = 403, message = "Insufficient privileges for operation."), @ApiResponse(code = 500, message = "if GemFire throws an error or exception") })
@PreAuthorize("@securityService.authorize('CLUSTER', 'READ')")
public ResponseEntity<?> servers() {
logger.debug("Executing function to get REST enabled gemfire nodes in the DS!");
Execution function;
try {
function = FunctionService.onMembers(getAllMembersInDS());
} catch (FunctionException fe) {
throw new GemfireRestException("Disributed system does not contain any valid data node that can host REST service!", fe);
}
try {
final ResultCollector<?, ?> results = function.withCollector(new RestServersResultCollector()).execute(FindRestEnabledServersFunction.FIND_REST_ENABLED_SERVERS_FUNCTION_ID);
Object functionResult = results.getResult();
if (functionResult instanceof List<?>) {
final HttpHeaders headers = new HttpHeaders();
headers.setLocation(toUri("servers"));
try {
String functionResultAsJson = JSONUtils.convertCollectionToJson((ArrayList<Object>) functionResult);
return new ResponseEntity<>(functionResultAsJson, headers, HttpStatus.OK);
} catch (JSONException e) {
throw new GemfireRestException("Could not convert function results into Restful (JSON) format!", e);
}
} else {
throw new GemfireRestException("Function has returned results that could not be converted into Restful (JSON) format!");
}
} catch (ClassCastException cce) {
throw new GemfireRestException("Key is of an inappropriate type for this region!", cce);
} catch (NullPointerException npe) {
throw new GemfireRestException("Specified key is null and this region does not permit null keys!", npe);
} catch (LowMemoryException lme) {
throw new GemfireRestException("Server has encountered low memory condition!", lme);
} catch (IllegalArgumentException ie) {
throw new GemfireRestException("Input parameter is null! ", ie);
} catch (FunctionException fe) {
throw new GemfireRestException("Server has encountered error while executing the function!", fe);
}
}
use of org.apache.geode.rest.internal.web.exception.GemfireRestException in project geode by apache.
the class FunctionAccessController method execute.
/**
* Execute a function on Gemfire data node using REST API call. Arguments to the function are
* passed as JSON string in the request body.
*
* @param functionId represents function to be executed
* @param region list of regions on which function to be executed.
* @param members list of nodes on which function to be executed.
* @param groups list of groups on which function to be executed.
* @param filter list of keys which the function will use to determine on which node to execute
* the function.
* @param argsInBody function argument as a JSON document
*
* @return result as a JSON document
*/
@RequestMapping(method = RequestMethod.POST, value = "/{functionId:.+}", produces = { MediaType.APPLICATION_JSON_VALUE })
@ApiOperation(value = "execute function", notes = "Execute function with arguments on regions, members, or group(s). By default function will be executed on all nodes if none of (onRegion, onMembers, onGroups) specified", response = void.class)
@ApiResponses({ @ApiResponse(code = 200, message = "OK."), @ApiResponse(code = 401, message = "Invalid Username or Password."), @ApiResponse(code = 403, message = "Insufficient privileges for operation."), @ApiResponse(code = 500, message = "if GemFire throws an error or exception"), @ApiResponse(code = 400, message = "if Function arguments specified as JSON document in the request body is invalid") })
@ResponseBody
@ResponseStatus(HttpStatus.OK)
@PreAuthorize("@securityService.authorize('DATA', 'WRITE')")
public ResponseEntity<String> execute(@PathVariable("functionId") String functionId, @RequestParam(value = "onRegion", required = false) String region, @RequestParam(value = "onMembers", required = false) final String[] members, @RequestParam(value = "onGroups", required = false) final String[] groups, @RequestParam(value = "filter", required = false) final String[] filter, @RequestBody(required = false) final String argsInBody) {
Execution function = null;
functionId = decode(functionId);
if (StringUtils.hasText(region)) {
logger.debug("Executing Function ({}) with arguments ({}) on Region ({})...", functionId, ArrayUtils.toString(argsInBody), region);
region = decode(region);
try {
function = FunctionService.onRegion(getRegion(region));
} catch (FunctionException fe) {
throw new GemfireRestException(String.format("The Region identified by name (%1$s) could not found!", region), fe);
}
} else if (ArrayUtils.isNotEmpty(members)) {
logger.debug("Executing Function ({}) with arguments ({}) on Member ({})...", functionId, ArrayUtils.toString(argsInBody), ArrayUtils.toString(members));
try {
function = FunctionService.onMembers(getMembers(members));
} catch (FunctionException fe) {
throw new GemfireRestException("Could not found the specified members in distributed system!", fe);
}
} else if (ArrayUtils.isNotEmpty(groups)) {
logger.debug("Executing Function ({}) with arguments ({}) on Groups ({})...", functionId, ArrayUtils.toString(argsInBody), ArrayUtils.toString(groups));
try {
function = FunctionService.onMembers(groups);
} catch (FunctionException fe) {
throw new GemfireRestException("no member(s) are found belonging to the provided group(s)!", fe);
}
} else {
// Default case is to execute function on all existing data node in DS, document this.
logger.debug("Executing Function ({}) with arguments ({}) on all Members...", functionId, ArrayUtils.toString(argsInBody));
try {
function = FunctionService.onMembers(getAllMembersInDS());
} catch (FunctionException fe) {
throw new GemfireRestException("Distributed system does not contain any valid data node to run the specified function!", fe);
}
}
if (!ArrayUtils.isEmpty(filter)) {
logger.debug("Executing Function ({}) with filter ({})", functionId, ArrayUtils.toString(filter));
Set filter1 = ArrayUtils.asSet(filter);
function = function.withFilter(filter1);
}
final ResultCollector<?, ?> results;
try {
if (argsInBody != null) {
Object[] args = jsonToObjectArray(argsInBody);
// execute function with specified arguments
if (args.length == 1) {
results = function.setArguments(args[0]).execute(functionId);
} else {
results = function.setArguments(args).execute(functionId);
}
} else {
// execute function with no args
results = function.execute(functionId);
}
} catch (ClassCastException cce) {
throw new GemfireRestException("Key is of an inappropriate type for this region!", cce);
} catch (NullPointerException npe) {
throw new GemfireRestException("Specified key is null and this region does not permit null keys!", npe);
} catch (LowMemoryException lme) {
throw new GemfireRestException("Server has encountered low memory condition!", lme);
} catch (IllegalArgumentException ie) {
throw new GemfireRestException("Input parameter is null! ", ie);
} catch (FunctionException fe) {
throw new GemfireRestException("Server has encountered error while executing the function!", fe);
}
try {
final HttpHeaders headers = new HttpHeaders();
headers.setLocation(toUri("functions", functionId));
Object functionResult = null;
if (results instanceof NoResult)
return new ResponseEntity<>("", headers, HttpStatus.OK);
functionResult = results.getResult();
if (functionResult instanceof List<?>) {
try {
@SuppressWarnings("unchecked") String functionResultAsJson = JSONUtils.convertCollectionToJson((ArrayList<Object>) functionResult);
return new ResponseEntity<>(functionResultAsJson, headers, HttpStatus.OK);
} catch (JSONException e) {
throw new GemfireRestException("Could not convert function results into Restful (JSON) format!", e);
}
} else {
throw new GemfireRestException("Function has returned results that could not be converted into Restful (JSON) format!");
}
} catch (FunctionException fe) {
fe.printStackTrace();
throw new GemfireRestException("Server has encountered an error while processing function execution!", fe);
}
}
use of org.apache.geode.rest.internal.web.exception.GemfireRestException in project geode by apache.
the class AbstractBaseController method introspectAndConvert.
@SuppressWarnings("unchecked")
private <T> T introspectAndConvert(final T value) {
if (value instanceof Map) {
final Map rawDataBinding = (Map) value;
if (isForm(rawDataBinding)) {
rawDataBinding.put(OLD_META_DATA_PROPERTY, introspectAndConvert(rawDataBinding.get(OLD_META_DATA_PROPERTY)));
rawDataBinding.put(NEW_META_DATA_PROPERTY, introspectAndConvert(rawDataBinding.get(NEW_META_DATA_PROPERTY)));
return (T) rawDataBinding;
} else {
final String typeValue = (String) rawDataBinding.get(TYPE_META_DATA_PROPERTY);
if (typeValue == null)
return (T) new JSONObject();
// Added for the primitive types put. Not supporting primitive types
if (NumberUtils.isPrimitiveOrObject(typeValue)) {
final Object primitiveValue = rawDataBinding.get("@value");
try {
return (T) NumberUtils.convertToActualType(primitiveValue.toString(), typeValue);
} catch (IllegalArgumentException e) {
throw new GemfireRestException("Server has encountered error (illegal or inappropriate arguments).", e);
}
} else {
Assert.state(typeValue != null, "The class type of the object to persist in GemFire must be specified in JSON content using the '@type' property!");
Assert.state(ClassUtils.isPresent(String.valueOf(typeValue), Thread.currentThread().getContextClassLoader()), String.format("Class (%1$s) could not be found!", typeValue));
return (T) objectMapper.convertValue(rawDataBinding, ClassUtils.resolveClassName(String.valueOf(typeValue), Thread.currentThread().getContextClassLoader()));
}
}
}
return value;
}
use of org.apache.geode.rest.internal.web.exception.GemfireRestException in project geode by apache.
the class AbstractBaseController method putValues.
protected void putValues(final String regionNamePath, String[] keys, List<?> values) {
Map<Object, Object> map = new HashMap<Object, Object>();
if (keys.length != values.size()) {
throw new GemfireRestException("Bad request, Keys and Value size does not match");
}
for (int i = 0; i < keys.length; i++) {
Object domainObj = introspectAndConvert(values.get(i));
map.put(keys[i], domainObj);
}
if (!map.isEmpty()) {
putValues(regionNamePath, map);
}
}
use of org.apache.geode.rest.internal.web.exception.GemfireRestException in project geode by apache.
the class QueryAccessController method runNamedQuery.
/**
* Run named parametrized Query with ID
*
* @param queryId id of the OQL string
* @param arguments query bind params required while executing query
* @return query result as a JSON document
*/
@RequestMapping(method = RequestMethod.POST, value = "/{query}", produces = { MediaType.APPLICATION_JSON_VALUE })
@ApiOperation(value = "run parametrized query", notes = "run the specified named query passing in scalar values for query parameters in the GemFire cluster", response = void.class)
@ApiResponses({ @ApiResponse(code = 200, message = "Query successfully executed."), @ApiResponse(code = 401, message = "Invalid Username or Password."), @ApiResponse(code = 403, message = "Insufficient privileges for operation."), @ApiResponse(code = 400, message = "Query bind params specified as JSON document in the request body is invalid"), @ApiResponse(code = 500, message = "GemFire throws an error or exception") })
@ResponseBody
@ResponseStatus(HttpStatus.OK)
@PreAuthorize("@securityService.authorize('DATA', 'READ')")
public ResponseEntity<String> runNamedQuery(@PathVariable("query") String queryId, @RequestBody String arguments) {
logger.debug("Running named Query with ID ({})...", queryId);
queryId = decode(queryId);
if (arguments != null) {
// Its a compiled query.
// Convert arguments into Object[]
Object[] args = jsonToObjectArray(arguments);
Query compiledQuery = compiledQueries.get(queryId);
if (compiledQuery == null) {
// This is first time the query is seen by this server.
final String oql = getValue(PARAMETERIZED_QUERIES_REGION, queryId, false);
ValidationUtils.returnValueThrowOnNull(oql, new ResourceNotFoundException(String.format("No Query with ID (%1$s) was found!", queryId)));
try {
compiledQuery = getQueryService().newQuery(oql);
} catch (QueryInvalidException qie) {
throw new GemfireRestException("Syntax of the OQL queryString is invalid!", qie);
}
compiledQueries.putIfAbsent(queryId, (DefaultQuery) compiledQuery);
}
// and handle the Exceptions appropriately (500 Server Error)!
try {
Object queryResult = compiledQuery.execute(args);
return processQueryResponse(compiledQuery, args, queryResult);
} catch (FunctionDomainException fde) {
throw new GemfireRestException("A function was applied to a parameter that is improper for that function!", fde);
} catch (TypeMismatchException tme) {
throw new GemfireRestException("Bind parameter is not of the expected type!", tme);
} catch (NameResolutionException nre) {
throw new GemfireRestException("Name in the query cannot be resolved!", nre);
} catch (IllegalArgumentException iae) {
throw new GemfireRestException(" The number of bound parameters does not match the number of placeholders!", iae);
} catch (IllegalStateException ise) {
throw new GemfireRestException("Query is not permitted on this type of region!", ise);
} catch (QueryExecutionTimeoutException qete) {
throw new GemfireRestException("Query execution time is exceeded max query execution time (gemfire.Cache.MAX_QUERY_EXECUTION_TIME) configured!", qete);
} catch (QueryInvocationTargetException qite) {
throw new GemfireRestException("Data referenced in from clause is not available for querying!", qite);
} catch (QueryExecutionLowMemoryException qelme) {
throw new GemfireRestException("Query gets canceled due to low memory conditions and the resource manager critical heap percentage has been set!", qelme);
} catch (Exception e) {
throw new GemfireRestException("Error encountered while executing named query!", e);
}
} else {
throw new GemfireRestException(" Bind params either not specified or not processed properly by the server!");
}
}
Aggregations