You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by je...@apache.org on 2016/02/25 21:27:12 UTC

[24/50] [abbrv] incubator-geode git commit: Merge branch 'develop' into feature/GEODE-17

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/5c01d5f4/geode-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/AbstractBaseController.java
----------------------------------------------------------------------
diff --cc geode-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/AbstractBaseController.java
index 0000000,30f6ab2..6e425d6
mode 000000,100644..100644
--- a/geode-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/AbstractBaseController.java
+++ b/geode-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/AbstractBaseController.java
@@@ -1,0 -1,841 +1,859 @@@
+ /*
+  * Licensed to the Apache Software Foundation (ASF) under one or more
+  * contributor license agreements.  See the NOTICE file distributed with
+  * this work for additional information regarding copyright ownership.
+  * The ASF licenses this file to You under the Apache License, Version 2.0
+  * (the "License"); you may not use this file except in compliance with
+  * the License.  You may obtain a copy of the License at
+  *
+  *      http://www.apache.org/licenses/LICENSE-2.0
+  *
+  * Unless required by applicable law or agreed to in writing, software
+  * distributed under the License is distributed on an "AS IS" BASIS,
+  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  * See the License for the specific language governing permissions and
+  * limitations under the License.
+  */
+ 
+ package com.gemstone.gemfire.rest.internal.web.controllers;
+ 
+ import java.io.IOException;
+ import java.io.PrintWriter;
+ import java.io.StringWriter;
+ import java.io.UnsupportedEncodingException;
+ import java.net.URI;
+ import java.net.URLDecoder;
+ import java.util.ArrayList;
+ import java.util.Arrays;
+ import java.util.Collection;
+ import java.util.HashMap;
+ import java.util.HashSet;
+ import java.util.List;
+ import java.util.Map;
+ import java.util.Set;
+ import java.util.concurrent.atomic.AtomicLong;
+ 
+ import javax.annotation.PostConstruct;
+ 
+ import org.apache.logging.log4j.Logger;
+ import org.springframework.beans.factory.annotation.Autowired;
+ import org.springframework.http.HttpHeaders;
+ import org.springframework.http.HttpStatus;
+ import org.springframework.http.ResponseEntity;
+ import org.springframework.util.Assert;
+ import org.springframework.util.ClassUtils;
+ import org.springframework.util.CollectionUtils;
+ import org.springframework.util.StringUtils;
+ import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
+ 
+ import com.fasterxml.jackson.core.JsonParseException;
+ import com.fasterxml.jackson.core.type.TypeReference;
+ import com.fasterxml.jackson.databind.JsonMappingException;
+ import com.fasterxml.jackson.databind.ObjectMapper;
+ import com.gemstone.gemfire.SerializationException;
+ import com.gemstone.gemfire.cache.Cache;
+ import com.gemstone.gemfire.cache.CacheLoaderException;
+ import com.gemstone.gemfire.cache.CacheWriterException;
+ import com.gemstone.gemfire.cache.LowMemoryException;
+ import com.gemstone.gemfire.cache.PartitionedRegionStorageException;
+ import com.gemstone.gemfire.cache.Region;
+ import com.gemstone.gemfire.cache.TimeoutException;
+ import com.gemstone.gemfire.cache.query.QueryService;
+ import com.gemstone.gemfire.distributed.DistributedMember;
+ import com.gemstone.gemfire.distributed.internal.DistributionManager;
+ import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
+ import com.gemstone.gemfire.distributed.internal.membership.InternalDistributedMember;
+ import com.gemstone.gemfire.i18n.LogWriterI18n;
+ import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
+ import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+ import com.gemstone.gemfire.internal.logging.LogService;
+ import com.gemstone.gemfire.pdx.JSONFormatter;
+ import com.gemstone.gemfire.pdx.JSONFormatterException;
+ import com.gemstone.gemfire.pdx.PdxInstance;
+ import com.gemstone.gemfire.rest.internal.web.controllers.support.JSONTypes;
+ import com.gemstone.gemfire.rest.internal.web.controllers.support.UpdateOp;
+ import com.gemstone.gemfire.rest.internal.web.exception.DataTypeNotSupportedException;
+ import com.gemstone.gemfire.rest.internal.web.exception.GemfireRestException;
+ import com.gemstone.gemfire.rest.internal.web.exception.MalformedJsonException;
+ import com.gemstone.gemfire.rest.internal.web.exception.RegionNotFoundException;
+ import com.gemstone.gemfire.rest.internal.web.exception.ResourceNotFoundException;
++import com.gemstone.gemfire.rest.internal.web.security.RestRequestFilter;
+ import com.gemstone.gemfire.rest.internal.web.util.ArrayUtils;
+ import com.gemstone.gemfire.rest.internal.web.util.IdentifiableUtils;
+ import com.gemstone.gemfire.rest.internal.web.util.JSONUtils;
+ import com.gemstone.gemfire.rest.internal.web.util.NumberUtils;
+ import com.gemstone.gemfire.rest.internal.web.util.ValidationUtils;
+ import org.json.JSONArray;
+ import org.json.JSONException;
+ import org.json.JSONObject;
+ import org.json.JSONTokener;
+ 
+ /**
+  * AbstractBaseController class contains common functionalities required for other controllers. 
+  * @author Nilkanth Patel, John blum.
+  * @since 8.0
+  */
+ 
+ @SuppressWarnings("unused")
+ public abstract class AbstractBaseController {
+   
+   private static final Logger logger = LogService.getLogger();
+   
+   protected static final String NEW_META_DATA_PROPERTY = "@new";
+   protected static final String OLD_META_DATA_PROPERTY = "@old";
+   protected static final String TYPE_META_DATA_PROPERTY = "@type";
+   
+   protected static final String UTF_8 = "UTF-8";
+   protected static final String DEFAULT_ENCODING = UTF_8;
+   private static final AtomicLong ID_SEQUENCE = new AtomicLong(0l);
++  protected static final String AUTH_TOKEN_HEADER = "security-gfrest-authtoken";
+   
+   //private Cache cache = GemFireCacheImpl.getExisting(null);
+   
+   @Autowired
+   private ObjectMapper objectMapper;
+ 
+   @PostConstruct
+   private void init() {
+     JSONUtils.setObjectMapper(objectMapper);
+   }
+ 
+   protected Cache getCache(){
+     Cache cache = GemFireCacheImpl.getExisting();
+     Assert.state(cache != null, "The Gemfire Cache reference was not properly initialized");
+     return cache;
+   }
+   
+   protected URI toUri(final String... pathSegments) {
+     return ServletUriComponentsBuilder.fromCurrentContextPath().path(getRestApiVersion()).pathSegment(pathSegments)
+       .build().toUri();
+   }
+   
+   protected abstract String getRestApiVersion();
+   
+   protected String validateQuery(String queryInUrl, String queryInBody){
+     
+     if (!(StringUtils.hasText(queryInUrl) || StringUtils.hasText(queryInBody))) {
+       throw new GemfireRestException("could not process null value specified in query String");
+     }
+     return (StringUtils.hasText(queryInUrl) ? decode(queryInUrl) : queryInBody);
+   }
+   
+   protected String decode(final String value) {
+     if(value == null) {
+       throw new GemfireRestException("could not process null value specified in query String"); 
+     }
+     
+     return decode(value, DEFAULT_ENCODING);
+   }
+ 
+   protected PdxInstance convert(final String json){
+     try{
+       return (StringUtils.hasText(json) ? JSONFormatter.fromJSON(json) : null);
+     }catch(JSONFormatterException jpe){
+       throw new MalformedJsonException("Json doc specified is either not supported or invalid!", jpe);
+     }
+   }
+   
+   protected String convert(final PdxInstance pdxObj){
+     try {
+       return (pdxObj != null ? JSONFormatter.toJSON(pdxObj) : null);
+     } catch(JSONFormatterException jpe) {
+       throw new GemfireRestException("Requested data could not convert into REST format(JSON)!", jpe);
+     }
+   }
+   
+   protected String convert(final Iterable<PdxInstance> pdxObjs){
+     final StringBuilder buffer = new StringBuilder("[");
+     int count = 0;
+ 
+     for (final PdxInstance pdxObj : pdxObjs) {
+       final String json = convert(pdxObj);
+ 
+       if (StringUtils.hasText(json)) {
+         buffer.append(count++ > 0 ? ", " : "").append(json);
+       }
+     }
+ 
+     buffer.append("]");
+ 
+     return buffer.toString();
+   }
+ 
+   @SuppressWarnings("unchecked")
+   protected <T> T casValue(String regionNamePath, String key, String jsonData){
+     JSONObject jsonObject;
+     try {
+       jsonObject = new JSONObject(jsonData);
+       String oldValue = jsonObject.get("@old").toString();
+       String newValue = jsonObject.get("@new").toString();
+   
+       return (T) casValue(regionNamePath, key, convert(oldValue), convert(newValue));
+       
+     } catch (JSONException je) {
+       throw new MalformedJsonException("Json doc specified in request body is invalid!", je);
+     }              
+   }
+   
 -  public ResponseEntity<String> processQueryResponse (Object  queryResult, String queryId) throws JSONException {
++  public ResponseEntity<String> processQueryResponse (Object  queryResult, String queryId, HttpHeaders headers) throws JSONException {
+     if(queryResult instanceof Collection<?>){
+       Collection<Object> result = (Collection<Object>) queryResult;
+       String queryResultAsJson =  JSONUtils.convertCollectionToJson(result);
+       
 -      final HttpHeaders headers = new HttpHeaders();
 -      headers.setLocation(toUri("queries", queryId));    
++      headers.setLocation(toUri("queries", queryId)); 
++ 
+       return new ResponseEntity<String>(queryResultAsJson, headers, HttpStatus.OK);
+     }else {
+       throw new GemfireRestException("Server has encountered error while generating query result into restful format(JSON)!");
+     }
+   }
+   
+   protected Collection<PdxInstance> convertJsonArrayIntoPdxCollection(final String jsonArray) {
+     JSONArray jsonArr = null;
+     try {
+       jsonArr = new JSONArray(jsonArray);
+       Collection<PdxInstance> pdxInstances = new ArrayList<PdxInstance>();
+       
+       
+       for(int index=0; index < jsonArr.length(); index++){
+         //String element = jsonArr.getJSONObject(i).toString();
+         //String element  = jsonArr.getString(i);
+         Object object= jsonArr.get(index);
+         String element = object.toString();
+         
+         PdxInstance pi = convert(element);
+         pdxInstances.add(pi);
+       }
+       return pdxInstances;
+     
+     } catch (JSONException je) {
+       throw new MalformedJsonException("Json document specified in request body is not valid!", je);
+     }
+   }
+   
+   
+   /*
+   protected PdxInstance convertJsonIntoPdxCollection(final String jsonArray) {
+     JSONArray jsonArr = null;
+     
+       PdxInstance pi = convert(jsonArray);
+       System.out.println("Successfully converted into PdxInstance..!!");
+       return pi;
+     
+   }
+   */
+   
+   protected Object casValue(final String regionNamePath, final Object key, final Object oldValue, final Object newValue) {
+     final Region<Object, Object> region = getRegion(regionNamePath);
+     try {
+       return (region.replace(key, oldValue, newValue) ? null : region.get(key));
+     } catch(UnsupportedOperationException use){
+       throw new GemfireRestException(String.format("Resource (%1$s) configuration does not support the requested operation!", regionNamePath), use);
+     }catch(ClassCastException cce){
+       throw new GemfireRestException(String.format("Resource (%1$s) configuration does not allow to store specified key or value type in this region!", regionNamePath), cce);
+     }catch(NullPointerException npe){
+       throw new GemfireRestException(String.format("Resource (%1$s) configuration does not allow null keys or values!", regionNamePath), npe);
+     }catch(IllegalArgumentException iae){
+       throw new GemfireRestException(String.format("Resource (%1$s) configuration prevents specified data from being stored in it!", regionNamePath), iae);
+     }catch(com.gemstone.gemfire.distributed.LeaseExpiredException lee){
+       throw new GemfireRestException("Server has encountered error while processing this request!", lee);
+     }catch(TimeoutException toe){
+       throw new GemfireRestException("Server has encountered timeout error while processing this request!", toe);
+     }catch(CacheWriterException cwe){
+       throw new GemfireRestException("Server has encountered CacheWriter error while processing this request!", cwe);
+     }catch(PartitionedRegionStorageException prse){
+       throw new GemfireRestException("Requested operation could not be completed on a partitioned region!", prse);
+     }catch(LowMemoryException lme){
+       throw new GemfireRestException("Server has detected low memory while processing this request!", lme);
+     } 
+   }
+     
+   protected void replaceValue(final String regionNamePath, final Object key, final PdxInstance value) {
+     try {
+       if(getRegion(regionNamePath).replace(key, value) == null){
+         throw new ResourceNotFoundException(String.format("No resource at (%1$s) exists!", toUri(regionNamePath, String.valueOf(key))));
+       }
+     }catch(UnsupportedOperationException use){
+       throw new GemfireRestException(String.format("Resource (%1$s) configuration does not support the requested operation!", regionNamePath), use);
+     }catch(ClassCastException cce){
+       throw new GemfireRestException(String.format("Resource (%1$s) configuration does not allow to store specified key or value type in this region!", regionNamePath), cce);
+     }catch(NullPointerException npe){
+       throw new GemfireRestException(String.format("Resource (%1$s) configuration does not allow null keys or values!", regionNamePath), npe);
+     }catch(IllegalArgumentException iae){
+       throw new GemfireRestException(String.format("Resource (%1$s) configuration prevents specified data from being stored in it!", regionNamePath), iae);
+     }catch(com.gemstone.gemfire.distributed.LeaseExpiredException lee){
+       throw new GemfireRestException("Server has encountered error while processing this request!", lee);
+     }catch(TimeoutException toe){
+       throw new GemfireRestException("Server has encountered timeout error while processing this request!", toe);
+     }catch(CacheWriterException cwe){
+       throw new GemfireRestException("Server has encountered CacheWriter error while processing this request!", cwe);
+     }catch(PartitionedRegionStorageException prse){
+       throw new GemfireRestException("Requested operation could not be completed on a partitioned region!", prse);
+     }catch(LowMemoryException lme){
+       throw new GemfireRestException("Server has detected low memory while processing this request!", lme);
+     }
+   }     
+   
+   protected void replaceValue(final String regionNamePath, final Object key, final Object value) {
+     //still do we need to worry for race condition..?
+     try {
+       if(getRegion(regionNamePath).replace(key, value) == null){
+         throw new ResourceNotFoundException(String.format("No resource at (%1$s) exists!", toUri(regionNamePath, String.valueOf(key))));
+       }
+     }catch(UnsupportedOperationException use){
+       throw new GemfireRestException(String.format("Resource (%1$s) configuration does not support the requested operation!", regionNamePath), use);
+     }catch(ClassCastException cce){
+       throw new GemfireRestException(String.format("Resource (%1$s) configuration does not allow to store specified key or value type in this region!", regionNamePath), cce);
+     }catch(NullPointerException npe){
+       throw new GemfireRestException(String.format("Resource (%1$s) configuration does not allow null keys or values!", regionNamePath), npe);
+     }catch(IllegalArgumentException iae){
+       throw new GemfireRestException(String.format("Resource (%1$s) configuration prevents specified data from being stored in it!", regionNamePath), iae);
+     }catch(com.gemstone.gemfire.distributed.LeaseExpiredException lee){
+       throw new GemfireRestException("Server has encountered error while processing this request!", lee);
+     }catch(TimeoutException toe){
+       throw new GemfireRestException("Server has encountered timeout error while processing this request!", toe);
+     }catch(CacheWriterException cwe){
+       throw new GemfireRestException("Server has encountered CacheWriter error while processing this request!", cwe);
+     }catch(PartitionedRegionStorageException prse){
+       throw new GemfireRestException("Requested operation could not be completed on a partitioned region!", prse);
+     }catch(LowMemoryException lme){
+       throw new GemfireRestException("Server has detected low memory while processing this request!", lme);
+     }
+   }
+   
+   protected void putValue(final String regionNamePath, final Object key, final Object value){
+     try {
+       getRegion(regionNamePath).put(key, value);
+     } catch (NullPointerException npe) {
+       throw new GemfireRestException(String.format("Resource (%1$s) configuration does not allow null keys or values!", regionNamePath), npe);
+     } catch (ClassCastException cce) {
+       throw new GemfireRestException(String.format("Resource (%1$s) configuration does not allow to store specified key or value type in this region!", regionNamePath), cce);
+     } catch (com.gemstone.gemfire.distributed.LeaseExpiredException lee) {
+       throw new GemfireRestException("Server has encountered error while processing this request!", lee);
+     } catch (TimeoutException toe) {
+       throw new GemfireRestException("Server has encountered timeout error while processing this request!", toe);
+     } catch (CacheWriterException cwe) {
+       throw new GemfireRestException("Server has encountered CacheWriter error while processing this request!", cwe);
+     } catch (PartitionedRegionStorageException prse) {
+       throw new GemfireRestException("Requested operation could not be completed on a partitioned region!", prse);
+     } catch (LowMemoryException lme) {
+       throw new GemfireRestException("Server has detected low memory while processing this request!", lme);
+     }
+   }
+   
+   protected void deleteQueryId(final String regionNamePath, final String key){
+     getQueryStore(regionNamePath).remove(key);
+   }
+   
+   protected void deleteNamedQuery(final String regionNamePath, final String key){
+     //Check whether query ID exist in region or not
+     checkForQueryIdExist(regionNamePath, key);
+     deleteQueryId(regionNamePath, key);  
+   }
+   
+   protected void checkForQueryIdExist(String region, String key) {
+     if(!getQueryStore(region).containsKey(key)) {
+       throw new ResourceNotFoundException(String.format("Named query (%1$s) does not exist!", key));
+     }
+   }
+   
+   protected Region<String, String> getQueryStore(final String namePath) {
+     return  ValidationUtils.returnValueThrowOnNull(getCache().<String, String>getRegion(namePath),
+       new GemfireRestException(String.format("Query store does not exist!",
+         namePath)));
+   }
+   
+   protected String getQueryIdValue(final String regionNamePath, final String key) {
+     Assert.notNull(key, "queryId cannot be null!");
+     try {
+       return  getQueryStore(regionNamePath).get(key);
+     } catch(NullPointerException npe) {
+       throw new GemfireRestException("NULL query ID or query string is not supported!", npe);
+     } catch(IllegalArgumentException iae) {
+       throw new GemfireRestException("Server has not allowed to perform the requested operation!", iae);
+     } catch(com.gemstone.gemfire.distributed.LeaseExpiredException lee) {
+       throw new GemfireRestException("Server has encountered error while processing this request!", lee);
+     } catch(TimeoutException te) {
+       throw new GemfireRestException("Server has encountered timeout error while processing this request!", te);
+     } 
+   }
+   
+   protected void updateNamedQuery(final String regionNamePath, final String key, final String value){
+     try {
+       getQueryStore(regionNamePath).put(key, value);
+     } catch (NullPointerException npe) {
+       throw new GemfireRestException("NULL query ID or query string is not supported!", npe);
+     } catch (ClassCastException cce) {
+       throw new GemfireRestException("specified queryId or query string is not supported!", cce);
+     } catch (com.gemstone.gemfire.distributed.LeaseExpiredException lee) {
+       throw new GemfireRestException("Server has encountered error while processing this request!", lee);
+     } catch (TimeoutException toe) {
+       throw new GemfireRestException("Server has encountered timeout error while processing this request!", toe);
+     } catch (LowMemoryException lme) {
+       throw new GemfireRestException("Server has detected low memory while processing this request!", lme);
+     }
+   }
+   
+   @SuppressWarnings("unchecked")
+   protected <T> T createNamedQuery(final String regionNamePath, final String key, final String value){
+     try {
+       return (T) getQueryStore(regionNamePath).putIfAbsent(key, value);
+     } catch(UnsupportedOperationException use){
+       throw new GemfireRestException("Requested operation is not supported!", use);
+     } catch(ClassCastException cce){
+       throw new GemfireRestException("Specified queryId or query string is not supported!", cce);
+     } catch(NullPointerException npe){
+       throw new GemfireRestException("NULL query ID or query string is not supported!", npe);
+     } catch(IllegalArgumentException iae){
+       throw new GemfireRestException("Configuration does not allow to perform the requested operation!", iae);
+     } catch(com.gemstone.gemfire.distributed.LeaseExpiredException lee){
+       throw new GemfireRestException("Server has encountered error while processing this request!", lee);
+     } catch(TimeoutException toe){
+       throw new GemfireRestException("Server has encountered timeout error while processing this request!", toe);
+     } catch(LowMemoryException lme){
+       throw new GemfireRestException("Server has detected low memory while processing this request!", lme);
+     }
+   }
+   
+   protected void putPdxValues(final String regionNamePath, final Map<Object, PdxInstance> map){
+     try {
+     getRegion(regionNamePath).putAll(map);
+     } catch (LowMemoryException lme) {
+       throw new GemfireRestException("low memory condition is detected.", lme);
+     }
+   }
+   
+   protected void putValues(final String regionNamePath, final Map<Object, Object> values) {
+     getRegion(regionNamePath).putAll(values);
+   }
+   
+   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);
+     }
+   }
+   
+   @SuppressWarnings("unchecked")
+   protected <T> T postValue(final String regionNamePath, final Object key, final Object value){ 
+     try {
+       return (T) getRegion(regionNamePath).putIfAbsent(key, value);
+     }catch(UnsupportedOperationException use){
+       throw new GemfireRestException(String.format("Resource (%1$s) configuration does not support the requested operation!", regionNamePath), use);
+     }catch(ClassCastException cce){
+       throw new GemfireRestException(String.format("Resource (%1$s) configuration does not allow to store specified key or value type in this region!", regionNamePath), cce);
+     }catch(NullPointerException npe){
+       throw new GemfireRestException(String.format("Resource (%1$s) configuration does not allow null keys or values!", regionNamePath), npe);
+     }catch(IllegalArgumentException iae){
+       throw new GemfireRestException(String.format("Resource (%1$s) configuration prevents specified data from being stored in it!", regionNamePath), iae);
+     }catch(com.gemstone.gemfire.distributed.LeaseExpiredException lee){
+       throw new GemfireRestException("Server has encountered error while processing this request!", lee);
+     }catch(TimeoutException toe){
+       throw new GemfireRestException("Server has encountered timeout error while processing this request!", toe);
+     }catch(CacheWriterException cwe){
+       throw new GemfireRestException("Server has encountered CacheWriter error while processing this request!", cwe);
+     }catch(PartitionedRegionStorageException prse){
+       throw new GemfireRestException("Requested operation could not be completed on a partitioned region!", prse);
+     }catch(LowMemoryException lme){
+       throw new GemfireRestException("Server has detected low memory while processing this request!", lme);
+     }
+   }
+  
+   protected Object getActualTypeValue(final String value, final String valueType){
+     Object actualValue = value;
+     if(valueType != null){
+       try {
+         actualValue  = NumberUtils.convertToActualType(value, valueType);
+       } catch (IllegalArgumentException ie) {
+         throw new GemfireRestException(ie.getMessage(), ie);
+       } 
+     }
+     return actualValue;
+   }
+   
+   protected String generateKey(final String existingKey){
+     return generateKey(existingKey, null);
+   }
+   
+   protected String generateKey(final String existingKey, final Object domainObject) {
+     Object domainObjectId = IdentifiableUtils.getId(domainObject);
+     String newKey;
+ 
+     if (StringUtils.hasText(existingKey)) {
+       newKey = existingKey;
+       if (NumberUtils.isNumeric(newKey) && domainObjectId == null) {
+         final Long newId = IdentifiableUtils.createId(NumberUtils.parseLong(newKey));
+         if (newKey.equals(newId.toString())) {
+           IdentifiableUtils.setId(domainObject, newId);
+         }
+       }
+     }
+     else if (domainObjectId != null) {
+       final Long domainObjectIdAsLong = NumberUtils.longValue(domainObjectId);
+       if (domainObjectIdAsLong != null) {
+         final Long newId = IdentifiableUtils.createId(domainObjectIdAsLong);
+         if (!domainObjectIdAsLong.equals(newId)) {
+           IdentifiableUtils.setId(domainObject, newId);
+         }
+         newKey = String.valueOf(newId);
+       }
+       else {
+         newKey = String.valueOf(domainObjectId);
+       }
+     }
+     else {
+       domainObjectId = IdentifiableUtils.createId();
+       newKey = String.valueOf(domainObjectId);
+       IdentifiableUtils.setId(domainObject, domainObjectId);
+     }
+ 
+     return newKey;
+   }
+   
+   protected String decode(final String value, final String encoding) {
+     try {
+       return URLDecoder.decode(value, encoding);
+     }
+     catch (UnsupportedEncodingException e) {
+       throw new GemfireRestException("Server has encountered unsupported encoding!");
+     }
+   }
+   
+   @SuppressWarnings("unchecked")
+   protected <T> Region<Object, T> getRegion(final String namePath) {
+     return (Region<Object, T>) ValidationUtils.returnValueThrowOnNull(getCache().getRegion(namePath),
+       new RegionNotFoundException(String.format("The Region identified by name (%1$s) could not be found!",
+         namePath)));
+   }
+   
+   protected void checkForKeyExist(String region, String key) {
+     if(!getRegion(region).containsKey(key)) {
+       throw new ResourceNotFoundException(String.format("Key (%1$s) does not exist for region (%2$s) in cache!", key, region));
+     }
+   }
+   
+   protected List<String> checkForMultipleKeysExist(String region, String... keys) {
+     List<String> unknownKeys = new ArrayList<String>();
+     for (int index=0; index < keys.length; index++) {
+       if(!getRegion(region).containsKey(keys[index])) {
+         //throw new ResourceNotFoundException(String.format("Key [(%1$s)] does not exist for region [(%2$s)] in cache!", key, region));
+         unknownKeys.add(keys[index]);
+       }
+     }
+     return unknownKeys;
+   }
+   
+   protected Object[] getKeys(final String regionNamePath, Object[] keys) {
+     return (!(keys == null || keys.length == 0) ? keys : getRegion(regionNamePath).keySet().toArray());
+   }
+   
+   protected <T> Map<Object, T> getValues(final String regionNamePath, Object... keys)  {
+     try{ 
+       final Region<Object, T> region = getRegion(regionNamePath);
+       final Map<Object, T> entries = region.getAll(Arrays.asList(getKeys(regionNamePath, keys)));
+       return entries;
+     } catch(SerializationException se) {
+       throw new DataTypeNotSupportedException("The resource identified could not convert into the supported content characteristics (JSON)!", se);
+     }
+   }
+   protected <T> Map<Object, T> getValues(final String regionNamePath, String... keys) {
+     return getValues(regionNamePath, (Object[])keys);
+   }  
+   
+   protected <T extends PdxInstance> Collection<T> getPdxValues(final String regionNamePath, final Object... keys) {
+     final Region<Object, T> region = getRegion(regionNamePath);
+     final Map<Object, T> entries = region.getAll(Arrays.asList(getKeys(regionNamePath, keys)));
+     
+     return entries.values();
+   }
+   
+   protected void deleteValue(final String regionNamePath, final Object key){
+     getRegion(regionNamePath).remove(key);
+   }
+   
+   protected void deleteValues(final String regionNamePath, final Object...keys){
+     //Check whether all keys exist in cache or not
+     for(final Object key : keys){
+       checkForKeyExist(regionNamePath, key.toString());
+     }
+     
+     for(final Object key : keys){
+       deleteValue(regionNamePath, key);
+     }
+   }
+   
+   protected void deleteValues(String regionNamePath){
+     try{
+       getRegion(regionNamePath).clear();
+     }catch(UnsupportedOperationException ue){
+       throw new GemfireRestException("Requested operation not allowed on partition region", ue);
+     }
+   }
+   
+   private boolean isForm(final Map<Object, Object> rawDataBinding) {
+     return (!rawDataBinding.containsKey(TYPE_META_DATA_PROPERTY)
+       && rawDataBinding.containsKey(OLD_META_DATA_PROPERTY)
+       && rawDataBinding.containsKey(NEW_META_DATA_PROPERTY));
+   }
+   
+   @SuppressWarnings("unchecked")
+   protected <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);
+         
+         //Added for the primitive types put. Not supporting primitive types 
+         if(NumberUtils.isPrimitiveOrObject(typeValue.toString())){ 
+           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;
+   }
+ 
+   protected String convertErrorAsJson(String errorMessage) {
+     return ("{" + "\"cause\"" + ":" + "\"" + errorMessage + "\"" + "}");
+   }
+ 
+   protected String convertErrorAsJson(Throwable t) {
+     StringWriter writer = new StringWriter();
+     t.printStackTrace(new PrintWriter(writer));
+     return String.format("{\"message\" : \"%1$s\", \"stackTrace\" : \"%2$s\"}", t.getMessage(), writer.toString());
+   }
+ 
+   protected Map<?,?> convertJsonToMap(final String jsonString) {
+     Map<String,String> map = new HashMap<String,String>();
+     
+     //convert JSON string to Map
+     try {
+       map = objectMapper.readValue(jsonString, new TypeReference<HashMap<String,String>>(){});
+     } catch (JsonParseException e) {
+       throw new MalformedJsonException("Bind params specified as JSON document in the request is incorrect!", e);
+     } catch (JsonMappingException e) {
+       throw new MalformedJsonException("Server unable to process bind params specified as JSON document in the request!", e);
+     } catch (IOException e) {
+       throw new GemfireRestException("Server has encountered error while process this request!", e);
+     }
+     return map;
+  }
+   
+   protected Object jsonToObject(final String jsonString) {
+     return introspectAndConvert(convertJsonToMap(jsonString));  
+   }
+   
+   protected Object[] jsonToObjectArray(final String arguments) {
+     final JSONTypes jsonType = validateJsonAndFindType(arguments);
+     if(JSONTypes.JSON_ARRAY.equals(jsonType)){
+       try {
+         JSONArray jsonArray  = new JSONArray(arguments);
+         Object[] args =  new Object[jsonArray.length()];
+         for(int index=0; index < jsonArray.length(); index++) {
+           args[index] = jsonToObject(jsonArray.get(index).toString());  
+         }
+         return args;
+       } catch (JSONException je) {
+         throw new MalformedJsonException("Json document specified in request body is not valid!", je);
+       }
+     } else if (JSONTypes.JSON_OBJECT.equals(jsonType)) {
+       return new Object[] { jsonToObject(arguments) };
+     } else {
+       throw new MalformedJsonException("Json document specified in request body is not valid!");
+     } 
+   }
+   
 -  public ResponseEntity<String> updateSingleKey(final String region, final String key, final String json, final String opValue){    
++  public ResponseEntity<String> updateSingleKey(final String region, final String key, final String json, final String opValue, HttpHeaders headers){    
+     
+     final JSONTypes jsonType = validateJsonAndFindType(json);
+     
+     final UpdateOp op = UpdateOp.valueOf(opValue.toUpperCase());
+     String existingValue = null;
+     
+     switch (op) {
+       case CAS:  
+         PdxInstance existingPdxObj = casValue(region, key, json);
+         existingValue = convert(existingPdxObj);
+         break;
+         
+       case REPLACE:
+         replaceValue(region, key, convert(json));
+         break;
+         
+       case PUT:
+       default:
+         if(JSONTypes.JSON_ARRAY.equals(jsonType)){
+           putValue(region, key, convertJsonArrayIntoPdxCollection(json));
+           //putValue(region, key, convertJsonIntoPdxCollection(json));
+         }else {
+           putValue(region, key, convert(json));
+         }
+     }
+         
 -    final HttpHeaders headers = new HttpHeaders();
+     headers.setLocation(toUri(region, key));
+     return new ResponseEntity<String>(existingValue, headers, (existingValue == null ? HttpStatus.OK : HttpStatus.CONFLICT));        
+   }
+   
+   
 -  public ResponseEntity<String> updateMultipleKeys(final String region, final String[] keys, final String json){
++  public ResponseEntity<String> updateMultipleKeys(final String region, final String[] keys, final String json, HttpHeaders headers){
+     
+     JSONArray jsonArr = null;
+     try {
+       jsonArr = new JSONArray(json);  
+     } catch (JSONException e) {
+       throw new MalformedJsonException("JSON document specified in the request is incorrect", e);
+     }
+   
+     if(jsonArr.length() != keys.length){
+       throw new MalformedJsonException("Each key must have corresponding value (JSON document) specified in the request");
+     }
+     
+     Map<Object, PdxInstance> map = new HashMap<Object, PdxInstance>();    
+     for(int i=0; i<keys.length; i++){
+       if (logger.isDebugEnabled()) {
+         logger.debug("Updating (put) Json document ({}) having key ({}) in Region ({})", json, keys[i], region);
+       }
+         
+       try {
+         PdxInstance pdxObj = convert( jsonArr.getJSONObject(i).toString());    
+         map.put(keys[i], pdxObj);
+       } catch (JSONException e) {
+         throw new MalformedJsonException(String.format("JSON document at index (%1$s) in the request body is incorrect", i), e);
+       }
+     }
+      
+     if(!CollectionUtils.isEmpty(map)){ 
+       putPdxValues(region, map);
+     }
 -    
 -    HttpHeaders headers = new HttpHeaders();
++   
+     headers.setLocation(toUri(region, StringUtils.arrayToCommaDelimitedString(keys)));
+     return new ResponseEntity<String>(headers, HttpStatus.OK);
+   }
+   
+   public JSONTypes validateJsonAndFindType(String json){
+     try {
+       Object jsonObj = new JSONTokener(json).nextValue();
+     
+       if (jsonObj instanceof JSONObject){
+         return JSONTypes.JSON_OBJECT;    
+       }else if (jsonObj instanceof JSONArray){  
+         return JSONTypes.JSON_ARRAY;  
+       }else {
+         return JSONTypes.UNRECOGNIZED_JSON;
+       }
+     } catch (JSONException je) {
+       throw new MalformedJsonException("JSON document specified in the request is incorrect", je);
+     }    
+   }
+   
+   protected QueryService getQueryService() {
+     return getCache().getQueryService();
+   }
+ 
+   @SuppressWarnings("unchecked")
+   protected <T> T getValue(final String regionNamePath, final Object key) {
+     Assert.notNull(key, "The Cache Region key to read the value for cannot be null!");
+   
+     Region r = getRegion(regionNamePath);
+     try {
+       Object value = r.get(key);
+       return (T) value;
+     } catch(SerializationException se) {
+       throw new DataTypeNotSupportedException("The resource identified could not convert into the supported content characteristics (JSON)!", se);
+     } catch(NullPointerException npe) {
+       throw new GemfireRestException(String.format("Resource (%1$s) configuration does not allow null keys!", regionNamePath), npe);
+     } catch(IllegalArgumentException iae) {
+       throw new GemfireRestException(String.format("Resource (%1$s) configuration does not allow requested operation on specified key!", regionNamePath), iae);
+     } catch(com.gemstone.gemfire.distributed.LeaseExpiredException lee) {
+       throw new GemfireRestException("Server has encountered error while processing this request!", lee);
+     } catch(TimeoutException te) {
+       throw new GemfireRestException("Server has encountered timeout error while processing this request!", te);
+     } catch(CacheLoaderException cle){
+       throw new GemfireRestException("Server has encountered CacheLoader error while processing this request!", cle);
+     } catch(PartitionedRegionStorageException prse) {
+       throw new GemfireRestException("CacheLoader could not be invoked on partitioned region!", prse);
+     }
+     
+   }
+  
+   protected Set<DistributedMember> getMembers(final String... memberIdNames) {
+     
+     ValidationUtils.returnValueThrowOnNull(memberIdNames, new GemfireRestException("No member found to run function"));
+     final Set<DistributedMember> targetedMembers = new HashSet<DistributedMember>(ArrayUtils.length(memberIdNames));
+     final List<String> memberIdNameList = Arrays.asList(memberIdNames);
+     GemFireCacheImpl c = (GemFireCacheImpl)getCache();
+     Set<DistributedMember> distMembers =  c.getDistributedSystem().getAllOtherMembers();
+    
+     //Add the local node to list
+     distMembers.add(c.getDistributedSystem().getDistributedMember());  
+     for (DistributedMember member : distMembers) {
+       if (memberIdNameList.contains(member.getId()) || memberIdNameList.contains(member.getName())) {
+         targetedMembers.add(member);
+       }
+     }
+     return targetedMembers;
+   }
+ 
+   protected Set<DistributedMember> getAllMembersInDS() {
+     GemFireCacheImpl c = (GemFireCacheImpl)getCache();
+     Set<DistributedMember> distMembers =  c.getDistributedSystem().getAllOtherMembers();
+     final Set<DistributedMember> targetedMembers = new HashSet<DistributedMember>();
+     
+     //find valid data nodes, i.e non locator, non-admin, non-loner nodes
+     for (DistributedMember member : distMembers) {
+       InternalDistributedMember idm = (InternalDistributedMember)member;
+       if (idm.getVmKind() == DistributionManager.NORMAL_DM_TYPE) {
+         targetedMembers.add(member);
+       }
+     }
+     //Add the local node to list
+     targetedMembers.add(c.getDistributedSystem().getDistributedMember());
+     return targetedMembers;
+   }
++  
++  protected void setAuthTokenHeader(HttpHeaders headers) {
++    Map<String, Object> envMap = (Map<String, Object>)RestRequestFilter.getEnvironment();
++    boolean isSecurityEnabled = (boolean) envMap.get("isSecurityEnabled");
++  
++    if(isSecurityEnabled == false)
++      return;
++  
++    headers.set(AUTH_TOKEN_HEADER,(String)envMap.get("authToken"));
++    
++  }
++  
++  protected String getAuthToken(){
++    Map<String, Object> envMap = (Map<String, Object>)RestRequestFilter.getEnvironment();
++    return (String)envMap.get("authToken");
++  }
++  
+ }
++

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/5c01d5f4/geode-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/BaseControllerAdvice.java
----------------------------------------------------------------------
diff --cc geode-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/BaseControllerAdvice.java
index 0000000,81714f9..3fb42fe
mode 000000,100644..100644
--- a/geode-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/BaseControllerAdvice.java
+++ b/geode-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/BaseControllerAdvice.java
@@@ -1,0 -1,147 +1,187 @@@
+ /*
+  * Licensed to the Apache Software Foundation (ASF) under one or more
+  * contributor license agreements.  See the NOTICE file distributed with
+  * this work for additional information regarding copyright ownership.
+  * The ASF licenses this file to You under the Apache License, Version 2.0
+  * (the "License"); you may not use this file except in compliance with
+  * the License.  You may obtain a copy of the License at
+  *
+  *      http://www.apache.org/licenses/LICENSE-2.0
+  *
+  * Unless required by applicable law or agreed to in writing, software
+  * distributed under the License is distributed on an "AS IS" BASIS,
+  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  * See the License for the specific language governing permissions and
+  * limitations under the License.
+  */
+ 
+ package com.gemstone.gemfire.rest.internal.web.controllers;
+ 
+ import java.io.PrintWriter;
+ import java.io.StringWriter;
+ 
+ import org.apache.logging.log4j.Logger;
+ import org.springframework.http.HttpStatus;
+ import org.springframework.web.HttpRequestMethodNotSupportedException;
+ import org.springframework.web.bind.annotation.ControllerAdvice;
+ import org.springframework.web.bind.annotation.ExceptionHandler;
+ import org.springframework.web.bind.annotation.ResponseBody;
+ import org.springframework.web.bind.annotation.ResponseStatus;
+ 
+ import com.gemstone.gemfire.internal.logging.LogService;
+ import com.gemstone.gemfire.rest.internal.web.exception.DataTypeNotSupportedException;
+ import com.gemstone.gemfire.rest.internal.web.exception.GemfireRestException;
+ import com.gemstone.gemfire.rest.internal.web.exception.MalformedJsonException;
+ import com.gemstone.gemfire.rest.internal.web.exception.RegionNotFoundException;
+ import com.gemstone.gemfire.rest.internal.web.exception.ResourceNotFoundException;
++import com.gemstone.gemfire.security.AuthenticationFailedException;
++import com.gemstone.gemfire.security.AuthenticationRequiredException;
++import com.gemstone.gemfire.security.NotAuthorizedException;
+ 
+ /**
+  * The CrudControllerAdvice class handles exception thrown while serving the REST request
+  * <p/>
+  * @author Nilkanth Patel, John Blum
+  * @since 8.0
+  */
+ 
 -@ControllerAdvice
++//@ControllerAdvice
+ @SuppressWarnings("unused")
+ public class BaseControllerAdvice extends AbstractBaseController{
+ 
+   private static final Logger logger = LogService.getLogger();
+   
+   protected static final String REST_API_VERSION = "/v1";
+    
+   @Override
+   protected String getRestApiVersion() {
+     return REST_API_VERSION;
+   }
+   /**
+    * Handles both ResourceNotFoundExceptions and specifically, RegionNotFoundExceptions, occurring when a resource
+    * or a Region (a.k.a. resource) does not exist in GemFire.
+    * <p/>
+    * @param e the RuntimeException thrown when the accessed/requested resource does not exist in GemFire.
+    * @return the String message from the RuntimeException.
+    */
+   @ExceptionHandler({ RegionNotFoundException.class, ResourceNotFoundException.class })
+   @ResponseBody
+   @ResponseStatus(HttpStatus.NOT_FOUND)
+   public String handle(final RuntimeException e) {
+     return convertErrorAsJson(e.getMessage());
+   }
+ 
+   /**
+    * Handles MalformedJsonFoundException, occurring when REST service encounters incorrect or malformed JSON document
+    * <p/>
+    * @param e the RuntimeException thrown when malformed JSON is encounterd.
+    * @return the String message from the RuntimeException.
+    */
+   @ExceptionHandler({ MalformedJsonException.class })
+   @ResponseBody
+   @ResponseStatus(HttpStatus.BAD_REQUEST)
+   public String handleException(final RuntimeException e) {
+     return convertErrorAsJson(e.getMessage());
+   }
+   
+   /**
+    * Handles any GemfireRestException thrown by a REST API web service endpoint, HTTP request handler method.
+    * <p/>
+    * @param ge the GemfireRestException thrown when it found problem processing REST request.
+    * @return the String message from the RuntimeException.
+    */
+   @ExceptionHandler(GemfireRestException.class)
+   @ResponseBody
+   @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
+   public String handleException(final GemfireRestException ge) {
+     return convertErrorAsJson(ge);
+   }
+   
+   /**
+    * Handles any DataTypeNotSupportedException thrown by a REST API web service endpoint, HTTP request handler method.
+    * <p/>
+    * @param tns the DataTypeNotSupportedException thrown if problem occurs in cache values to JSON conversion.
+    * @return the String message from the RuntimeException.
+    */
+   @ExceptionHandler(DataTypeNotSupportedException.class)
+   @ResponseBody
+   @ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
+   public String handleException(final DataTypeNotSupportedException tns) {
+     return convertErrorAsJson(tns.getMessage());
+   }
+   
+   /**
+    * Handles HttpRequestMethodNotSupportedException thrown by a REST API web service when request is 
+    * received with unsupported HTTP method.
+    * <p/>
+    * @param e the HttpRequestMethodNotSupportedException thrown when REST request is received with NOT support methods.
+    * @return the String message from the RuntimeException.
+    */
+   @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
+   @ResponseBody
+   @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
+   public String handleException(final HttpRequestMethodNotSupportedException e) {
+     return convertErrorAsJson(e.getMessage());
+   }
+  
+   /**
+    * Handles any Exception thrown by a REST API web service endpoint, HTTP request handler method.
+    * <p/>
+    * @param cause the Exception causing the error.
+    * @return a ResponseEntity with an appropriate HTTP status code (500 - Internal Server Error) and HTTP response body
+    * containing the stack trace of the Exception.
+    */
+   @ExceptionHandler(Throwable.class)
+   @ResponseBody
+   @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
+   public String handleException(final Throwable cause) {
+     final StringWriter stackTraceWriter = new StringWriter();
+     cause.printStackTrace(new PrintWriter(stackTraceWriter));
+     final String stackTrace = stackTraceWriter.toString();
+     
+     if(logger.isDebugEnabled()){
+       logger.debug(stackTrace);  
+     }
+     
+     return convertErrorAsJson(cause.getMessage());
+   }
+   
++  /**
++   * Handles NotAuthorizedException, occurring when REST service encounters unAuthorized access.
++   * <p/>
++   * @param e the RuntimeException thrown when request is not authorized to perform the operation.
++   * @return the String message from the RuntimeException.
++   */
++  @ExceptionHandler({ NotAuthorizedException.class })
++  @ResponseBody
++  @ResponseStatus(HttpStatus.UNAUTHORIZED)
++  public String handleException(final NotAuthorizedException e) {
++    return convertErrorAsJson(e.getMessage());
++  }
++  
++  /**
++   * Handles AuthenticationFailedException, occurring when REST service can not authenticate the request.
++   * <p/>
++   * @param e the RuntimeException thrown when request is not authenticated to perform the operation.
++   * @return the String message from the RuntimeException.
++   */
++  @ExceptionHandler({ AuthenticationFailedException.class })
++  @ResponseBody
++  @ResponseStatus(HttpStatus.FORBIDDEN)
++  public String handleException(final AuthenticationFailedException e) {
++    return convertErrorAsJson(e.getMessage());
++  }
++  
++  /**
++   * Handles AuthenticationRequiredException, occurring when REST service can not find the security credentials i nthe request.
++   * <p/>
++   * @param e the RuntimeException thrown when request does not contains security credentials for authentication.
++   * @return the String message from the RuntimeException.
++   */
++  @ExceptionHandler({ AuthenticationRequiredException.class })
++  @ResponseBody
++  @ResponseStatus(HttpStatus.FORBIDDEN)
++  public String handleException(final AuthenticationRequiredException e) {
++    return convertErrorAsJson(e.getMessage());
++  }
+ }
 -

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/5c01d5f4/geode-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/CommonCrudController.java
----------------------------------------------------------------------
diff --cc geode-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/CommonCrudController.java
index 0000000,a2b3e71..f309411
mode 000000,100644..100644
--- a/geode-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/CommonCrudController.java
+++ b/geode-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/CommonCrudController.java
@@@ -1,0 -1,249 +1,312 @@@
+ /*
+  * Licensed to the Apache Software Foundation (ASF) under one or more
+  * contributor license agreements.  See the NOTICE file distributed with
+  * this work for additional information regarding copyright ownership.
+  * The ASF licenses this file to You under the Apache License, Version 2.0
+  * (the "License"); you may not use this file except in compliance with
+  * the License.  You may obtain a copy of the License at
+  *
+  *      http://www.apache.org/licenses/LICENSE-2.0
+  *
+  * Unless required by applicable law or agreed to in writing, software
+  * distributed under the License is distributed on an "AS IS" BASIS,
+  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  * See the License for the specific language governing permissions and
+  * limitations under the License.
+  */
+ 
+ package com.gemstone.gemfire.rest.internal.web.controllers;
+ 
+ import java.util.ArrayList;
+ import java.util.List;
+ import java.util.Set;
+ 
+ import org.apache.logging.log4j.Logger;
+ import org.springframework.http.HttpHeaders;
+ import org.springframework.http.HttpStatus;
+ import org.springframework.http.MediaType;
+ import org.springframework.http.ResponseEntity;
+ import org.springframework.web.bind.annotation.PathVariable;
+ import org.springframework.web.bind.annotation.RequestMapping;
+ import org.springframework.web.bind.annotation.RequestMethod;
+ 
+ import com.gemstone.gemfire.cache.LowMemoryException;
+ import com.gemstone.gemfire.cache.Region;
+ import com.gemstone.gemfire.cache.execute.Execution;
+ import com.gemstone.gemfire.cache.execute.FunctionException;
+ import com.gemstone.gemfire.cache.execute.FunctionService;
+ import com.gemstone.gemfire.cache.execute.ResultCollector;
++import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
+ import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
+ import com.gemstone.gemfire.internal.logging.LogService;
++import com.gemstone.gemfire.internal.security.AuthorizeRequest;
+ import com.gemstone.gemfire.internal.util.ArrayUtils;
+ import com.gemstone.gemfire.rest.internal.web.controllers.support.RestServersResultCollector;
+ import com.gemstone.gemfire.rest.internal.web.exception.GemfireRestException;
++import com.gemstone.gemfire.rest.internal.web.security.AuthorizationProvider;
++import com.gemstone.gemfire.rest.internal.web.security.RestRequestFilter;
+ import com.gemstone.gemfire.rest.internal.web.util.JSONUtils;
++import com.gemstone.gemfire.security.NotAuthorizedException;
+ import org.json.JSONException;
+ import com.wordnik.swagger.annotations.ApiOperation;
+ import com.wordnik.swagger.annotations.ApiResponse;
+ import com.wordnik.swagger.annotations.ApiResponses;
+ 
+ /**
+  * The CommonCrudController serves REST Requests related to listing regions, 
+  * listing keys in region, delete keys or delete all data in region.
+  * <p/>
+  * @author Nilkanth Patel, john blum
+  * @since 8.0
+  */
+ 
+ @SuppressWarnings("unused")
+ public abstract class CommonCrudController extends AbstractBaseController {
+   
+   private static final Logger logger = LogService.getLogger();
+   
+   /**
+    * list all available resources (Regions) in the GemFire cluster
+    * @return JSON document containing result
+    */
+   @RequestMapping(method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE })
+   @ApiOperation(
+     value = "list all resources (Regions)",
+     notes = "List all available resources (Regions) in the GemFire cluster",
+     response  = void.class
+   )
+   @ApiResponses( {
+     @ApiResponse( code = 200, message = "OK." ),
+     @ApiResponse( code = 500, message = "GemFire throws an error or exception." )   
+   } )
+   public ResponseEntity<?> regions() {
+     
+     if(logger.isDebugEnabled()){
+       logger.debug("Listing all resources (Regions) in GemFire...");
+     }
+     
 -    final Set<Region<?, ?>> regions = getCache().rootRegions();
 -    String listRegionsAsJson =  JSONUtils.formulateJsonForListRegions(regions, "regions");
+     final HttpHeaders headers = new HttpHeaders();  
+     headers.setLocation(toUri());
++    
++    //Do request(Pre) authorization if security is enabled.
++    if(AuthorizationProvider.isSecurityEnabled()){
++      setAuthTokenHeader(headers);
++      AuthorizationProvider.init();
++      try{
++        AuthorizationProvider.listRegionsAuthorize(OperationCode.LIST, true, "LIST_REGIONS");
++      }catch(NotAuthorizedException nae){
++        return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
++      }
++    }
++   
++    final Set<Region<?, ?>> regions = getCache().rootRegions();
++    String listRegionsAsJson =  JSONUtils.formulateJsonForListRegions(regions, "regions");
++    
+     return new ResponseEntity<String>(listRegionsAsJson, headers, HttpStatus.OK);
+   }
+   
+   /**
+    * List all keys for the given region in the GemFire cluster
+    * @param region gemfire region
+    * @return JSON document containing result
+    */
+   @RequestMapping(method = RequestMethod.GET, value = "/{region}/keys", 
+                   produces = { MediaType.APPLICATION_JSON_VALUE } )
+   @ApiOperation(
+     value = "list all keys",
+     notes = "List all keys in region",
+     response  = void.class
+   )
+   @ApiResponses( {
+     @ApiResponse( code = 200, message = "OK" ),
+     @ApiResponse( code = 404, message = "Region does not exist" ),
+     @ApiResponse( code = 500, message = "GemFire throws an error or exception" )   
+   } )
+   public ResponseEntity<?> keys(@PathVariable("region") String region){ 
+     
+     if(logger.isDebugEnabled()){
 -      logger.debug("Reading all Keys in Region ({})...", region);
++      logger.debug("Listing all Keys in Region ({})...", region);
+     }
+     
+     region = decode(region);
 -    
 -    Object[] keys = getKeys(region, null);  
 -    
 -    String listKeysAsJson =  JSONUtils.formulateJsonForListKeys(keys, "keys");
+     final HttpHeaders headers = new HttpHeaders();  
+     headers.setLocation(toUri(region, "keys"));
++    
++    //Request(Pre) authorization if security is enabled.
++    if(AuthorizationProvider.isSecurityEnabled()){
++      setAuthTokenHeader(headers);
++      AuthorizationProvider.init();
++      try{
++        AuthorizationProvider.keySetAuthorize(region);
++      }catch(NotAuthorizedException nae) {
++        return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
++      }
++    }
++    
++    Set<Object> keys = getRegion(region).keySet();
++    
++    //Post authorization
++    if(AuthorizationProvider.isSecurityEnabled()){
++      try{
++        AuthorizationProvider.keySetAuthorizePP(region, keys);
++      }catch(NotAuthorizedException nae) {
++        return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
++      }
++    }
++    String listKeysAsJson =  JSONUtils.formulateJsonForListKeys(keys.toArray(), "keys");
+     return new ResponseEntity<String>(listKeysAsJson, headers, HttpStatus.OK);
+   }
+   
+   /**
+    * Delete data for single key or specific keys in region
+    * @param region gemfire region
+    * @param keys for which data is requested
+    * @return JSON document containing result
+    */
+   @RequestMapping(method = RequestMethod.DELETE, value = "/{region}/{keys}",
+                   produces = { MediaType.APPLICATION_JSON_VALUE } )
+   @ApiOperation(
+     value = "delete data for key(s)",
+     notes = "Delete data for single key or specific keys in region",
+     response  = void.class
+   )
+   @ApiResponses( {
+     @ApiResponse( code = 200, message = "OK" ),
+     @ApiResponse( code = 404, message = "Region or key(s) does not exist" ),
+     @ApiResponse( code = 500, message = "GemFire throws an error or exception" )      
+   } )
+   public ResponseEntity<?> delete(@PathVariable("region") String region,
+                                   @PathVariable("keys") final String[] keys){     
+     if(logger.isDebugEnabled()){
+       logger.debug("Delete data for key {} on region {}", ArrayUtils.toString((Object[])keys), region);
+     }
+     
+     region = decode(region);
++    final HttpHeaders headers = new HttpHeaders(); 
++    
++    //Do request(Pre) authorization if security is enabled.
++    if(AuthorizationProvider.isSecurityEnabled()){
++      setAuthTokenHeader(headers);
++      AuthorizationProvider.init();
++      try{
++        AuthorizationProvider.deleteAuthorize(region, keys, null);
++      }catch(NotAuthorizedException nae) {
++        return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
++      }
++    }
+     
+     deleteValues(region, (Object[])keys);
 -    return new ResponseEntity<Object>(HttpStatus.OK);
++    return new ResponseEntity<Object>(headers, HttpStatus.OK);
+   }
+ 
+   /**
+    * Delete all data in region
+    * @param region gemfire region
+    * @return JSON document containing result
+    */
+   @RequestMapping(method = RequestMethod.DELETE, value = "/{region}")
+   @ApiOperation(
+     value = "delete all data",
+     notes = "Delete all data in the region",
+     response  = void.class
+   )
+   @ApiResponses( {
+     @ApiResponse( code = 200, message = "OK" ),
+     @ApiResponse( code = 404, message = "Region does not exist" ),
+     @ApiResponse( code = 500, message = "if GemFire throws an error or exception" )   
+   } )
+   public ResponseEntity<?> delete(@PathVariable("region") String region) {
+     
+     if(logger.isDebugEnabled()){
+       logger.debug("Deleting all data in Region ({})...", region);
+     }
+     
+     region = decode(region);
++    final HttpHeaders headers = new HttpHeaders(); 
++    
++    //Do request(Pre) authorization if security is enabled.
++    if(AuthorizationProvider.isSecurityEnabled()){
++      setAuthTokenHeader(headers);
++      AuthorizationProvider.init();
++      try{
++        AuthorizationProvider.deleteAllAuthorize(region, null);
++      }catch(NotAuthorizedException nae) {
++        return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
++      }
++    }
+     
+     deleteValues(region);
 -    return new ResponseEntity<Object>(HttpStatus.OK);
++    return new ResponseEntity<Object>(headers, HttpStatus.OK);
+   }
+   
+   @RequestMapping(method = { RequestMethod.GET, RequestMethod.HEAD }, value = "/ping")
+   @ApiOperation(
+     value = "Check Rest service status ",
+     notes = "Check whether gemfire REST service is up and running!",
+     response  = void.class
+   )
+   @ApiResponses( {
+     @ApiResponse( code = 200, message = "OK" ),
+     @ApiResponse( code = 500, message = "if GemFire throws an error or exception" )   
+   } )
+   public ResponseEntity<?> ping() {
++    // Request Authorization not required.
+     return new ResponseEntity<Object>(HttpStatus.OK);
+   }
+   
+   @RequestMapping(method = { RequestMethod.GET }, value = "/servers")
+   @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 = 500, message = "if GemFire throws an error or exception" )   
+   } )
+   public ResponseEntity<?> servers() {
++    //Request Authorization not required.
+     Execution function = null;
+       
+     if(logger.isDebugEnabled()){
+       logger.debug("Executing function to get REST enabled gemfire nodes in the DS!");
+     }
 -      
++    
+     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(GemFireCacheImpl.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<String>(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);
+     }
+     
+   }
+   
+ }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/5c01d5f4/geode-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/FunctionAccessController.java
----------------------------------------------------------------------
diff --cc geode-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/FunctionAccessController.java
index 0000000,2c37c7f..11c5201
mode 000000,100644..100644
--- a/geode-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/FunctionAccessController.java
+++ b/geode-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/FunctionAccessController.java
@@@ -1,0 -1,246 +1,293 @@@
+ /*
+  * Licensed to the Apache Software Foundation (ASF) under one or more
+  * contributor license agreements.  See the NOTICE file distributed with
+  * this work for additional information regarding copyright ownership.
+  * The ASF licenses this file to You under the Apache License, Version 2.0
+  * (the "License"); you may not use this file except in compliance with
+  * the License.  You may obtain a copy of the License at
+  *
+  *      http://www.apache.org/licenses/LICENSE-2.0
+  *
+  * Unless required by applicable law or agreed to in writing, software
+  * distributed under the License is distributed on an "AS IS" BASIS,
+  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  * See the License for the specific language governing permissions and
+  * limitations under the License.
+  */
+ 
+ package com.gemstone.gemfire.rest.internal.web.controllers;
+ 
+ import java.util.ArrayList;
+ import java.util.List;
+ import java.util.Map;
+ 
+ import org.apache.logging.log4j.Logger;
+ import org.springframework.http.HttpHeaders;
+ import org.springframework.http.HttpStatus;
+ import org.springframework.http.MediaType;
+ import org.springframework.http.ResponseEntity;
+ import org.springframework.stereotype.Controller;
+ import org.springframework.util.StringUtils;
+ import org.springframework.web.bind.annotation.PathVariable;
+ import org.springframework.web.bind.annotation.RequestBody;
+ import org.springframework.web.bind.annotation.RequestMapping;
+ import org.springframework.web.bind.annotation.RequestMethod;
+ import org.springframework.web.bind.annotation.RequestParam;
+ import org.springframework.web.bind.annotation.ResponseBody;
+ import org.springframework.web.bind.annotation.ResponseStatus;
+ 
+ import com.gemstone.gemfire.cache.LowMemoryException;
+ import com.gemstone.gemfire.cache.execute.Execution;
+ import com.gemstone.gemfire.cache.execute.Function;
+ import com.gemstone.gemfire.cache.execute.FunctionException;
+ import com.gemstone.gemfire.cache.execute.FunctionService;
+ import com.gemstone.gemfire.cache.execute.ResultCollector;
++import com.gemstone.gemfire.cache.operations.ExecuteFunctionOperationContext;
++import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
+ import com.gemstone.gemfire.internal.logging.LogService;
++import com.gemstone.gemfire.management.internal.RestAgent;
+ import com.gemstone.gemfire.rest.internal.web.exception.GemfireRestException;
++import com.gemstone.gemfire.rest.internal.web.security.AuthorizationProvider;
++import com.gemstone.gemfire.rest.internal.web.security.FunctionExecutionPostAuthzRC;
+ import com.gemstone.gemfire.rest.internal.web.util.ArrayUtils;
+ import com.gemstone.gemfire.rest.internal.web.util.JSONUtils;
++import com.gemstone.gemfire.security.NotAuthorizedException;
+ import org.json.JSONException;
+ import com.wordnik.swagger.annotations.Api;
+ import com.wordnik.swagger.annotations.ApiOperation;
+ import com.wordnik.swagger.annotations.ApiResponse;
+ import com.wordnik.swagger.annotations.ApiResponses;
+ 
+ /**
+  * The FunctionsController class serving REST Requests related to the function execution
+  * <p/>
+  * @author Nilkanth Patel, john blum
+  * @see org.springframework.stereotype.Controller
+  * @since 8.0
+  */
+ 
+ @Controller("functionController")
+ @Api(value = "functions", description = "Rest api for gemfire function execution")
+ @RequestMapping(FunctionAccessController.REST_API_VERSION + "/functions")
+ @SuppressWarnings("unused")
+ public class FunctionAccessController extends AbstractBaseController {
+   private static final Logger logger = LogService.getLogger();
+ 
+   // Constant String value indicating the version of the REST API.
+   protected static final String REST_API_VERSION = "/v1";
+ 
+   /**
+    * Gets the version of the REST API implemented by this @Controller.
+    * <p/>
+    * @return a String indicating the REST API version.
+    */
+   @Override
+   protected String getRestApiVersion() {
+     return REST_API_VERSION;
+   }
+   
+   /**
+    * list all registered functions in Gemfire data node
+    * @return result as a JSON document.
+    */
+   @RequestMapping(method = RequestMethod.GET,  produces = { MediaType.APPLICATION_JSON_VALUE })
+   @ApiOperation(
+     value = "list all functions",
+     notes = "list all functions available in the GemFire cluster",
+     response  = void.class
+   )
+   @ApiResponses( {
+     @ApiResponse( code = 200, message = "OK." ),
+     @ApiResponse( code = 500, message = "GemFire throws an error or exception." )   
+   } )
+   @ResponseBody
+   @ResponseStatus(HttpStatus.OK)
+   public ResponseEntity<?> list() {
+     
+     if(logger.isDebugEnabled()){
+       logger.debug("Listing all registered Functions in GemFire...");
+     }
+     
 -    final Map<String, Function> registeredFunctions = FunctionService.getRegisteredFunctions();
 -    String listFunctionsAsJson =  JSONUtils.formulateJsonForListFunctionsCall(registeredFunctions.keySet());
+     final HttpHeaders headers = new HttpHeaders();  
+     headers.setLocation(toUri("functions"));
++    
++    //Do request(Pre) authorization if security is enabled.
++    if(AuthorizationProvider.isSecurityEnabled()){
++      setAuthTokenHeader(headers);  
++      AuthorizationProvider.init();
++      try{
++        AuthorizationProvider.listFunctionsAuthorize(OperationCode.LIST, true, "LIST_FUNCTIONS");
++      }catch(NotAuthorizedException nae) {
++        return new ResponseEntity<String>(HttpStatus.UNAUTHORIZED);
++      }
++    }
++    
++    final Map<String, Function> registeredFunctions = FunctionService.getRegisteredFunctions();
++    String listFunctionsAsJson =  JSONUtils.formulateJsonForListFunctionsCall(registeredFunctions.keySet());
+     return new ResponseEntity<String>(listFunctionsAsJson, headers, HttpStatus.OK);
+   } 
+   
+   /**
+    * 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 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 = 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)
+   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,
+                           @RequestBody(required = false) final String argsInBody
+                           )
+   {
+     Execution function = null;
+     functionId = decode(functionId);
+     
++    boolean isOptimizedForWrite = FunctionService.getFunction(functionId).optimizeForWrite();
++    Object[] args = null;
++    final HttpHeaders headers = new HttpHeaders();
++    
++    if(argsInBody != null) 
++    {
++      args = jsonToObjectArray(argsInBody);
++    }
++    
++    //Request(Pre) authorization if security is enabled.
++    ExecuteFunctionOperationContext fContext = null;
++    if(AuthorizationProvider.isSecurityEnabled()){
++      setAuthTokenHeader(headers);
++      AuthorizationProvider.init();
++      try{
++        fContext = AuthorizationProvider.executeFunctionAuthorize(functionId, region, null, args, isOptimizedForWrite);
++      }catch(NotAuthorizedException nae) {
++        return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
++      }
++    }
++    
+     if (StringUtils.hasText(region)) {
+       if(logger.isDebugEnabled()){
+         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)) {
+       if(logger.isDebugEnabled()){
+         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 disributed system!", fe);
+       }
+     }
+     else if (ArrayUtils.isNotEmpty(groups)) {
+       if(logger.isDebugEnabled()){
+         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.
+       if(logger.isDebugEnabled()){
+         logger.debug("Executing Function ({}) with arguments ({}) on all Members...", functionId,
+             ArrayUtils.toString(argsInBody));
+       }
+         
+       try {
+         function = FunctionService.onMembers(getAllMembersInDS());
+       } catch(FunctionException fe) {
+         throw new GemfireRestException("Disributed system does not contain any valid data node to run the specified  function!", fe);
+       }
+     }
 -
++    
+     final ResultCollector<?, ?> results;
+     
+     try {
 -      if(argsInBody != null) 
 -      {
 -        Object[] args = jsonToObjectArray(argsInBody);
 -        
 -        //execute function with specified arguments
 -        if(args.length == 1){
++      //Post Authorization if security is enabled.
++      if(AuthorizationProvider.isSecurityEnabled() && RestAgent.getAuthorizeRequestPP(getAuthToken()) != null) {
++        if (fContext == null){
++          fContext = new ExecuteFunctionOperationContext(functionId, region, null, args, isOptimizedForWrite, true);
++        }
++        if(args != null && args.length == 1){        
++          results = function.withArgs(args[0]).withCollector(new FunctionExecutionPostAuthzRC(fContext)).execute(functionId);
++        }else if (args != null && args.length > 1) {
++          results = function.withArgs(args).withCollector(new FunctionExecutionPostAuthzRC(fContext)).execute(functionId);
++        }else {
++          //execute function with no args
++          results = function.withCollector(new FunctionExecutionPostAuthzRC(fContext)).execute(functionId);
++        }
++      }else {
++        if(args != null && args.length == 1){        
+           results = function.withArgs(args[0]).execute(functionId);
 -        } else {
++        }else if (args != null && args.length > 1) {
+           results = function.withArgs(args).execute(functionId);
++        }else {
++          //execute function with no args
++          results = function.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 {
+       Object functionResult = results.getResult();
+     
+       if(functionResult instanceof List<?>) {
 -        final HttpHeaders headers = new HttpHeaders();
+         headers.setLocation(toUri("functions", functionId));
+       
+         try {
+           @SuppressWarnings("unchecked")
+           String functionResultAsJson = JSONUtils.convertCollectionToJson((ArrayList<Object>)functionResult);
+           return new ResponseEntity<String>(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);
+     }
+   }
+ }
+