You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by ji...@apache.org on 2016/07/08 15:51:23 UTC

[03/50] [abbrv] incubator-geode git commit: GEODE-1751: putting security checks in all applicable client-server commands.

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/536c13bd/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/GetAll651.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/GetAll651.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/GetAll651.java
index 9cea674..56100f2 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/GetAll651.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/GetAll651.java
@@ -52,8 +52,7 @@ public class GetAll651 extends BaseCommand {
   }
 
   @Override
-  public void cmdExecute(Message msg, ServerConnection servConn, long start)
-      throws IOException, InterruptedException {
+  public void cmdExecute(Message msg, ServerConnection servConn, long start) throws IOException, InterruptedException {
     Part regionNamePart = null, keysPart = null;
     String regionName = null;
     Object[] keys = null;
@@ -69,8 +68,7 @@ public class GetAll651 extends BaseCommand {
     keysPart = msg.getPart(1);
     try {
       keys = (Object[]) keysPart.getObject();
-    }
-    catch (Exception e) {
+    } catch (Exception e) {
       writeChunkedException(msg, e, false, servConn);
       servConn.setAsTrue(RESPONDED);
       return;
@@ -78,21 +76,19 @@ public class GetAll651 extends BaseCommand {
 
     if (logger.isDebugEnabled()) {
       StringBuffer buffer = new StringBuffer();
-      buffer
-        .append(servConn.getName())
-        .append(": Received getAll request (")
-        .append(msg.getPayloadLength())
-        .append(" bytes) from ")
-        .append(servConn.getSocketString())
-        .append(" for region ")
-        .append(regionName)
-        .append(" keys ");
+      buffer.append(servConn.getName())
+            .append(": Received getAll request (")
+            .append(msg.getPayloadLength())
+            .append(" bytes) from ")
+            .append(servConn.getSocketString())
+            .append(" for region ")
+            .append(regionName)
+            .append(" keys ");
       if (keys != null) {
-        for (int i=0; i<keys.length; i++) {
+        for (int i = 0; i < keys.length; i++) {
           buffer.append(keys[i]).append(" ");
         }
-      }
-      else {
+      } else {
         buffer.append("NULL");
       }
       logger.debug(buffer.toString());
@@ -101,50 +97,48 @@ public class GetAll651 extends BaseCommand {
     // Process the getAll request
     if (regionName == null) {
       String message = null;
-//      if (regionName == null) (can only be null) 
+      //      if (regionName == null) (can only be null)
       {
         message = LocalizedStrings.GetAll_THE_INPUT_REGION_NAME_FOR_THE_GETALL_REQUEST_IS_NULL.toLocalizedString();
       }
       logger.warn("{}: {}", servConn.getName(), message);
-      writeChunkedErrorResponse(msg, MessageType.GET_ALL_DATA_ERROR, message,
-          servConn);
+      writeChunkedErrorResponse(msg, MessageType.GET_ALL_DATA_ERROR, message, servConn);
       servConn.setAsTrue(RESPONDED);
+      return;
     }
-    else {
-      LocalRegion region = (LocalRegion)crHelper.getRegion(regionName);
-      if (region == null) {
-        String reason = " was not found during getAll request";
-        writeRegionDestroyedEx(msg, regionName, reason, servConn);
-        servConn.setAsTrue(RESPONDED);
-      }
-      else {
-        // Send header
-        ChunkedMessage chunkedResponseMsg = servConn.getChunkedResponseMessage();
-        chunkedResponseMsg.setMessageType(MessageType.RESPONSE);
-        chunkedResponseMsg.setTransactionId(msg.getTransactionId());
-        chunkedResponseMsg.sendHeader();
 
-        // Send chunk response
-        try {
-          fillAndSendGetAllResponseChunks(region, regionName, keys, servConn);
-          servConn.setAsTrue(RESPONDED);
-        }
-        catch (Exception e) {
-          // If an interrupted exception is thrown , rethrow it
-          checkForInterrupt(servConn, e);
+    LocalRegion region = (LocalRegion) crHelper.getRegion(regionName);
+    if (region == null) {
+      String reason = " was not found during getAll request";
+      writeRegionDestroyedEx(msg, regionName, reason, servConn);
+      servConn.setAsTrue(RESPONDED);
+      return;
+    }
+    // Send header
+    ChunkedMessage chunkedResponseMsg = servConn.getChunkedResponseMessage();
+    chunkedResponseMsg.setMessageType(MessageType.RESPONSE);
+    chunkedResponseMsg.setTransactionId(msg.getTransactionId());
+    chunkedResponseMsg.sendHeader();
 
-          // Otherwise, write an exception message and continue
-          writeChunkedException(msg, e, false, servConn);
-          servConn.setAsTrue(RESPONDED);
-          return;
-        }
-      }
+    // Send chunk response
+    try {
+      fillAndSendGetAllResponseChunks(region, regionName, keys, servConn);
+      servConn.setAsTrue(RESPONDED);
+    } catch (Exception e) {
+      // If an interrupted exception is thrown , rethrow it
+      checkForInterrupt(servConn, e);
+
+      // Otherwise, write an exception message and continue
+      writeChunkedException(msg, e, false, servConn);
+      servConn.setAsTrue(RESPONDED);
+      return;
     }
   }
 
   private void fillAndSendGetAllResponseChunks(Region region,
-      String regionName, Object[] keys, ServerConnection servConn)
-      throws IOException {
+                                               String regionName,
+                                               Object[] keys,
+                                               ServerConnection servConn) throws IOException {
 
     // Interpret null keys object as a request to get all key,value entry pairs
     // of the region; otherwise iterate each key and perform the get behavior.
@@ -153,8 +147,7 @@ public class GetAll651 extends BaseCommand {
     if (keys != null) {
       allKeysIter = null;
       numKeys = keys.length;
-    }
-    else {
+    } else {
       Set allKeys = region.keySet();
       allKeysIter = allKeys.iterator();
       numKeys = allKeys.size();
@@ -165,7 +158,7 @@ public class GetAll651 extends BaseCommand {
     Request request = (Request) Request.getCommand();
     Object[] valueAndIsObject = new Object[3];
     final boolean isDebugEnabled = logger.isDebugEnabled();
-    for (int i=0; i<numKeys; i++) {
+    for (int i = 0; i < numKeys; i++) {
       // Send the intermediate chunk if necessary
       if (values.size() == maximumChunkSize) {
         // Send the chunk and clear the list
@@ -177,8 +170,7 @@ public class GetAll651 extends BaseCommand {
       boolean keyNotPresent = false;
       if (keys != null) {
         key = keys[i];
-      }
-      else {
+      } else {
         key = allKeysIter.next();
       }
       if (isDebugEnabled) {
@@ -192,47 +184,58 @@ public class GetAll651 extends BaseCommand {
           if (isDebugEnabled) {
             logger.debug("{}: Passed GET pre-authorization for key={}", servConn.getName(), key);
           }
-        }
-        catch (NotAuthorizedException ex) {
-          logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[] {servConn.getName(), key}), ex);
+        } catch (NotAuthorizedException ex) {
+          logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[] {
+            servConn.getName(),
+            key
+          }), ex);
           values.addExceptionPart(key, ex);
           continue;
         }
       }
 
-      GeodeSecurityUtil.authorizeRegionRead(regionName, key.toString());
+      try {
+        GeodeSecurityUtil.authorizeRegionRead(regionName, key.toString());
+      } catch (NotAuthorizedException ex) {
+        logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[] {
+          servConn.getName(),
+          key
+        }), ex);
+        values.addExceptionPart(key, ex);
+        continue;
+      }
 
       // Get the value and update the statistics. Do not deserialize
       // the value if it is a byte[].
       // Getting a value in serialized form is pretty nasty. I split this out
       // so the logic can be re-used by the CacheClientProxy.
-      request.getValueAndIsObject(region, key,
-          null, servConn, valueAndIsObject);
+      request.getValueAndIsObject(region, key, null, servConn, valueAndIsObject);
       Object value = valueAndIsObject[0];
       boolean isObject = ((Boolean) valueAndIsObject[1]).booleanValue();
-      keyNotPresent = ((Boolean) valueAndIsObject[2]).booleanValue();;
+      keyNotPresent = ((Boolean) valueAndIsObject[2]).booleanValue();
+      ;
       if (isDebugEnabled) {
         logger.debug("{}: Retrieved value for key={}: {}", servConn.getName(), key, value);
       }
 
       if (postAuthzRequest != null) {
         try {
-          getContext = postAuthzRequest.getAuthorize(regionName, key, value,
-              isObject, getContext);
+          getContext = postAuthzRequest.getAuthorize(regionName, key, value, isObject, getContext);
           byte[] serializedValue = getContext.getSerializedValue();
           if (serializedValue == null) {
             value = getContext.getObject();
-          }
-          else {
+          } else {
             value = serializedValue;
           }
           isObject = getContext.isObject();
           if (isDebugEnabled) {
             logger.debug("{}: Passed GET post-authorization for key={}: {}", servConn.getName(), key, value);
           }
-        }
-        catch (NotAuthorizedException ex) {
-          logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[] {servConn.getName(), key}), ex);
+        } catch (NotAuthorizedException ex) {
+          logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[] {
+            servConn.getName(),
+            key
+          }), ex);
           values.addExceptionPart(key, ex);
           continue;
         }
@@ -245,23 +248,24 @@ public class GetAll651 extends BaseCommand {
       }
 
       // Add the value to the list of values
-      if(keyNotPresent) {
+      if (keyNotPresent) {
         if (logger.isDebugEnabled()) {
           logger.debug("{}: key={} is not present on server.", servConn.getName(), key);
-        } 
+        }
         values.addObjectPartForAbsentKey(key, value);
-      }else {
-        values.addObjectPart(key, value, isObject, null);  
+      } else {
+        values.addObjectPart(key, value, isObject, null);
       }
     }
 
-  // Send the last chunk even if the list is of zero size.
+    // Send the last chunk even if the list is of zero size.
     sendGetAllResponseChunk(region, values, true, servConn);
     servConn.setAsTrue(RESPONDED);
   }
 
   /**
    * This method is protected so it can be overriden in GetAllForRI.
+   *
    * @param includeKeys if the part list should include the keys
    */
   protected ObjectPartList651 getObjectPartsList(boolean includeKeys) {
@@ -269,15 +273,18 @@ public class GetAll651 extends BaseCommand {
     return values;
   }
 
-  private static void sendGetAllResponseChunk(Region region, ObjectPartList651 list,
-      boolean lastChunk, ServerConnection servConn) throws IOException {
+  private static void sendGetAllResponseChunk(Region region,
+                                              ObjectPartList651 list,
+                                              boolean lastChunk,
+                                              ServerConnection servConn) throws IOException {
     ChunkedMessage chunkedResponseMsg = servConn.getChunkedResponseMessage();
     chunkedResponseMsg.setNumberOfParts(1);
     chunkedResponseMsg.setLastChunk(lastChunk);
     chunkedResponseMsg.addObjPart(list, zipValues);
 
     if (logger.isDebugEnabled()) {
-      logger.debug("{}: Sending {} getAll response chunk for region={} values={} chunk=<{}>", servConn.getName(), (lastChunk ? " last " : " "), region.getFullPath(), list, chunkedResponseMsg);
+      logger.debug("{}: Sending {} getAll response chunk for region={} values={} chunk=<{}>", servConn.getName(), (lastChunk ? " last " : " "), region
+        .getFullPath(), list, chunkedResponseMsg);
     }
 
     chunkedResponseMsg.sendChunk(servConn);

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/536c13bd/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/GetAll70.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/GetAll70.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/GetAll70.java
index 007d583..d162b19 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/GetAll70.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/GetAll70.java
@@ -57,14 +57,12 @@ public class GetAll70 extends BaseCommand {
   /**
    * client wants values to be serialized as byte arrays, not objects
    */
- // private boolean requestSerializedValues;
-
+  // private boolean requestSerializedValues;
   protected GetAll70() {
   }
 
   @Override
-  public void cmdExecute(Message msg, ServerConnection servConn, long start)
-          throws IOException, InterruptedException {
+  public void cmdExecute(Message msg, ServerConnection servConn, long start) throws IOException, InterruptedException {
     Part regionNamePart = null, keysPart = null;
     String regionName = null;
     Object[] keys = null;
@@ -91,15 +89,14 @@ public class GetAll70 extends BaseCommand {
 
     if (logger.isDebugEnabled()) {
       StringBuffer buffer = new StringBuffer();
-      buffer
-              .append(servConn.getName())
-              .append(": Received getAll request (")
-              .append(msg.getPayloadLength())
-              .append(" bytes) from ")
-              .append(servConn.getSocketString())
-              .append(" for region ")
-              .append(regionName)
-              .append(" keys ");
+      buffer.append(servConn.getName())
+            .append(": Received getAll request (")
+            .append(msg.getPayloadLength())
+            .append(" bytes) from ")
+            .append(servConn.getSocketString())
+            .append(" for region ")
+            .append(regionName)
+            .append(" keys ");
       if (keys != null) {
         for (int i = 0; i < keys.length; i++) {
           buffer.append(keys[i]).append(" ");
@@ -118,42 +115,44 @@ public class GetAll70 extends BaseCommand {
         message = LocalizedStrings.GetAll_THE_INPUT_REGION_NAME_FOR_THE_GETALL_REQUEST_IS_NULL.toLocalizedString();
       }
       logger.warn("{}: {}", servConn.getName(), message);
-      writeChunkedErrorResponse(msg, MessageType.GET_ALL_DATA_ERROR, message,
-              servConn);
+      writeChunkedErrorResponse(msg, MessageType.GET_ALL_DATA_ERROR, message, servConn);
       servConn.setAsTrue(RESPONDED);
-    } else {
-      LocalRegion region = (LocalRegion) crHelper.getRegion(regionName);
-      if (region == null) {
-        String reason = " was not found during getAll request";
-        writeRegionDestroyedEx(msg, regionName, reason, servConn);
-        servConn.setAsTrue(RESPONDED);
-      } else {
-        // Send header
-        ChunkedMessage chunkedResponseMsg = servConn.getChunkedResponseMessage();
-        chunkedResponseMsg.setMessageType(MessageType.RESPONSE);
-        chunkedResponseMsg.setTransactionId(msg.getTransactionId());
-        chunkedResponseMsg.sendHeader();
+      return;
+    }
 
-        // Send chunk response
-        try {
-          fillAndSendGetAllResponseChunks(region, regionName, keys, servConn, requestSerializedValues);
-          servConn.setAsTrue(RESPONDED);
-        } catch (Exception e) {
-          // If an interrupted exception is thrown , rethrow it
-          checkForInterrupt(servConn, e);
+    LocalRegion region = (LocalRegion) crHelper.getRegion(regionName);
+    if (region == null) {
+      String reason = " was not found during getAll request";
+      writeRegionDestroyedEx(msg, regionName, reason, servConn);
+      servConn.setAsTrue(RESPONDED);
+      return;
+    }
+    // Send header
+    ChunkedMessage chunkedResponseMsg = servConn.getChunkedResponseMessage();
+    chunkedResponseMsg.setMessageType(MessageType.RESPONSE);
+    chunkedResponseMsg.setTransactionId(msg.getTransactionId());
+    chunkedResponseMsg.sendHeader();
 
-          // Otherwise, write an exception message and continue
-          writeChunkedException(msg, e, false, servConn);
-          servConn.setAsTrue(RESPONDED);
-          return;
-        }
-      }
+    // Send chunk response
+    try {
+      fillAndSendGetAllResponseChunks(region, regionName, keys, servConn, requestSerializedValues);
+      servConn.setAsTrue(RESPONDED);
+    } catch (Exception e) {
+      // If an interrupted exception is thrown , rethrow it
+      checkForInterrupt(servConn, e);
+
+      // Otherwise, write an exception message and continue
+      writeChunkedException(msg, e, false, servConn);
+      servConn.setAsTrue(RESPONDED);
+      return;
     }
   }
 
   private void fillAndSendGetAllResponseChunks(Region region,
-      String regionName, Object[] keys, ServerConnection servConn, boolean requestSerializedValues)
-      throws IOException {
+                                               String regionName,
+                                               Object[] keys,
+                                               ServerConnection servConn,
+                                               boolean requestSerializedValues) throws IOException {
 
     // Interpret null keys object as a request to get all key,value entry pairs
     // of the region; otherwise iterate each key and perform the get behavior.
@@ -176,133 +175,144 @@ public class GetAll70 extends BaseCommand {
     // So the only reason we would tell the VersionedObjectList that it needs to track keys is if we are running
     // in the old mode (which may be impossible since we only used that mode pre 7.0) in which the client told us
     // to get and return all the keys and values. I think this was used for register interest.
-    VersionedObjectList values = new VersionedObjectList(maximumChunkSize, keys == null, region.getAttributes().getConcurrencyChecksEnabled(), requestSerializedValues);
+    VersionedObjectList values = new VersionedObjectList(maximumChunkSize, keys == null, region.getAttributes()
+                                                                                               .getConcurrencyChecksEnabled(), requestSerializedValues);
     try {
-    AuthorizeRequest authzRequest = servConn.getAuthzRequest();
-    AuthorizeRequestPP postAuthzRequest = servConn.getPostAuthzRequest();
-    Get70 request = (Get70) Get70.getCommand();
-    final boolean isDebugEnabled = logger.isDebugEnabled();
-    for (int i = 0; i < numKeys; i++) {
-      // Send the intermediate chunk if necessary
-      if (values.size() == maximumChunkSize) {
-        // Send the chunk and clear the list
-        values.setKeys(null);
-        sendGetAllResponseChunk(region, values, false, servConn);
-        values.clear();
-      }
-
-      Object key;
-      boolean keyNotPresent = false;
-      if (keys != null) {
-        key = keys[i];
-      } else {
-        key = allKeysIter.next();
-      }
-      if (isDebugEnabled) {
-        logger.debug("{}: Getting value for key={}", servConn.getName(), key);
-      }
-      // Determine if the user authorized to get this key
-      GetOperationContext getContext = null;
-      if (authzRequest != null) {
-        try {
-          getContext = authzRequest.getAuthorize(regionName, key, null);
-          if (isDebugEnabled) {
-            logger.debug("{}: Passed GET pre-authorization for key={}", servConn.getName(), key);
-          }
-        } catch (NotAuthorizedException ex) {
-          logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[]{servConn.getName(), key}), ex);
-          values.addExceptionPart(key, ex);
-          continue;
+      AuthorizeRequest authzRequest = servConn.getAuthzRequest();
+      AuthorizeRequestPP postAuthzRequest = servConn.getPostAuthzRequest();
+      Get70 request = (Get70) Get70.getCommand();
+      final boolean isDebugEnabled = logger.isDebugEnabled();
+      for (int i = 0; i < numKeys; i++) {
+        // Send the intermediate chunk if necessary
+        if (values.size() == maximumChunkSize) {
+          // Send the chunk and clear the list
+          values.setKeys(null);
+          sendGetAllResponseChunk(region, values, false, servConn);
+          values.clear();
         }
-      }
-
-      try {
-        GeodeSecurityUtil.authorizeRegionRead(regionName, key.toString());
-      }
-      catch (NotAuthorizedException ex) {
-        logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[]{servConn.getName(), key}), ex);
-        values.addExceptionPart(key, ex);
-        continue;
-      }
-
-      // Get the value and update the statistics. Do not deserialize
-      // the value if it is a byte[].
-      // Getting a value in serialized form is pretty nasty. I split this out
-      // so the logic can be re-used by the CacheClientProxy.
-      Get70.Entry entry = request.getEntry(region, key, null, servConn);
-      @Retained final Object originalData = entry.value;
-      Object data = originalData;
-      if (logger.isDebugEnabled()) {
-        logger.debug("retrieved key={} {}", key, entry);
-      }
-      boolean addedToValues = false;
-      try {
-        boolean isObject = entry.isObject;
-        VersionTag versionTag = entry.versionTag;
-        keyNotPresent = entry.keyNotPresent;
 
-        if (postAuthzRequest != null) {
+        Object key;
+        boolean keyNotPresent = false;
+        if (keys != null) {
+          key = keys[i];
+        } else {
+          key = allKeysIter.next();
+        }
+        if (isDebugEnabled) {
+          logger.debug("{}: Getting value for key={}", servConn.getName(), key);
+        }
+        // Determine if the user authorized to get this key
+        GetOperationContext getContext = null;
+        if (authzRequest != null) {
           try {
-            getContext = postAuthzRequest.getAuthorize(regionName, key, data,
-                isObject, getContext);
-            GetOperationContextImpl gci = (GetOperationContextImpl) getContext;
-            Object newData = gci.getRawValue();
-            if (newData != data) {
-              // user changed the value
-              isObject = getContext.isObject();
-              data = newData;
+            getContext = authzRequest.getAuthorize(regionName, key, null);
+            if (isDebugEnabled) {
+              logger.debug("{}: Passed GET pre-authorization for key={}", servConn.getName(), key);
             }
           } catch (NotAuthorizedException ex) {
-            logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1,
-                new Object[]{servConn.getName(), key}), ex);
+            logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[] {
+              servConn.getName(),
+              key
+            }), ex);
             values.addExceptionPart(key, ex);
             continue;
-          } finally {
-            if (getContext != null) {
-              ((GetOperationContextImpl)getContext).release();
-            }
           }
         }
 
-        data = GeodeSecurityUtil.postProcess(regionName, key, data);
+        try {
+          GeodeSecurityUtil.authorizeRegionRead(regionName, key.toString());
+        } catch (NotAuthorizedException ex) {
+          logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[] {
+            servConn.getName(),
+            key
+          }), ex);
+          values.addExceptionPart(key, ex);
+          continue;
+        }
 
-        // Add the entry to the list that will be returned to the client
-        if (keyNotPresent) {
-          values.addObjectPartForAbsentKey(key, data, versionTag);
-          addedToValues = true;
-        } else {
-          values.addObjectPart(key, data, isObject, versionTag);
-          addedToValues = true;
+        // Get the value and update the statistics. Do not deserialize
+        // the value if it is a byte[].
+        // Getting a value in serialized form is pretty nasty. I split this out
+        // so the logic can be re-used by the CacheClientProxy.
+        Get70.Entry entry = request.getEntry(region, key, null, servConn);
+        @Retained
+        final Object originalData = entry.value;
+        Object data = originalData;
+        if (logger.isDebugEnabled()) {
+          logger.debug("retrieved key={} {}", key, entry);
         }
-      } finally {
-        if (!addedToValues || data != originalData) {
-          OffHeapHelper.release(originalData);
+        boolean addedToValues = false;
+        try {
+          boolean isObject = entry.isObject;
+          VersionTag versionTag = entry.versionTag;
+          keyNotPresent = entry.keyNotPresent;
+
+          if (postAuthzRequest != null) {
+            try {
+              getContext = postAuthzRequest.getAuthorize(regionName, key, data, isObject, getContext);
+              GetOperationContextImpl gci = (GetOperationContextImpl) getContext;
+              Object newData = gci.getRawValue();
+              if (newData != data) {
+                // user changed the value
+                isObject = getContext.isObject();
+                data = newData;
+              }
+            } catch (NotAuthorizedException ex) {
+              logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[] {
+                servConn.getName(),
+                key
+              }), ex);
+              values.addExceptionPart(key, ex);
+              continue;
+            } finally {
+              if (getContext != null) {
+                ((GetOperationContextImpl) getContext).release();
+              }
+            }
+          }
+
+          data = GeodeSecurityUtil.postProcess(regionName, key, data);
+
+          // Add the entry to the list that will be returned to the client
+          if (keyNotPresent) {
+            values.addObjectPartForAbsentKey(key, data, versionTag);
+            addedToValues = true;
+          } else {
+            values.addObjectPart(key, data, isObject, versionTag);
+            addedToValues = true;
+          }
+        } finally {
+          if (!addedToValues || data != originalData) {
+            OffHeapHelper.release(originalData);
+          }
         }
       }
-    }
 
-    // Send the last chunk even if the list is of zero size.
-    if (Version.GFE_701.compareTo(servConn.getClientVersion()) <= 0) {
-      // 7.0.1 and later clients do not expect the keys in the response
-      values.setKeys(null);
-    }
-    sendGetAllResponseChunk(region, values, true, servConn);
-    servConn.setAsTrue(RESPONDED);
+      // Send the last chunk even if the list is of zero size.
+      if (Version.GFE_701.compareTo(servConn.getClientVersion()) <= 0) {
+        // 7.0.1 and later clients do not expect the keys in the response
+        values.setKeys(null);
+      }
+      sendGetAllResponseChunk(region, values, true, servConn);
+      servConn.setAsTrue(RESPONDED);
     } finally {
       values.release();
     }
   }
 
 
-  private static void sendGetAllResponseChunk(Region region, ObjectPartList list,
-                                              boolean lastChunk, ServerConnection servConn) throws IOException {
+  private static void sendGetAllResponseChunk(Region region,
+                                              ObjectPartList list,
+                                              boolean lastChunk,
+                                              ServerConnection servConn) throws IOException {
     ChunkedMessage chunkedResponseMsg = servConn.getChunkedResponseMessage();
     chunkedResponseMsg.setNumberOfParts(1);
     chunkedResponseMsg.setLastChunk(lastChunk);
     chunkedResponseMsg.addObjPartNoCopying(list);
 
     if (logger.isDebugEnabled()) {
-      logger.debug("{}: Sending {} getAll response chunk for region={}{}", servConn.getName(), (lastChunk ? " last " : " "), region.getFullPath(), (logger.isTraceEnabled()? " values=" + list + " chunk=<" + chunkedResponseMsg + ">" : ""));
+      logger.debug("{}: Sending {} getAll response chunk for region={}{}", servConn.getName(), (lastChunk ? " last " : " "), region
+        .getFullPath(), (logger.isTraceEnabled() ? " values=" + list + " chunk=<" + chunkedResponseMsg + ">" : ""));
     }
 
     chunkedResponseMsg.sendChunk(servConn);

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/536c13bd/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/GetAllWithCallback.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/GetAllWithCallback.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/GetAllWithCallback.java
index 630163b..42a871a 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/GetAllWithCallback.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/GetAllWithCallback.java
@@ -24,10 +24,7 @@ import org.apache.logging.log4j.Logger;
 import com.gemstone.gemfire.cache.Region;
 import com.gemstone.gemfire.cache.operations.GetOperationContext;
 import com.gemstone.gemfire.cache.operations.internal.GetOperationContextImpl;
-import com.gemstone.gemfire.distributed.internal.DistributionStats;
-import com.gemstone.gemfire.i18n.LogWriterI18n;
 import com.gemstone.gemfire.internal.cache.LocalRegion;
-import com.gemstone.gemfire.internal.cache.PartitionedRegion;
 import com.gemstone.gemfire.internal.cache.tier.CachedRegionHelper;
 import com.gemstone.gemfire.internal.cache.tier.Command;
 import com.gemstone.gemfire.internal.cache.tier.MessageType;
@@ -38,7 +35,6 @@ import com.gemstone.gemfire.internal.cache.tier.sockets.ObjectPartList;
 import com.gemstone.gemfire.internal.cache.tier.sockets.Part;
 import com.gemstone.gemfire.internal.cache.tier.sockets.ServerConnection;
 import com.gemstone.gemfire.internal.cache.tier.sockets.VersionedObjectList;
-import com.gemstone.gemfire.internal.cache.tier.sockets.command.Get70.Entry;
 import com.gemstone.gemfire.internal.cache.versions.VersionTag;
 import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
 import com.gemstone.gemfire.internal.logging.LogService;
@@ -47,6 +43,7 @@ import com.gemstone.gemfire.internal.offheap.OffHeapHelper;
 import com.gemstone.gemfire.internal.offheap.annotations.Retained;
 import com.gemstone.gemfire.internal.security.AuthorizeRequest;
 import com.gemstone.gemfire.internal.security.AuthorizeRequestPP;
+import com.gemstone.gemfire.internal.security.GeodeSecurityUtil;
 import com.gemstone.gemfire.security.NotAuthorizedException;
 
 /**
@@ -134,34 +131,36 @@ public class GetAllWithCallback extends BaseCommand {
       writeChunkedErrorResponse(msg, MessageType.GET_ALL_DATA_ERROR, message,
               servConn);
       servConn.setAsTrue(RESPONDED);
-    } else {
-      LocalRegion region = (LocalRegion) crHelper.getRegion(regionName);
-      if (region == null) {
-        String reason = " was not found during getAll request";
-        writeRegionDestroyedEx(msg, regionName, reason, servConn);
-        servConn.setAsTrue(RESPONDED);
-      } else {
-        // Send header
-        ChunkedMessage chunkedResponseMsg = servConn.getChunkedResponseMessage();
-        chunkedResponseMsg.setMessageType(MessageType.RESPONSE);
-        chunkedResponseMsg.setTransactionId(msg.getTransactionId());
-        chunkedResponseMsg.sendHeader();
+      return;
+    }
+    LocalRegion region = (LocalRegion) crHelper.getRegion(regionName);
+    if (region == null) {
+      String reason = " was not found during getAll request";
+      writeRegionDestroyedEx(msg, regionName, reason, servConn);
+      servConn.setAsTrue(RESPONDED);
+      return;
+    }
+    // Send header
+    ChunkedMessage chunkedResponseMsg = servConn.getChunkedResponseMessage();
+    chunkedResponseMsg.setMessageType(MessageType.RESPONSE);
+    chunkedResponseMsg.setTransactionId(msg.getTransactionId());
+    chunkedResponseMsg.sendHeader();
 
-        // Send chunk response
-        try {
-          fillAndSendGetAllResponseChunks(region, regionName, keys, servConn, callback);
-          servConn.setAsTrue(RESPONDED);
-        } catch (Exception e) {
-          // If an interrupted exception is thrown , rethrow it
-          checkForInterrupt(servConn, e);
+    // Send chunk response
+    try {
+      fillAndSendGetAllResponseChunks(region, regionName, keys, servConn, callback);
+      servConn.setAsTrue(RESPONDED);
+    } catch (Exception e) {
+      // If an interrupted exception is thrown , rethrow it
+      checkForInterrupt(servConn, e);
 
-          // Otherwise, write an exception message and continue
-          writeChunkedException(msg, e, false, servConn);
-          servConn.setAsTrue(RESPONDED);
-          return;
-        }
-      }
+      // Otherwise, write an exception message and continue
+      writeChunkedException(msg, e, false, servConn);
+      servConn.setAsTrue(RESPONDED);
+      return;
     }
+
+
   }
 
   private void fillAndSendGetAllResponseChunks(Region region,
@@ -205,6 +204,17 @@ public class GetAllWithCallback extends BaseCommand {
         }
       }
 
+      try {
+        GeodeSecurityUtil.authorizeRegionRead(regionName, key.toString());
+      } catch (NotAuthorizedException ex) {
+        logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[] {
+          servConn.getName(),
+          key
+        }), ex);
+        values.addExceptionPart(key, ex);
+        continue;
+      }
+
       // Get the value and update the statistics. Do not deserialize
       // the value if it is a byte[].
       // Getting a value in serialized form is pretty nasty. I split this out

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/536c13bd/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/GetFunctionAttribute.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/GetFunctionAttribute.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/GetFunctionAttribute.java
index 1ea5919..871a80b 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/GetFunctionAttribute.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/GetFunctionAttribute.java
@@ -26,6 +26,7 @@ import com.gemstone.gemfire.internal.cache.tier.sockets.BaseCommand;
 import com.gemstone.gemfire.internal.cache.tier.sockets.Message;
 import com.gemstone.gemfire.internal.cache.tier.sockets.ServerConnection;
 import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+import com.gemstone.gemfire.internal.security.GeodeSecurityUtil;
 
 public class GetFunctionAttribute extends BaseCommand {
 
@@ -50,24 +51,26 @@ public class GetFunctionAttribute extends BaseCommand {
       sendError(msg, message, servConn);
       return;
     }
-    else {
-      Function function = FunctionService.getFunction(functionId);
-      if (function == null) {
-        String message = null;
-        message = LocalizedStrings.GetFunctionAttribute_THE_FUNCTION_IS_NOT_REGISTERED_FOR_FUNCTION_ID_0
-            .toLocalizedString(functionId);
-        logger.warn("{}: {}", servConn.getName(), message);
-        sendError(msg, message, servConn);
-        return;
-      }
-      else {
-        byte[] functionAttributes = new byte[3];
-        functionAttributes[0] = (byte)(function.hasResult() ? 1 : 0);
-        functionAttributes[1] = (byte)(function.isHA() ? 1 : 0);
-        functionAttributes[2] = (byte)(function.optimizeForWrite() ? 1 : 0);
-        writeResponseWithFunctionAttribute(functionAttributes, msg, servConn);
-      }
+
+    Function function = FunctionService.getFunction(functionId);
+    if (function == null) {
+      String message = null;
+      message = LocalizedStrings.GetFunctionAttribute_THE_FUNCTION_IS_NOT_REGISTERED_FOR_FUNCTION_ID_0
+          .toLocalizedString(functionId);
+      logger.warn("{}: {}", servConn.getName(), message);
+      sendError(msg, message, servConn);
+      return;
     }
+
+    GeodeSecurityUtil.authorizeFunctionRead(functionId);
+
+    byte[] functionAttributes = new byte[3];
+    functionAttributes[0] = (byte)(function.hasResult() ? 1 : 0);
+    functionAttributes[1] = (byte)(function.isHA() ? 1 : 0);
+    functionAttributes[2] = (byte)(function.optimizeForWrite() ? 1 : 0);
+    writeResponseWithFunctionAttribute(functionAttributes, msg, servConn);
+
+
   }
 
   private void sendError(Message msg, String message, ServerConnection servConn)

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/536c13bd/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/Invalidate.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/Invalidate.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/Invalidate.java
index ee64872..44a6f7e 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/Invalidate.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/Invalidate.java
@@ -114,112 +114,106 @@ public class Invalidate extends BaseCommand {
       }
       writeErrorResponse(msg, MessageType.DESTROY_DATA_ERROR, errMessage.toString(), servConn);
       servConn.setAsTrue(RESPONDED);
-    } else {
-      LocalRegion region = (LocalRegion) crHelper.getRegion(regionName);
-      if (region == null) {
-        String reason = LocalizedStrings.BaseCommand__0_WAS_NOT_FOUND_DURING_1_REQUEST.toLocalizedString(regionName, "invalidate");
-        writeRegionDestroyedEx(msg, regionName, reason, servConn);
-        servConn.setAsTrue(RESPONDED);
-      } else {
-        // Invalidate the entry
-        ByteBuffer eventIdPartsBuffer = ByteBuffer.wrap(eventPart.getSerializedForm());
-        long threadId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
-        long sequenceId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
-        EventID eventId = new EventID(servConn.getEventMemberIDByteArray(), threadId, sequenceId);
-
-        Breadcrumbs.setEventId(eventId);
-
-        VersionTag tag = null;
-
-        // for integrated security
-        GeodeSecurityUtil.authorizeRegionWrite(regionName, key.toString());
-
-        try {
-          /*
-           * 
-           * txtodo: doesn't seem like there is any notion of authzInvalidate
-           */
-          AuthorizeRequest authzRequest = servConn.getAuthzRequest();
-          if (authzRequest != null) {
-            InvalidateOperationContext invalidateContext = authzRequest.invalidateAuthorize(regionName, key, callbackArg);
-            callbackArg = invalidateContext.getCallbackArg();
-          }
-          EventIDHolder clientEvent = new EventIDHolder(eventId);
-
-          // msg.isRetry might be set by v7.0 and later clients
-          if (msg.isRetry()) {
-            //            if (logger.isDebugEnabled()) {
-            //              logger.debug("DEBUG: encountered isRetry in Invalidate");
-            //            }
-            clientEvent.setPossibleDuplicate(true);
-            if (region.getAttributes().getConcurrencyChecksEnabled()) {
-              // recover the version tag from other servers
-              clientEvent.setRegion(region);
-              if (!recoverVersionTagForRetriedOperation(clientEvent)) {
-                clientEvent.setPossibleDuplicate(false); // no-one has seen this event
-              }
-            }
-          }
+      return;
+    }
+    LocalRegion region = (LocalRegion) crHelper.getRegion(regionName);
+    if (region == null) {
+      String reason = LocalizedStrings.BaseCommand__0_WAS_NOT_FOUND_DURING_1_REQUEST.toLocalizedString(regionName, "invalidate");
+      writeRegionDestroyedEx(msg, regionName, reason, servConn);
+      servConn.setAsTrue(RESPONDED);
+      return;
+    }
+    // Invalidate the entry
+    ByteBuffer eventIdPartsBuffer = ByteBuffer.wrap(eventPart.getSerializedForm());
+    long threadId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
+    long sequenceId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
+    EventID eventId = new EventID(servConn.getEventMemberIDByteArray(), threadId, sequenceId);
 
-          region.basicBridgeInvalidate(key, callbackArg, servConn.getProxyID(), true, clientEvent);
-          tag = clientEvent.getVersionTag();
-          servConn.setModificationInfo(true, regionName, key);
-        } catch (EntryNotFoundException e) {
-          // Don't send an exception back to the client if this
-          // exception happens. Just log it and continue.
-          logger.info(LocalizedMessage.create(LocalizedStrings.BaseCommand_DURING_0_NO_ENTRY_WAS_FOUND_FOR_KEY_1, new Object[] {
-            "invalidate",
-            key
-          }));
-        } catch (RegionDestroyedException rde) {
-          writeException(msg, rde, false, servConn);
-          servConn.setAsTrue(RESPONDED);
-          return;
-        } catch (Exception e) {
-          // If an interrupted exception is thrown , rethrow it
-          checkForInterrupt(servConn, e);
-
-          // If an exception occurs during the destroy, preserve the connection
-          writeException(msg, e, false, servConn);
-          servConn.setAsTrue(RESPONDED);
-          if (e instanceof GemFireSecurityException) {
-            // Fine logging for security exceptions since these are already
-            // logged by the security logger
-            if (logger.isDebugEnabled()) {
-              logger.debug("{}: Unexpected Security exception", servConn.getName(), e);
-            }
-          } else {
-            logger.warn(LocalizedMessage.create(LocalizedStrings.BaseCommand_0_UNEXPECTED_EXCEPTION, servConn.getName()), e);
-          }
-          return;
-        }
+    Breadcrumbs.setEventId(eventId);
 
-        // Update the statistics and write the reply
-        {
-          long oldStart = start;
-          start = DistributionStats.getStatTime();
-          stats.incProcessInvalidateTime(start - oldStart);
-        }
-        if (region instanceof PartitionedRegion) {
-          PartitionedRegion pr = (PartitionedRegion) region;
-          if (pr.isNetworkHop() != (byte) 0) {
-            writeReplyWithRefreshMetadata(msg, servConn, pr, pr.isNetworkHop(), tag);
-            pr.setIsNetworkHop((byte) 0);
-            pr.setMetadataVersion(Byte.valueOf((byte) 0));
-          } else {
-            writeReply(msg, servConn, tag);
+    VersionTag tag = null;
+
+    // for integrated security
+    GeodeSecurityUtil.authorizeRegionWrite(regionName, key.toString());
+
+    try {
+      AuthorizeRequest authzRequest = servConn.getAuthzRequest();
+      if (authzRequest != null) {
+        InvalidateOperationContext invalidateContext = authzRequest.invalidateAuthorize(regionName, key, callbackArg);
+        callbackArg = invalidateContext.getCallbackArg();
+      }
+      EventIDHolder clientEvent = new EventIDHolder(eventId);
+
+      // msg.isRetry might be set by v7.0 and later clients
+      if (msg.isRetry()) {
+        //            if (logger.isDebugEnabled()) {
+        //              logger.debug("DEBUG: encountered isRetry in Invalidate");
+        //            }
+        clientEvent.setPossibleDuplicate(true);
+        if (region.getAttributes().getConcurrencyChecksEnabled()) {
+          // recover the version tag from other servers
+          clientEvent.setRegion(region);
+          if (!recoverVersionTagForRetriedOperation(clientEvent)) {
+            clientEvent.setPossibleDuplicate(false); // no-one has seen this event
           }
-        } else {
-          writeReply(msg, servConn, tag);
         }
-        servConn.setAsTrue(RESPONDED);
+      }
+
+      region.basicBridgeInvalidate(key, callbackArg, servConn.getProxyID(), true, clientEvent);
+      tag = clientEvent.getVersionTag();
+      servConn.setModificationInfo(true, regionName, key);
+    } catch (EntryNotFoundException e) {
+      // Don't send an exception back to the client if this
+      // exception happens. Just log it and continue.
+      logger.info(LocalizedMessage.create(LocalizedStrings.BaseCommand_DURING_0_NO_ENTRY_WAS_FOUND_FOR_KEY_1, new Object[] {
+        "invalidate", key
+      }));
+    } catch (RegionDestroyedException rde) {
+      writeException(msg, rde, false, servConn);
+      servConn.setAsTrue(RESPONDED);
+      return;
+    } catch (Exception e) {
+      // If an interrupted exception is thrown , rethrow it
+      checkForInterrupt(servConn, e);
+
+      // If an exception occurs during the destroy, preserve the connection
+      writeException(msg, e, false, servConn);
+      servConn.setAsTrue(RESPONDED);
+      if (e instanceof GemFireSecurityException) {
+        // Fine logging for security exceptions since these are already
+        // logged by the security logger
         if (logger.isDebugEnabled()) {
-          logger.debug("{}: Sent invalidate response for region {} key {}", servConn.getName(), regionName, key);
+          logger.debug("{}: Unexpected Security exception", servConn.getName(), e);
         }
-        stats.incWriteInvalidateResponseTime(DistributionStats.getStatTime() - start);
+      } else {
+        logger.warn(LocalizedMessage.create(LocalizedStrings.BaseCommand_0_UNEXPECTED_EXCEPTION, servConn.getName()), e);
       }
+      return;
     }
 
+    // Update the statistics and write the reply
+    {
+      long oldStart = start;
+      start = DistributionStats.getStatTime();
+      stats.incProcessInvalidateTime(start - oldStart);
+    }
+    if (region instanceof PartitionedRegion) {
+      PartitionedRegion pr = (PartitionedRegion) region;
+      if (pr.isNetworkHop() != (byte) 0) {
+        writeReplyWithRefreshMetadata(msg, servConn, pr, pr.isNetworkHop(), tag);
+        pr.setIsNetworkHop((byte) 0);
+        pr.setMetadataVersion(Byte.valueOf((byte) 0));
+      } else {
+        writeReply(msg, servConn, tag);
+      }
+    } else {
+      writeReply(msg, servConn, tag);
+    }
+    servConn.setAsTrue(RESPONDED);
+    if (logger.isDebugEnabled()) {
+      logger.debug("{}: Sent invalidate response for region {} key {}", servConn.getName(), regionName, key);
+    }
+    stats.incWriteInvalidateResponseTime(DistributionStats.getStatTime() - start);
   }
 
   protected void writeReply(Message origMsg, ServerConnection servConn, VersionTag tag) throws IOException {

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/536c13bd/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/KeySet.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/KeySet.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/KeySet.java
index 8da7af9..0163be7 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/KeySet.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/KeySet.java
@@ -15,7 +15,7 @@
  * limitations under the License.
  */
 /**
- * 
+ *
  */
 package com.gemstone.gemfire.internal.cache.tier.sockets.command;
 
@@ -56,8 +56,7 @@ public class KeySet extends BaseCommand {
   }
 
   @Override
-  public void cmdExecute(Message msg, ServerConnection servConn, long start)
-      throws IOException, InterruptedException {
+  public void cmdExecute(Message msg, ServerConnection servConn, long start) throws IOException, InterruptedException {
     Part regionNamePart = null;
     String regionName = null;
     CachedRegionHelper crHelper = servConn.getCachedRegionHelper();
@@ -70,84 +69,86 @@ public class KeySet extends BaseCommand {
     ChunkedMessage chunkedResponseMsg = servConn.getChunkedResponseMessage();
     final boolean isDebugEnabled = logger.isDebugEnabled();
     if (isDebugEnabled) {
-      logger.debug("{}: Received key set request ({} bytes) from {} for region {}", servConn.getName(), msg.getPayloadLength(), servConn.getSocketString(), regionName);
+      logger.debug("{}: Received key set request ({} bytes) from {} for region {}", servConn.getName(), msg.getPayloadLength(), servConn
+        .getSocketString(), regionName);
     }
 
     // Process the key set request
     if (regionName == null) {
       String message = null;
-//      if (regionName == null) (can only be null) 
+      //      if (regionName == null) (can only be null)
       {
-        message = LocalizedStrings.KeySet_0_THE_INPUT_REGION_NAME_FOR_THE_KEY_SET_REQUEST_IS_NULL.toLocalizedString(servConn.getName());
-        logger.warn(LocalizedMessage.create(LocalizedStrings.KeySet_0_THE_INPUT_REGION_NAME_FOR_THE_KEY_SET_REQUEST_IS_NULL, servConn.getName()));
+        message = LocalizedStrings.KeySet_0_THE_INPUT_REGION_NAME_FOR_THE_KEY_SET_REQUEST_IS_NULL.toLocalizedString(servConn
+          .getName());
+        logger.warn(LocalizedMessage.create(LocalizedStrings.KeySet_0_THE_INPUT_REGION_NAME_FOR_THE_KEY_SET_REQUEST_IS_NULL, servConn
+          .getName()));
       }
-      writeKeySetErrorResponse(msg, MessageType.KEY_SET_DATA_ERROR, message,
-          servConn);
+      writeKeySetErrorResponse(msg, MessageType.KEY_SET_DATA_ERROR, message, servConn);
+      servConn.setAsTrue(RESPONDED);
+      return;
+    }
+
+    LocalRegion region = (LocalRegion) crHelper.getRegion(regionName);
+    if (region == null) {
+      String reason = LocalizedStrings.KeySet__0_WAS_NOT_FOUND_DURING_KEY_SET_REQUEST.toLocalizedString(regionName);
+      writeRegionDestroyedEx(msg, regionName, reason, servConn);
       servConn.setAsTrue(RESPONDED);
+      return;
     }
-    else {
-      LocalRegion region = (LocalRegion)crHelper.getRegion(regionName);
-      if (region == null) {
-        String reason = LocalizedStrings.KeySet__0_WAS_NOT_FOUND_DURING_KEY_SET_REQUEST.toLocalizedString(regionName);
-        writeRegionDestroyedEx(msg, regionName, reason, servConn);
+
+    GeodeSecurityUtil.authorizeRegionRead(regionName);
+
+    KeySetOperationContext keySetContext = null;
+    AuthorizeRequest authzRequest = servConn.getAuthzRequest();
+    if (authzRequest != null) {
+      try {
+        keySetContext = authzRequest.keySetAuthorize(regionName);
+      } catch (NotAuthorizedException ex) {
+        writeChunkedException(msg, ex, false, servConn);
         servConn.setAsTrue(RESPONDED);
-      }
-      else {
-        KeySetOperationContext keySetContext = null;
-        AuthorizeRequest authzRequest = servConn.getAuthzRequest();
-        if (authzRequest != null) {
-          try {
-            keySetContext = authzRequest.keySetAuthorize(regionName);
-          }
-          catch (NotAuthorizedException ex) {
-            writeChunkedException(msg, ex, false, servConn);
-            servConn.setAsTrue(RESPONDED);
-            return;
-          }
-        }
-        // Update the statistics and write the reply
-        // bserverStats.incLong(processDestroyTimeId,
-        // DistributionStats.getStatTime() - start);
-        // start = DistributionStats.getStatTime();
-
-        // Send header
-        chunkedResponseMsg.setMessageType(MessageType.RESPONSE);
-        chunkedResponseMsg.setTransactionId(msg.getTransactionId());
-        chunkedResponseMsg.sendHeader();
-
-        // Send chunk response
-        try {
-          fillAndSendKeySetResponseChunks(region, regionName, keySetContext,
-              servConn);
-          servConn.setAsTrue(RESPONDED);
-        }
-        catch (Exception e) {
-          // If an interrupted exception is thrown , rethrow it
-          checkForInterrupt(servConn, e);
-
-          // Otherwise, write an exception message and continue
-          writeChunkedException(msg, e, false, servConn, servConn
-              .getChunkedResponseMessage());
-          servConn.setAsTrue(RESPONDED);
-          return;
-        }
-
-        if (isDebugEnabled) {
-          // logger.fine(getName() + ": Sent chunk (1 of 1) of register interest
-          // response (" + chunkedResponseMsg.getBufferLength() + " bytes) for
-          // region " + regionName + " key " + key);
-          logger.debug("{}: Sent key set response for the region {}", servConn.getName(), regionName);
-        }
-        // bserverStats.incLong(writeDestroyResponseTimeId,
-        // DistributionStats.getStatTime() - start);
-        // bserverStats.incInt(destroyResponsesId, 1);
+        return;
       }
     }
+    // Update the statistics and write the reply
+    // bserverStats.incLong(processDestroyTimeId,
+    // DistributionStats.getStatTime() - start);
+    // start = DistributionStats.getStatTime();
+
+    // Send header
+    chunkedResponseMsg.setMessageType(MessageType.RESPONSE);
+    chunkedResponseMsg.setTransactionId(msg.getTransactionId());
+    chunkedResponseMsg.sendHeader();
+
+    // Send chunk response
+    try {
+      fillAndSendKeySetResponseChunks(region, regionName, keySetContext, servConn);
+      servConn.setAsTrue(RESPONDED);
+    } catch (Exception e) {
+      // If an interrupted exception is thrown , rethrow it
+      checkForInterrupt(servConn, e);
+
+      // Otherwise, write an exception message and continue
+      writeChunkedException(msg, e, false, servConn, servConn.getChunkedResponseMessage());
+      servConn.setAsTrue(RESPONDED);
+      return;
+    }
+
+    if (isDebugEnabled) {
+      // logger.fine(getName() + ": Sent chunk (1 of 1) of register interest
+      // response (" + chunkedResponseMsg.getBufferLength() + " bytes) for
+      // region " + regionName + " key " + key);
+      logger.debug("{}: Sent key set response for the region {}", servConn.getName(), regionName);
+    }
+    // bserverStats.incLong(writeDestroyResponseTimeId,
+    // DistributionStats.getStatTime() - start);
+    // bserverStats.incInt(destroyResponsesId, 1);
+
   }
 
   private void fillAndSendKeySetResponseChunks(LocalRegion region,
-      String regionName, KeySetOperationContext context,
-      ServerConnection servConn) throws IOException {
+                                               String regionName,
+                                               KeySetOperationContext context,
+                                               ServerConnection servConn) throws IOException {
 
     // Get the key set
     Set keySet = region.keys();
@@ -156,19 +157,18 @@ public class KeySet extends BaseCommand {
     // Post-operation filtering
     AuthorizeRequestPP postAuthzRequest = servConn.getPostAuthzRequest();
     if (postAuthzRequest != null) {
-      keySetContext = postAuthzRequest.keySetAuthorize(regionName, keySet,
-          keySetContext);
+      keySetContext = postAuthzRequest.keySetAuthorize(regionName, keySet, keySetContext);
       keySet = keySetContext.getKeySet();
     }
 
     List keyList = new ArrayList(maximumChunkSize);
     final boolean isTraceEnabled = logger.isTraceEnabled();
-    for (Iterator it = keySet.iterator(); it.hasNext();) {
+    for (Iterator it = keySet.iterator(); it.hasNext(); ) {
       Object entryKey = it.next();
-      GeodeSecurityUtil.authorizeRegionRead(regionName, entryKey.toString());
       keyList.add(entryKey);
       if (isTraceEnabled) {
-        logger.trace("{}: fillAndSendKeySetResponseKey <{}>; list size was {}; region: {}", servConn.getName(), entryKey, keyList.size(), region.getFullPath());
+        logger.trace("{}: fillAndSendKeySetResponseKey <{}>; list size was {}; region: {}", servConn.getName(), entryKey, keyList
+          .size(), region.getFullPath());
       }
       if (keyList.size() == maximumChunkSize) {
         // Send the chunk and clear the list
@@ -180,8 +180,8 @@ public class KeySet extends BaseCommand {
     sendKeySetResponseChunk(region, keyList, true, servConn);
   }
 
-  private static void sendKeySetResponseChunk(Region region, List list,
-      boolean lastChunk, ServerConnection servConn) throws IOException {
+  private static void sendKeySetResponseChunk(Region region, List list, boolean lastChunk, ServerConnection servConn)
+    throws IOException {
     ChunkedMessage chunkedResponseMsg = servConn.getChunkedResponseMessage();
 
     chunkedResponseMsg.setNumberOfParts(1);
@@ -189,7 +189,8 @@ public class KeySet extends BaseCommand {
     chunkedResponseMsg.addObjPart(list, zipValues);
 
     if (logger.isDebugEnabled()) {
-      logger.debug("{}: Sending {} key set response chunk for region={}{}", servConn.getName(), (lastChunk ? " last " : " "), region.getFullPath(), (logger.isTraceEnabled() ? " keys=" + list + " chunk=<" + chunkedResponseMsg + ">" : ""));
+      logger.debug("{}: Sending {} key set response chunk for region={}{}", servConn.getName(), (lastChunk ? " last " : " "), region
+        .getFullPath(), (logger.isTraceEnabled() ? " keys=" + list + " chunk=<" + chunkedResponseMsg + ">" : ""));
     }
 
     chunkedResponseMsg.sendChunk(servConn);

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/536c13bd/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/Put61.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/Put61.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/Put61.java
index 4cadd20..48e2a01 100755
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/Put61.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/Put61.java
@@ -15,7 +15,7 @@
  * limitations under the License.
  */
 /**
- * 
+ *
  */
 package com.gemstone.gemfire.internal.cache.tier.sockets.command;
 
@@ -28,7 +28,6 @@ import com.gemstone.gemfire.cache.RegionDestroyedException;
 import com.gemstone.gemfire.cache.ResourceException;
 import com.gemstone.gemfire.cache.operations.PutOperationContext;
 import com.gemstone.gemfire.distributed.internal.DistributionStats;
-import com.gemstone.gemfire.internal.cache.EntryEventImpl;
 import com.gemstone.gemfire.internal.cache.EventID;
 import com.gemstone.gemfire.internal.cache.EventIDHolder;
 import com.gemstone.gemfire.internal.cache.LocalRegion;
@@ -44,6 +43,7 @@ import com.gemstone.gemfire.internal.cache.tier.sockets.ServerConnection;
 import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
 import com.gemstone.gemfire.internal.logging.log4j.LocalizedMessage;
 import com.gemstone.gemfire.internal.security.AuthorizeRequest;
+import com.gemstone.gemfire.internal.security.GeodeSecurityUtil;
 import com.gemstone.gemfire.security.GemFireSecurityException;
 
 /**
@@ -62,7 +62,7 @@ public class Put61 extends BaseCommand {
 
   @Override
   public void cmdExecute(Message msg, ServerConnection servConn, long p_start)
-      throws IOException, InterruptedException {
+    throws IOException, InterruptedException {
     long start = p_start;
     Part regionNamePart = null, keyPart = null, valuePart = null, callbackArgPart = null;
     String regionName = null;
@@ -76,11 +76,9 @@ public class Put61 extends BaseCommand {
       boolean interrupted = Thread.interrupted();
       try {
         Thread.sleep(crHelper.emulateSlowServer());
-      }
-      catch (InterruptedException ugh) {
+      } catch (InterruptedException ugh) {
         interrupted = true;
-      }
-      finally {
+      } finally {
         if (interrupted) {
           Thread.currentThread().interrupt();
         }
@@ -98,9 +96,8 @@ public class Put61 extends BaseCommand {
     regionNamePart = msg.getPart(0);
     keyPart = msg.getPart(1);
     try {
-      isDelta = (Boolean)msg.getPart(2).getObject();
-    }
-    catch (Exception e) {
+      isDelta = (Boolean) msg.getPart(2).getObject();
+    } catch (Exception e) {
       writeException(msg, MessageType.PUT_DELTA_ERROR, e, false, servConn);
       servConn.setAsTrue(RESPONDED);
       // CachePerfStats not available here.
@@ -112,8 +109,7 @@ public class Put61 extends BaseCommand {
       callbackArgPart = msg.getPart(5);
       try {
         callbackArg = callbackArgPart.getObject();
-      }
-      catch (Exception e) {
+      } catch (Exception e) {
         writeException(msg, e, false, servConn);
         servConn.setAsTrue(RESPONDED);
         return;
@@ -123,8 +119,7 @@ public class Put61 extends BaseCommand {
 
     try {
       key = keyPart.getStringOrObject();
-    }
-    catch (Exception e) {
+    } catch (Exception e) {
       writeException(msg, e, false, servConn);
       servConn.setAsTrue(RESPONDED);
       return;
@@ -132,7 +127,8 @@ public class Put61 extends BaseCommand {
 
     final boolean isDebugEnabled = logger.isDebugEnabled();
     if (isDebugEnabled) {
-      logger.debug("{}: Received 6.1{}put request ({} bytes) from {} for region {} key {}", servConn.getName(), (isDelta ? " delta " : " "), msg.getPayloadLength(), servConn.getSocketString(), regionName, key);
+      logger.debug("{}: Received 6.1{}put request ({} bytes) from {} for region {} key {}", servConn.getName(), (isDelta ? " delta " : " "), msg
+        .getPayloadLength(), servConn.getSocketString(), regionName, key);
     }
 
     // Process the put request
@@ -151,169 +147,153 @@ public class Put61 extends BaseCommand {
         }
         errMessage.append(putMsg);
       }
-      writeErrorResponse(msg, MessageType.PUT_DATA_ERROR,
-          errMessage.toString(), servConn);
+      writeErrorResponse(msg, MessageType.PUT_DATA_ERROR, errMessage.toString(), servConn);
       servConn.setAsTrue(RESPONDED);
+      return;
     }
-    else {
-      LocalRegion region = (LocalRegion)crHelper.getRegion(regionName);
-      if (region == null) {
-        String reason = " was not found during 6.1 put request";
-        writeRegionDestroyedEx(msg, regionName, reason, servConn);
-        servConn.setAsTrue(RESPONDED);
-      }
-      else if (valuePart.isNull() && region.containsKey(key)) {
-        // Invalid to 'put' a null value in an existing key
-        String putMsg = " Attempted to 6.1 put a null value for existing key "
-            + key;
-        if (isDebugEnabled) {
-          logger.debug("{}:{}", servConn.getName(), putMsg);
-        }
-        errMessage.append(putMsg);
-        writeErrorResponse(msg, MessageType.PUT_DATA_ERROR, errMessage
-            .toString(), servConn);
-        servConn.setAsTrue(RESPONDED);
+
+    LocalRegion region = (LocalRegion) crHelper.getRegion(regionName);
+    if (region == null) {
+      String reason = " was not found during 6.1 put request";
+      writeRegionDestroyedEx(msg, regionName, reason, servConn);
+      servConn.setAsTrue(RESPONDED);
+      return;
+    }
+
+    if (valuePart.isNull() && region.containsKey(key)) {
+      // Invalid to 'put' a null value in an existing key
+      String putMsg = " Attempted to 6.1 put a null value for existing key " + key;
+      if (isDebugEnabled) {
+        logger.debug("{}:{}", servConn.getName(), putMsg);
       }
-      else {
-        // try {
-        // this.eventId = (EventID)eventPart.getObject();
-        ByteBuffer eventIdPartsBuffer = ByteBuffer.wrap(eventPart
-            .getSerializedForm());
-        long threadId = EventID
-            .readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
-        long sequenceId = EventID
-            .readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
-        EventID eventId = new EventID(servConn.getEventMemberIDByteArray(),
-            threadId, sequenceId);
+      errMessage.append(putMsg);
+      writeErrorResponse(msg, MessageType.PUT_DATA_ERROR, errMessage.toString(), servConn);
+      servConn.setAsTrue(RESPONDED);
+      return;
+    }
 
-        try {
-          Object value = null;
-          if (!isDelta) {
-            value = valuePart.getSerializedForm();
-          } 
-          boolean isObject = valuePart.isObject();
-          boolean isMetaRegion = region.isUsedForMetaRegion();
-          msg.setMetaRegion(isMetaRegion);
-          AuthorizeRequest authzRequest = null;
-          if (!isMetaRegion) {
-            authzRequest = servConn.getAuthzRequest();
-          }
-          if (authzRequest != null) {
-            // TODO SW: This is to handle DynamicRegionFactory create
-            // calls. Rework this when the semantics of DynamicRegionFactory are
-            // cleaned up.
-            if (DynamicRegionFactory.regionIsDynamicRegionList(regionName)) {
-              authzRequest.createRegionAuthorize((String)key);
-            }
-            // Allow PUT operations on meta regions (bug #38961)
-            else {
-              PutOperationContext putContext = authzRequest.putAuthorize(
-                  regionName, key, value, isObject, callbackArg);
-              value = putContext.getValue();
-              isObject = putContext.isObject();
-              callbackArg = putContext.getCallbackArg();
-            }
-          }
-          // If the value is 1 byte and the byte represents null,
-          // attempt to create the entry. This test needs to be
-          // moved to DataSerializer or DataSerializer.NULL needs
-          // to be publicly accessible.
-          boolean result = false;
-          if (value == null && !isDelta) {
-            // Create the null entry. Since the value is null, the value of the
-            // isObject
-            // the true after null doesn't matter and is not used.
-            result = region.basicBridgeCreate(key, null, true, callbackArg,
-                servConn.getProxyID(), true, new EventIDHolder(eventId), false);
-          }
-          else {
-            // Put the entry
-            byte[] delta = null;
-            if (isDelta) {
-              delta = valuePart.getSerializedForm();              
-            }
-            result = region.basicBridgePut(key, value, delta, isObject,
-                callbackArg, servConn.getProxyID(), true, new EventIDHolder(eventId));
-          }
-          if (result) {
-            servConn.setModificationInfo(true, regionName, key);
-          }
-          else {
-            String message = servConn.getName()
-                + ": Failed to 6.1 put entry for region " + regionName
-                + " key " + key + " value " + valuePart;
-            if (isDebugEnabled) {
-              logger.debug(message);
-            }
-            throw new Exception(message);
-          }
-        }
-        catch (RegionDestroyedException rde) {
-          writeException(msg, rde, false, servConn);
-          servConn.setAsTrue(RESPONDED);
-          return;
-        }
-        catch (ResourceException re) {
-          writeException(msg, re, false, servConn);
-          servConn.setAsTrue(RESPONDED);
-          return;
-        }
-        catch (InvalidDeltaException ide) {
-          logger.info(LocalizedMessage.create(LocalizedStrings.UpdateOperation_ERROR_APPLYING_DELTA_FOR_KEY_0_OF_REGION_1, new Object[] { key, regionName }));
-          writeException(msg, MessageType.PUT_DELTA_ERROR, ide, false, servConn);
-          servConn.setAsTrue(RESPONDED);
-          region.getCachePerfStats().incDeltaFullValuesRequested();
-          return;
+    GeodeSecurityUtil.authorizeRegionWrite(regionName, key.toString());
 
-        }
-        catch (Exception ce) {
-          // If an interrupted exception is thrown , rethrow it
-          checkForInterrupt(servConn, ce);
+    // try {
+    // this.eventId = (EventID)eventPart.getObject();
+    ByteBuffer eventIdPartsBuffer = ByteBuffer.wrap(eventPart.getSerializedForm());
+    long threadId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
+    long sequenceId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
+    EventID eventId = new EventID(servConn.getEventMemberIDByteArray(), threadId, sequenceId);
 
-          // If an exception occurs during the put, preserve the connection
-          writeException(msg, ce, false, servConn);
-          servConn.setAsTrue(RESPONDED);
-          if (ce instanceof GemFireSecurityException) {
-            // Fine logging for security exceptions since these are already
-            // logged by the security logger
-            if (isDebugEnabled) {
-              logger.debug("{}: Unexpected Security exception", servConn.getName(), ce);
-            }
-          }
-          else if (isDebugEnabled) {
-            logger.debug("{}: Unexpected Exception", servConn.getName(), ce);
-          }
-          return;
+    try {
+      Object value = null;
+      if (!isDelta) {
+        value = valuePart.getSerializedForm();
+      }
+      boolean isObject = valuePart.isObject();
+      boolean isMetaRegion = region.isUsedForMetaRegion();
+      msg.setMetaRegion(isMetaRegion);
+      AuthorizeRequest authzRequest = null;
+      if (!isMetaRegion) {
+        authzRequest = servConn.getAuthzRequest();
+      }
+      if (authzRequest != null) {
+        // TODO SW: This is to handle DynamicRegionFactory create
+        // calls. Rework this when the semantics of DynamicRegionFactory are
+        // cleaned up.
+        if (DynamicRegionFactory.regionIsDynamicRegionList(regionName)) {
+          authzRequest.createRegionAuthorize((String) key);
         }
-        finally {
-          long oldStart = start;
-          start = DistributionStats.getStatTime();
-          stats.incProcessPutTime(start - oldStart);
+        // Allow PUT operations on meta regions (bug #38961)
+        else {
+          PutOperationContext putContext = authzRequest.putAuthorize(regionName, key, value, isObject, callbackArg);
+          value = putContext.getValue();
+          isObject = putContext.isObject();
+          callbackArg = putContext.getCallbackArg();
         }
-
-        // Increment statistics and write the reply
-        if (region instanceof PartitionedRegion) {
-          PartitionedRegion pr = (PartitionedRegion)region;
-          if (pr.isNetworkHop() != (byte)0) {
-            writeReplyWithRefreshMetadata(msg, servConn,pr,pr.isNetworkHop());
-            pr.setIsNetworkHop((byte)0);
-            pr.setMetadataVersion(Byte.valueOf((byte)0));
-          }
-          else {
-            writeReply(msg, servConn);
-          }
+      }
+      // If the value is 1 byte and the byte represents null,
+      // attempt to create the entry. This test needs to be
+      // moved to DataSerializer or DataSerializer.NULL needs
+      // to be publicly accessible.
+      boolean result = false;
+      if (value == null && !isDelta) {
+        // Create the null entry. Since the value is null, the value of the
+        // isObject
+        // the true after null doesn't matter and is not used.
+        result = region.basicBridgeCreate(key, null, true, callbackArg, servConn.getProxyID(), true, new EventIDHolder(eventId), false);
+      } else {
+        // Put the entry
+        byte[] delta = null;
+        if (isDelta) {
+          delta = valuePart.getSerializedForm();
         }
-        else {
-          writeReply(msg, servConn);
+        result = region.basicBridgePut(key, value, delta, isObject, callbackArg, servConn.getProxyID(), true, new EventIDHolder(eventId));
+      }
+      if (result) {
+        servConn.setModificationInfo(true, regionName, key);
+      } else {
+        String message = servConn.getName() + ": Failed to 6.1 put entry for region " + regionName + " key " + key + " value " + valuePart;
+        if (isDebugEnabled) {
+          logger.debug(message);
         }
-        servConn.setAsTrue(RESPONDED);
+        throw new Exception(message);
+      }
+    } catch (RegionDestroyedException rde) {
+      writeException(msg, rde, false, servConn);
+      servConn.setAsTrue(RESPONDED);
+      return;
+    } catch (ResourceException re) {
+      writeException(msg, re, false, servConn);
+      servConn.setAsTrue(RESPONDED);
+      return;
+    } catch (InvalidDeltaException ide) {
+      logger.info(LocalizedMessage.create(LocalizedStrings.UpdateOperation_ERROR_APPLYING_DELTA_FOR_KEY_0_OF_REGION_1, new Object[] {
+        key,
+        regionName
+      }));
+      writeException(msg, MessageType.PUT_DELTA_ERROR, ide, false, servConn);
+      servConn.setAsTrue(RESPONDED);
+      region.getCachePerfStats().incDeltaFullValuesRequested();
+      return;
+
+    } catch (Exception ce) {
+      // If an interrupted exception is thrown , rethrow it
+      checkForInterrupt(servConn, ce);
+
+      // If an exception occurs during the put, preserve the connection
+      writeException(msg, ce, false, servConn);
+      servConn.setAsTrue(RESPONDED);
+      if (ce instanceof GemFireSecurityException) {
+        // Fine logging for security exceptions since these are already
+        // logged by the security logger
         if (isDebugEnabled) {
-          logger.debug("{}: Sent 6.1 put response back to {} for region {} key {} value {}", servConn.getName(), servConn.getSocketString(), regionName, key, valuePart);
+          logger.debug("{}: Unexpected Security exception", servConn.getName(), ce);
         }
-        stats.incWritePutResponseTime(DistributionStats.getStatTime() - start);
+      } else if (isDebugEnabled) {
+        logger.debug("{}: Unexpected Exception", servConn.getName(), ce);
       }
+      return;
+    } finally {
+      long oldStart = start;
+      start = DistributionStats.getStatTime();
+      stats.incProcessPutTime(start - oldStart);
     }
 
+    // Increment statistics and write the reply
+    if (region instanceof PartitionedRegion) {
+      PartitionedRegion pr = (PartitionedRegion) region;
+      if (pr.isNetworkHop() != (byte) 0) {
+        writeReplyWithRefreshMetadata(msg, servConn, pr, pr.isNetworkHop());
+        pr.setIsNetworkHop((byte) 0);
+        pr.setMetadataVersion(Byte.valueOf((byte) 0));
+      } else {
+        writeReply(msg, servConn);
+      }
+    } else {
+      writeReply(msg, servConn);
+    }
+    servConn.setAsTrue(RESPONDED);
+    if (isDebugEnabled) {
+      logger.debug("{}: Sent 6.1 put response back to {} for region {} key {} value {}", servConn.getName(), servConn.getSocketString(), regionName, key, valuePart);
+    }
+    stats.incWritePutResponseTime(DistributionStats.getStatTime() - start);
   }
 
 }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/536c13bd/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/Put65.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/Put65.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/Put65.java
index 156fbbc..960958f 100755
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/Put65.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/Put65.java
@@ -209,6 +209,7 @@ public class Put65 extends BaseCommand {
       return;
     }
 
+    GeodeSecurityUtil.authorizeRegionWrite(regionName, key.toString());
 
     ByteBuffer eventIdPartsBuffer = ByteBuffer.wrap(eventPart.getSerializedForm());
     long threadId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
@@ -269,8 +270,6 @@ public class Put65 extends BaseCommand {
         logger.debug("processing put65 with operation={}", operation);
       }
 
-      GeodeSecurityUtil.authorizeRegionWrite(regionName, key.toString());
-
       // If the value is 1 byte and the byte represents null,
       // attempt to create the entry. This test needs to be
       // moved to DataSerializer or DataSerializer.NULL needs

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/536c13bd/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/PutAll.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/PutAll.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/PutAll.java
index 1f668e4..8b24f3e 100755
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/PutAll.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/PutAll.java
@@ -19,7 +19,18 @@
  */
 package com.gemstone.gemfire.internal.cache.tier.sockets.command;
 
+import java.io.IOException;
+import java.nio.ByteBuffer;
 import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import com.gemstone.gemfire.cache.DynamicRegionFactory;
+import com.gemstone.gemfire.cache.RegionDestroyedException;
+import com.gemstone.gemfire.cache.ResourceException;
+import com.gemstone.gemfire.cache.operations.PutAllOperationContext;
+import com.gemstone.gemfire.cache.operations.internal.UpdateOnlyMap;
+import com.gemstone.gemfire.distributed.internal.DistributionStats;
 import com.gemstone.gemfire.internal.cache.CachedDeserializableFactory;
 import com.gemstone.gemfire.internal.cache.EventID;
 import com.gemstone.gemfire.internal.cache.LocalRegion;
@@ -28,22 +39,16 @@ import com.gemstone.gemfire.internal.cache.PutAllPartialResultException;
 import com.gemstone.gemfire.internal.cache.tier.CachedRegionHelper;
 import com.gemstone.gemfire.internal.cache.tier.Command;
 import com.gemstone.gemfire.internal.cache.tier.MessageType;
-import com.gemstone.gemfire.internal.cache.tier.sockets.*;
+import com.gemstone.gemfire.internal.cache.tier.sockets.BaseCommand;
+import com.gemstone.gemfire.internal.cache.tier.sockets.CacheServerStats;
+import com.gemstone.gemfire.internal.cache.tier.sockets.Message;
+import com.gemstone.gemfire.internal.cache.tier.sockets.Part;
+import com.gemstone.gemfire.internal.cache.tier.sockets.ServerConnection;
 import com.gemstone.gemfire.internal.cache.versions.VersionTag;
 import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
 import com.gemstone.gemfire.internal.logging.log4j.LocalizedMessage;
 import com.gemstone.gemfire.internal.security.AuthorizeRequest;
-import com.gemstone.gemfire.cache.DynamicRegionFactory;
-import com.gemstone.gemfire.cache.RegionDestroyedException;
-import com.gemstone.gemfire.cache.ResourceException;
-import com.gemstone.gemfire.cache.operations.PutAllOperationContext;
-import com.gemstone.gemfire.cache.operations.internal.UpdateOnlyMap;
-import com.gemstone.gemfire.distributed.internal.DistributionStats;
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.util.LinkedHashMap;
-import java.util.Map;
+import com.gemstone.gemfire.internal.security.GeodeSecurityUtil;
 
 public class PutAll extends BaseCommand {
   
@@ -116,7 +121,9 @@ public class PutAll extends BaseCommand {
         servConn.setAsTrue(RESPONDED);
         return;
       }
-      
+
+      GeodeSecurityUtil.authorizeRegionWrite(regionName);
+
       // part 1: eventID
       eventPart = msg.getPart(1);
       ByteBuffer eventIdPartsBuffer = ByteBuffer.wrap(eventPart
@@ -194,22 +201,6 @@ public class PutAll extends BaseCommand {
             map = ((UpdateOnlyMap) map).getInternalMap();
           }
         }
-      } else {
-        // no auth, so update the map based on isObjectMap here
-        /*
-         Collection entries = map.entrySet();
-         Iterator iterator = entries.iterator();
-         Map.Entry mapEntry = null;
-         while (iterator.hasNext()) {
-         mapEntry = (Map.Entry)iterator.next();
-         Object currkey = mapEntry.getKey();
-         byte[] serializedValue = (byte[])mapEntry.getValue();
-         boolean isObject = ((Boolean)isObjectMap.get(currkey)).booleanValue();
-         if (isObject) {
-         map.put(currkey, CachedDeserializableFactory.create(serializedValue));
-         }
-         }
-         */
       }
       
       if (logger.isDebugEnabled()) {

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/536c13bd/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/PutAll70.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/PutAll70.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/PutAll70.java
index 4b13ecd..6e3aec9 100755
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/PutAll70.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/PutAll70.java
@@ -51,6 +51,7 @@ import com.gemstone.gemfire.internal.cache.versions.VersionTag;
 import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
 import com.gemstone.gemfire.internal.logging.log4j.LocalizedMessage;
 import com.gemstone.gemfire.internal.security.AuthorizeRequest;
+import com.gemstone.gemfire.internal.security.GeodeSecurityUtil;
 
 public class PutAll70 extends BaseCommand {
   
@@ -127,7 +128,9 @@ public class PutAll70 extends BaseCommand {
         servConn.setAsTrue(RESPONDED);
         return;
       }
-      
+
+      GeodeSecurityUtil.authorizeRegionWrite(regionName);
+
       // part 1: eventID
       eventPart = msg.getPart(1);
       ByteBuffer eventIdPartsBuffer = ByteBuffer.wrap(eventPart

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/536c13bd/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/PutAll80.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/PutAll80.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/PutAll80.java
index 0c2a86c..06512ac 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/PutAll80.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/PutAll80.java
@@ -134,6 +134,7 @@ public class PutAll80 extends BaseCommand {
         servConn.setAsTrue(RESPONDED);
         return;
       }
+
       LocalRegion region = (LocalRegion)crHelper.getRegion(regionName);
       if (region == null) {
         String reason = " was not found during putAll request";

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/536c13bd/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/RegisterInterest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/RegisterInterest.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/RegisterInterest.java
index 3cf4bf4..6381c7d 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/RegisterInterest.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/RegisterInterest.java
@@ -19,22 +19,28 @@
  */
 package com.gemstone.gemfire.internal.cache.tier.sockets.command;
 
+import java.io.IOException;
+
+import com.gemstone.gemfire.cache.DynamicRegionFactory;
+import com.gemstone.gemfire.cache.InterestResultPolicy;
+import com.gemstone.gemfire.cache.operations.RegisterInterestOperationContext;
+import com.gemstone.gemfire.i18n.StringId;
 import com.gemstone.gemfire.internal.cache.LocalRegion;
 import com.gemstone.gemfire.internal.cache.tier.CachedRegionHelper;
 import com.gemstone.gemfire.internal.cache.tier.Command;
+import com.gemstone.gemfire.internal.cache.tier.InterestType;
 import com.gemstone.gemfire.internal.cache.tier.MessageType;
-import com.gemstone.gemfire.internal.cache.tier.sockets.*;
+import com.gemstone.gemfire.internal.cache.tier.sockets.BaseCommand;
+import com.gemstone.gemfire.internal.cache.tier.sockets.CacheClientProxy;
+import com.gemstone.gemfire.internal.cache.tier.sockets.ChunkedMessage;
+import com.gemstone.gemfire.internal.cache.tier.sockets.Message;
+import com.gemstone.gemfire.internal.cache.tier.sockets.Part;
+import com.gemstone.gemfire.internal.cache.tier.sockets.ServerConnection;
 import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
 import com.gemstone.gemfire.internal.logging.log4j.LocalizedMessage;
 import com.gemstone.gemfire.internal.security.AuthorizeRequest;
-import com.gemstone.gemfire.cache.DynamicRegionFactory;
-import com.gemstone.gemfire.cache.InterestResultPolicy;
-import com.gemstone.gemfire.cache.operations.RegisterInterestOperationContext;
-import com.gemstone.gemfire.i18n.StringId;
 import com.gemstone.gemfire.internal.security.GeodeSecurityUtil;
 
-import java.io.IOException;
-
 public class RegisterInterest extends BaseCommand {
 
   private final static RegisterInterest singleton = new RegisterInterest();
@@ -120,19 +126,6 @@ public class RegisterInterest extends BaseCommand {
       logger.debug("{}: Received register interest request ({} bytes) from {} for region {} key {}", servConn.getName(), msg.getPayloadLength(), servConn.getSocketString(), regionName, key);
     }
     
-    /*
-    AcceptorImpl acceptor = servConn.getAcceptor();
-    
-    //  Check if the Server is running in NotifyBySubscription=true mode.
-    if (!acceptor.getCacheClientNotifier().getNotifyBySubscription()) {
-      // This should have been taken care at the client.
-      String err = LocalizedStrings.RegisterInterest_INTEREST_REGISTRATION_IS_SUPPORTED_ONLY_FOR_SERVERS_WITH_NOTIFYBYSUBSCRIPTION_SET_TO_TRUE.toLocalizedString() ;
-      writeChunkedErrorResponse(msg, MessageType.REGISTER_INTEREST_DATA_ERROR,
-          err, servConn);
-      servConn.setAsTrue(RESPONDED);  return;
-    }
-    */
-    
     // Process the register interest request
     if (key == null || regionName == null) {
       StringId message = null;
@@ -149,8 +142,13 @@ public class RegisterInterest extends BaseCommand {
       return;
     }
 
-    // TODO: add security changes here
-    GeodeSecurityUtil.authorizeRegionRead(regionName, key.toString());
+    if(interestType == InterestType.REGULAR_EXPRESSION) {
+      GeodeSecurityUtil.authorizeRegionRead(regionName);
+    }
+    else {
+      GeodeSecurityUtil.authorizeRegionRead(regionName, key.toString());
+    }
+
 
     // input key not null
     LocalRegion region = (LocalRegion)crHelper.getRegion(regionName);